name
stringlengths 1
64
| url
stringlengths 44
135
| author
stringlengths 3
30
| author_url
stringlengths 34
61
| likes_count
int64 0
33.2k
| kind
stringclasses 3
values | pine_version
int64 1
5
| license
stringclasses 3
values | source
stringlengths 177
279k
|
---|---|---|---|---|---|---|---|---|
Hobbiecode - RSI + Close previous day | https://www.tradingview.com/script/1rpeHDCL/ | hobbiecode | https://www.tradingview.com/u/hobbiecode/ | 211 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © hobbiecode
// If RSI(2) is less than 15, then enter at the close.
// Exit on close if today’s close is higher than yesterday’s high.
//@version=5
strategy("Hobbiecode - RSI + Close previous day", overlay=true)
// RSI parameters
rsi_period = 2
rsi_lower = 15
// Calculate RSI
rsi_val = ta.rsi(close, rsi_period)
// Check if RSI is lower than the defined threshold
if (rsi_val < rsi_lower)
strategy.entry("Buy", strategy.long)
// Check if today's close is higher than yesterday's high
if (strategy.position_size > 0 and close > ta.highest(high[1], 1))
strategy.close("Buy")
// Plot RSI on chart
plot(rsi_val, title="RSI", color=color.red)
hline(rsi_lower, title="Oversold Level", color=color.blue)
|
Monthly Strategy Performance Table | https://www.tradingview.com/script/aHwncfep-Monthly-Strategy-Performance-Table/ | ZenAndTheArtOfTrading | https://www.tradingview.com/u/ZenAndTheArtOfTrading/ | 304 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ZenAndTheArtOfTrading
// Version 2 (Last Updated 29th June, 2023)
// Huge thanks to Marc (https://www.tradingview.com/u/Mrcrbw/) for providing
// major improvements and fixes to the code that made this script much better!
// @version=5
//////////////////////////////////////////////////////////////////////////
// EXAMPLE STRATEGY (REPLACE THIS CODE WITH YOUR OWN) //
// Replace lines 15 -> 69 with your own strategy script code! //
// This example system is my Simple Pullback Strategy //
// Check my TradingView profile for more info about this script //
//////////////////////////////////////////////////////////////////////////
strategy("Monthly Performance Table",
overlay=true,
initial_capital=100000,
default_qty_type=strategy.percent_of_equity,
default_qty_value=100,
commission_type=strategy.commission.cash_per_contract,
commission_value=0.005)
// Get user input
i_ma1 = input.int(title="MA 1 Length", defval=200, step=10, group="Strategy Parameters", tooltip="Long-term MA")
i_ma2 = input.int(title="MA 2 Length", defval=10, step=10, group="Strategy Parameters", tooltip="Short-term MA")
i_stopPercent = input.float(title="Stop Loss Percent", defval=0.10, step=0.1, group="Strategy Parameters", tooltip="Failsafe Stop Loss Percent Decline")
i_lowerClose = input.bool(title="Exit On Lower Close", defval=false, group="Strategy Parameters", tooltip="Wait for a lower-close before exiting above MA2")
i_startTime = input.time(title="Start Filter", defval=timestamp("01 Jan 1995 13:30 +0000"), group="Time Filter", tooltip="Start date & time to begin searching for setups")
i_endTime = input.time(title="End Filter", defval=timestamp("1 Jan 2099 19:30 +0000"), group="Time Filter", tooltip="End date & time to stop searching for setups")
// Get indicator values
ma1 = ta.sma(close, i_ma1)
ma2 = ta.sma(close, i_ma2)
// Check filter(s)
f_dateFilter = time >= i_startTime and time <= i_endTime
// Check buy/sell conditions
var float buyPrice = 0
buyCondition = close > ma1 and close < ma2 and strategy.position_size == 0 and f_dateFilter
sellCondition = close > ma2 and strategy.position_size > 0 and (not i_lowerClose or close < low[1])
stopDistance = strategy.position_size > 0 ? ((buyPrice - close) / close) : na
stopPrice = strategy.position_size > 0 ? buyPrice - (buyPrice * i_stopPercent) : na
stopCondition = strategy.position_size > 0 and stopDistance > i_stopPercent
// Enter positions
if buyCondition
strategy.entry(id="Long", direction=strategy.long, comment="Equity = $" + str.tostring(strategy.equity, "#.##"))
if buyCondition[1]
buyPrice := strategy.position_avg_price
// Exit positions
if sellCondition or stopCondition
strategy.close(id="Long", comment="Exit" + (stopCondition ? "SL=true" : ""))
buyPrice := na
// Draw pretty colors
plot(buyPrice, color=color.lime, style=plot.style_linebr)
plot(stopPrice, color=color.red, style=plot.style_linebr, offset=-1)
plot(ma1, color=color.blue)
plot(ma2, color=color.orange)
////////////////////////////////////////////////////////////
// END EXAMPLE STRATEGY (REPLACE THIS CODE WITH YOUR OWN) //
////////////////////////////////////////////////////////////
//-------------------------------------------------------------------------//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MONTHLY TABLE based on the script written by QuantNomad - Copy & Paste code from here down into your strategy script /{
// Original Script: https://tradingview.com/script/kzp8e4X3-Monthly-Returns-in-PineScript-Strategies/ //
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var string GROUP_PERFORMANCE_TABLE = "Monthly Performance Table"
mptable_on = input.bool(title="Turn On |", defval=true, display=display.none, group=GROUP_PERFORMANCE_TABLE, inline="MPT_Toggles")
mptable_debug = input.bool(title="Debug Mode |", defval=false, display=display.none, group=GROUP_PERFORMANCE_TABLE, inline="MPT_Toggles")
mptable_precision = input.int(title="Decimal Precision", defval=2, minval=1, display=display.none, group=GROUP_PERFORMANCE_TABLE, inline="MPT_Toggles", tooltip="Decimal precision of each cell")
mptable_titleColor = input.color(title="Title Cell Color", defval=#cccccc, display=display.none, group=GROUP_PERFORMANCE_TABLE, inline="MPT_Colors")
mptable_titleTextColor = input.color(title="Title Text Color", defval=#363a45, display=display.none, group=GROUP_PERFORMANCE_TABLE, inline="MPT_Colors")
mptable_textColor = input.color(title="Cell Text Color", defval=color.white, display=display.none, group=GROUP_PERFORMANCE_TABLE, inline="MPT_Colors")
mptable_ProfitColor = input.color(title="Year Profit Color", defval=color.new(color.green, 50), display=display.none, group=GROUP_PERFORMANCE_TABLE, inline="MPT_Colors")
mptable_LossColor = input.color(title="Year Loss Color", defval=color.new(color.red, 50), display=display.none, group=GROUP_PERFORMANCE_TABLE, inline="MPT_Colors")
mptable_BreakEvenColor = input.color(title="Year B/E Color", defval=color.new(color.white, 50), display=display.none, group=GROUP_PERFORMANCE_TABLE, inline="MPT_Colors")
mptable_pageNumber = input.int(title="Page Number", defval=1, minval=1, step=1, maxval=10, display=display.none, group=GROUP_PERFORMANCE_TABLE, tooltip="Which page of results to display") - 1 // -1 is for corection for arrays. Aaray index start with 0
mptable_pageSize = input.int(title="Page Size (Rows)", defval=20, minval=1, display=display.none, group=GROUP_PERFORMANCE_TABLE, tooltip="How many rows to display") - 1 // 9 is used to show 10 rows of data due to array start from 0
mptable_tableTextSize = input.string(title="Text Size", defval="Small", options=["Auto", "Huge", "Large", "Normal", "Small", "Tiny"], display=display.none, group=GROUP_PERFORMANCE_TABLE)
// Custom function for getting table text sized based on user input
table_text_size(_size) =>
switch _size
"Auto" => size.auto
"Huge" => size.huge
"Large" => size.large
"Normal" => size.normal
"Small" => size.small
=> size.tiny
tableTextSize = table_text_size(mptable_tableTextSize)
// Custom function for getting decimal precision based on given number
// (eg. if number is > 0 but < 0.05 or < 0 and > -0.05, set precision to 3 to avoid rounding to 0 which is misleading)
GetRoundingPrecision(float num) =>
if (num > 0 and num < 0.05) or (num < 0 and num > -0.05)
3
else
mptable_precision
// Define an open trade's cost (used to calculate commission cost)
type TradeCost
int entryTime
float entryPrice
float cost
// Define a monthly/yearly return type
type StrategyReturn
float profit
float drawdown
float peak
int timestamp
// Store accumulated P&L values
var float accumulatedMonthlyPL = 0
var float accumulatedYearlyPL = 0
var float bestAccumulatedMonthlyPL = 0
var float bestAccumulatedYearlyPL = 0
// Store drawdown values
var float equityPeak = strategy.initial_capital
var float yearlyEquityHigh = 0
var float currentYearlyDrawdown = 0
var float yearlyMaxDrawdown = 0
var float worstDrawdown = 0
var float monthlyEquityHigh = 0
var float currentMonthlyDrawdown = 0
var float monthlyMaxDrawdown = 0
var int currentDrawdownBars = 0
var int maxDrawdownBars = 0
// Store stat arrays
var totalDrawdownBars = array.new<int>(0)
var totalDrawdowns = array.new<float>(0)
// Store long & short trade count
var int totalBreakEvenTrades = 0
var int totalLongTrades = 0
var int totalLongTradeWins = 0
var int totalShortTrades = 0
var int totalShortTradeWins = 0
// Store open trade commission costs in array
var costOfOpenTrades = array.new<TradeCost>(0)
// Detect opened trade and save cost of trade (I tried many methods to get my numbers to match the Cumulative Profit list in the Strategy Tester, no idea why, but none of them worked without doing this)
if strategy.opentrades != strategy.opentrades[1] and strategy.closedtrades == strategy.closedtrades[1]
costOfTrade = strategy.grossloss - strategy.grossloss[1]
costOfOpenTrades.push(TradeCost.new(strategy.opentrades.entry_time(strategy.opentrades - 1), strategy.opentrades.entry_price(strategy.opentrades - 1), costOfTrade))
// Detect a closed trade
// TV Documentation: Trade List's Cumulative Profit % Formula = TradeProfit / (InitialCapital + Cumulative Profit of the previous trades) * 100%
if strategy.closedtrades != strategy.closedtrades[1]
// Retrieve trade cost for the closed trade
float tradeCost = 0
int removeIdx = -1
if costOfOpenTrades.size() > 0
for i = 0 to costOfOpenTrades.size() - 1
TradeCost tc = costOfOpenTrades.get(i)
if tc.entryTime == strategy.closedtrades.entry_time(strategy.closedtrades - 1) and tc.entryPrice == strategy.closedtrades.entry_price(strategy.closedtrades - 1)
tradeCost := tc.cost
removeIdx := i
break
// Remove cost
if removeIdx != -1
costOfOpenTrades.remove(removeIdx)
// Calculate equity before trade closed (strategy.equity will not do, because it changes bar-by-bar based on open P&L not realized P&L)
float preEquity = strategy.initial_capital + strategy.netprofit[1]
// Calculate P&L + cost of this trade
float profitLoss = 0
if strategy.losstrades > strategy.losstrades[1]
profitLoss := (strategy.grossloss - (strategy.grossloss[1] - tradeCost)) * -1
else
profitLoss := strategy.grossprofit - strategy.grossprofit[1]
// Check if this was a long or short trade and if it won or lost
if strategy.position_size[1] > 0
totalLongTrades := totalLongTrades + 1
if profitLoss > 0
totalLongTradeWins := totalLongTradeWins + 1
else if strategy.position_size[1] < 0
totalShortTrades := totalShortTrades + 1
if profitLoss > 0
totalShortTradeWins := totalShortTradeWins + 1
// Check if the trade broke even
if profitLoss == 0
totalBreakEvenTrades := totalBreakEvenTrades + 1
// Calculate cumulative profit % for this trade
float cumulativeProfitPercent = (profitLoss / preEquity) * 100
// Store highest peak value of equity (we can now use strategy.equity since equity has updated to realized P&L on this bar)
if strategy.equity > equityPeak
equityPeak := strategy.equity
// Calculate total system drawdown %
float equityDD = ((strategy.equity - equityPeak) / equityPeak) * 100
if equityDD < worstDrawdown
worstDrawdown := equityDD
// Store accumulated monthly + yearly P&L
accumulatedMonthlyPL := cumulativeProfitPercent + accumulatedMonthlyPL[1]
accumulatedYearlyPL := accumulatedYearlyPL + cumulativeProfitPercent
// Save max favourable excursion for this month (ie. peak return as %)
if accumulatedMonthlyPL > bestAccumulatedMonthlyPL
bestAccumulatedMonthlyPL := accumulatedMonthlyPL
// Save max favourable excursion for this year (ie. peak return as %)
if accumulatedYearlyPL > bestAccumulatedYearlyPL
bestAccumulatedYearlyPL := accumulatedYearlyPL
// Track max equity high over current year for max yearly drawdown calculation
if accumulatedYearlyPL > yearlyEquityHigh
yearlyEquityHigh := accumulatedYearlyPL
// Check if our yearly realized equity high minus current realized equity exceeds our stored max drawdown for the year, update if necessary, and save worst drawdown
if accumulatedYearlyPL - yearlyEquityHigh < 0
currentYearlyDrawdown := accumulatedYearlyPL - yearlyEquityHigh
if currentYearlyDrawdown < yearlyMaxDrawdown
yearlyMaxDrawdown := currentYearlyDrawdown
currentDrawdownBars := currentDrawdownBars + 1
// Track max equity high over current month for max monthly drawdown calculation
if accumulatedMonthlyPL > monthlyEquityHigh
monthlyEquityHigh := accumulatedMonthlyPL
// Check if our monthly realized equity high minus current realized equity exceeds our stored max drawdown for the month, update if necessary, and save worst drawdown
if accumulatedMonthlyPL - monthlyEquityHigh < 0
currentMonthlyDrawdown := accumulatedMonthlyPL - monthlyEquityHigh
if currentMonthlyDrawdown < monthlyMaxDrawdown
monthlyMaxDrawdown := currentMonthlyDrawdown
// Debug label
if mptable_debug
string debugTip = "Equity = $" + str.tostring(strategy.equity, "#.##") +
"\nP&L=" + str.tostring(cumulativeProfitPercent) + "%" +
"\nAccumMonthlyP&L=" + str.tostring(math.round(accumulatedMonthlyPL, GetRoundingPrecision(accumulatedMonthlyPL))) + "%" +
"\nAccumYearlyP&L=" + str.tostring(math.round(accumulatedYearlyPL, GetRoundingPrecision(accumulatedYearlyPL))) + "%" +
"\nMonthlyMaxDD=" + str.tostring(math.round(monthlyMaxDrawdown, GetRoundingPrecision(monthlyMaxDrawdown))) + "%" +
"\nYearlyMaxDD=" + str.tostring(math.round(yearlyMaxDrawdown, GetRoundingPrecision(yearlyMaxDrawdown))) + "%" +
"\nTotalMaxDD=" + str.tostring(math.round(worstDrawdown, GetRoundingPrecision(worstDrawdown))) + "%" +
"\nCurrentDDBars=" + str.tostring(currentDrawdownBars) +
"\nMaxDDBars=" + str.tostring(maxDrawdownBars) +
"\nTotalBreakEven=" + str.tostring(totalBreakEvenTrades) +
"\nTotalLongs=" + str.tostring(totalLongTrades) +
"\nTotalLongWins=" + str.tostring(totalLongTradeWins) +
"\nTotalShorts=" + str.tostring(totalShortTrades) +
"\nTotalShortWins=" + str.tostring(totalShortTradeWins)
label.new(bar_index, high + (high * 0.01), "P&L " + str.tostring(math.round(cumulativeProfitPercent, GetRoundingPrecision(cumulativeProfitPercent))) + "%", tooltip=debugTip, textcolor=color.white)
// Calculate drawdown since last equity high (NOT max drawdown, just the current max DD since we were out of DD)
float t_equityDD = ((strategy.equity - equityPeak) / equityPeak) * 100
var float currentMaxDrawdownSinceLast = 0
// Update Max Drawdown bar count and current DD if equity is under water, check isconfirmed to prevent double-counting bars with recalc_on_order_fills on
if strategy.equity < equityPeak and barstate.isconfirmed
currentDrawdownBars := currentDrawdownBars + 1
if currentDrawdownBars > maxDrawdownBars
maxDrawdownBars := currentDrawdownBars
if t_equityDD < currentMaxDrawdownSinceLast
currentMaxDrawdownSinceLast := t_equityDD
else
if currentDrawdownBars > 0
totalDrawdownBars.push(currentDrawdownBars)
totalDrawdowns.push(currentMaxDrawdownSinceLast)
currentDrawdownBars := 0
currentMaxDrawdownSinceLast := 0
// Prepare arrays to store Yearly and Monthly P&Ls
var monthlyReturns = array.new<StrategyReturn>(0)
var yearlyReturns = array.new<StrategyReturn>(0)
var bool firstEntryTime = false
// Retrieve entry time of initial entry in open position
if not firstEntryTime and strategy.opentrades.entry_time(0)
firstEntryTime := true
// Detect new month and year
new_month = month(time) != month(time[1])
new_year = year(time) != year(time[1])
// Detect a new month and store its return profile
if not barstate.isfirst and new_month and firstEntryTime or barstate.islastconfirmedhistory
StrategyReturn mr = StrategyReturn.new(accumulatedMonthlyPL, monthlyMaxDrawdown, bestAccumulatedMonthlyPL, time[1]) // time)
monthlyReturns.push(mr)
accumulatedMonthlyPL := 0
monthlyMaxDrawdown := 0
monthlyEquityHigh := 0
currentMonthlyDrawdown := 0
bestAccumulatedMonthlyPL := 0
// Detect a new year and reset tracking variables
if not barstate.isfirst and new_year and firstEntryTime or barstate.islastconfirmedhistory
StrategyReturn yr = StrategyReturn.new(accumulatedYearlyPL, yearlyMaxDrawdown, bestAccumulatedYearlyPL, time[1])
yearlyReturns.push(yr)
accumulatedYearlyPL := 0
yearlyMaxDrawdown := 0
yearlyEquityHigh := 0
currentYearlyDrawdown := 0
bestAccumulatedYearlyPL := 0
// DEBUG code
bgcolor(mptable_debug and new_month ? color.lime : na, title="New Month", display=display.none)
bgcolor(mptable_debug and new_year ? color.red : na, title="New Year", display=display.none)
// END DEBUG CODE
// Define Monthly P&L Table
var table performance_table = table(na)
//Adjust mptable_pageSize if the years are less than the mptable_pageSize
if yearlyReturns.size() < mptable_pageSize
mptable_pageSize := yearlyReturns.size()
// Caluclate the start and end of page to display
startIndex = math.max(math.min(yearlyReturns.size() - 1, yearlyReturns.size() - 1 - (mptable_pageSize + 1) * mptable_pageNumber), mptable_pageSize - 1)
endIndex = math.max(startIndex - mptable_pageSize, 0)
mptable_pageSize := endIndex <= mptable_pageSize ? endIndex : mptable_pageSize
// If this is the last bar on our chart, display the performance table
var int EXTRA_STAT_ROWS = 5 // This ensures table includes enough rows for CAGR etc
if mptable_on and monthlyReturns.size() > 0 and barstate.islastconfirmedhistory
// Create table (100 rows = 100 years of data, should be plenty for all markets!)
performance_table := table.new(position.bottom_right, columns=17, rows=yearlyReturns.size() + EXTRA_STAT_ROWS, border_width=1)
// Set column headers
performance_table.cell(0, 0, "Year", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)
performance_table.cell(1, 0, "Jan", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)
performance_table.cell(2, 0, "Feb", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)
performance_table.cell(3, 0, "Mar", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)
performance_table.cell(4, 0, "Apr", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)
performance_table.cell(5, 0, "May", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)
performance_table.cell(6, 0, "Jun", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)
performance_table.cell(7, 0, "Jul", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)
performance_table.cell(8, 0, "Aug", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)
performance_table.cell(9, 0, "Sep", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)
performance_table.cell(10, 0, "Oct", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)
performance_table.cell(11, 0, "Nov", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)
performance_table.cell(12, 0, "Dec", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)
performance_table.cell(13, 0, "TOTAL", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)
performance_table.cell(14, 0, "MaxDD", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)
// Set yearly values
for year_index = startIndex to yearlyReturns.size() == 0 ? na : endIndex
// Get yearly return for this loop, set year number in first column, determine color of cell
StrategyReturn yearlyReturn = yearlyReturns.get(year_index)
// Set year title and determine color
performance_table.cell(0, year_index + 1, str.tostring(year(yearlyReturn.timestamp)), bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)
color y_color = yearlyReturn.profit > 0 ? mptable_ProfitColor : yearlyReturn.profit == 0 ? mptable_BreakEvenColor : mptable_LossColor
// Populate yearly cell values
string yearlyTip = "MaxDD: " + str.tostring(math.round(yearlyReturn.drawdown, GetRoundingPrecision(yearlyReturn.drawdown))) + "%" +
"\nMFE: " + str.tostring(math.round(yearlyReturn.peak, GetRoundingPrecision(yearlyReturn.peak))) + "%"
performance_table.cell(13, year_index + 1, (yearlyReturn.profit > 0 ? "+" : "") + str.tostring(math.round(yearlyReturn.profit, GetRoundingPrecision(yearlyReturn.profit))) + "%", bgcolor=y_color, text_color=color.white, text_size=tableTextSize, tooltip=yearlyTip)
performance_table.cell(14, year_index + 1, str.tostring(math.round(yearlyReturn.drawdown, GetRoundingPrecision(yearlyReturn.drawdown))) + "%", bgcolor=mptable_BreakEvenColor, text_color=color.white, text_size=tableTextSize)
// Set monthly values
for month_index = 0 to monthlyReturns.size() - 1
// Get monthly return for this loop, get current year for this loop, then calculate the corresponding table column and row
StrategyReturn monthlyReturn = monthlyReturns.get(month_index)
int yearOfMonth = year(monthlyReturn.timestamp)
int monthCol = month(monthlyReturn.timestamp)
// populate monthly profit only if the years of the yearly return match with the monthly return.
if yearOfMonth == year(yearlyReturn.timestamp)
// Determine color for monthly P&L
color m_color = monthlyReturn.profit > 0 ? color.new(mptable_ProfitColor, color.t(mptable_ProfitColor) + 20) : monthlyReturn.profit == 0 ? color.new(mptable_BreakEvenColor, color.t(mptable_BreakEvenColor) + 20) : color.new(mptable_LossColor, color.t(mptable_LossColor) + 20)
// Set monthly P&L cell
string monthlyTip = "MaxDD: " + str.tostring(math.round(monthlyReturn.drawdown, GetRoundingPrecision(monthlyReturn.drawdown))) + "%" +
"\nMFE: " + str.tostring(math.round(monthlyReturn.peak, GetRoundingPrecision(monthlyReturn.peak))) + "%"
performance_table.cell(monthCol, year_index + 1, str.tostring(math.round(monthlyReturn.profit, GetRoundingPrecision(monthlyReturn.profit))), bgcolor=m_color, text_color=color.white, text_size=tableTextSize, tooltip=monthlyTip)
float percentReturn = (strategy.netprofit / strategy.initial_capital) * 100
float cagr = (math.pow((strategy.netprofit + strategy.initial_capital) / strategy.initial_capital, 1 / yearlyReturns.size()) - 1) * 100
float mar = cagr / math.abs(worstDrawdown)
lastMonthRowIndex = startIndex < 5 ? 5 : startIndex
// Populate table data
float totalWinRate = (strategy.wintrades / strategy.closedtrades) * 100
float longWinRate = nz((totalLongTradeWins / totalLongTrades) * 100)
float shortWinRate = nz((totalShortTradeWins / totalShortTrades) * 100)
string returnTip = "Based on a total of " + str.tostring(strategy.closedtrades) + " trades" +
"\nWin Rate = " + str.tostring(math.round(totalWinRate, GetRoundingPrecision(totalWinRate))) + "%" +
"\nLong Trades = " + str.tostring(totalLongTrades) + " (Win " + str.tostring(math.round(longWinRate, GetRoundingPrecision(longWinRate))) + "%)" +
"\nShort Trades = " + str.tostring(totalShortTrades) + " (Win " + str.tostring(math.round(shortWinRate, GetRoundingPrecision(shortWinRate))) + "%)"
performance_table.cell(15, lastMonthRowIndex, "Return: " + (percentReturn > 0 ? "+" : "") + str.tostring(math.round(percentReturn, GetRoundingPrecision(percentReturn))) + "%", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_font_family=font.family_monospace, text_size=tableTextSize, tooltip=returnTip)
performance_table.cell(15, lastMonthRowIndex - 1, "MAR: " + str.tostring(mar, "#.##"), bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_font_family=font.family_monospace, text_size=tableTextSize, tooltip="Measure of return adjusted for risk: CAGR divided by Max Drawdown. Indicates how comfortable the system might be to trade. Higher than 0.5 is ideal, 1.0 and above is very good, and anything 3.0 or above should be considered suspicious.")
performance_table.cell(15, lastMonthRowIndex - 2, "DD Bars: " + str.tostring(maxDrawdownBars), bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_font_family=font.family_monospace, text_size=tableTextSize, tooltip="Average Drawdown Bars: " + str.tostring(totalDrawdownBars.avg(), "#.#") + "\n\nThis is how many bars it took to recover the longest drawdown (note: this is different to the MAX drawdown, and represents time drawdown)")
performance_table.cell(15, lastMonthRowIndex - 3, "MaxDD: " + str.tostring(math.round(worstDrawdown, GetRoundingPrecision(worstDrawdown))) + "%", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_font_family=font.family_monospace, text_size=tableTextSize, tooltip="Average Drawdown: " + str.tostring(totalDrawdowns.avg(), "#.##") + "%\n\nThis number is different to the Strategy Tester because this number is based on closed trade equity while the Tester's MaxDD is based on open equity.")
performance_table.cell(15, lastMonthRowIndex - 4, "CAGR: " + (cagr > 0 ? "+" : "") + str.tostring(math.round(cagr, GetRoundingPrecision(cagr))) + "%", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_font_family=font.family_monospace, text_size=tableTextSize, tooltip="Compounded annual growth rate")
performance_table.cell(15, lastMonthRowIndex - 5, "REALIZED P&L", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_font_family=font.family_monospace, text_size=tableTextSize, tooltip="These numbers are based on Realized equity (closed trades)")
// } END MONTHLY TABLE
/////////// END OF PERFORMANCE TABLE CODE. /////////// |
Volatility Breakout Strategy [Angel Algo] | https://www.tradingview.com/script/fgwTwNJM-Volatility-Breakout-Strategy-Angel-Algo/ | AngelAlgo | https://www.tradingview.com/u/AngelAlgo/ | 215 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
strategy("Volatility Breakout Strategy [Angel Algo]", overlay = true)
// Inputs
length = input(title="Length", defval=20)
// Calculate the average true range (ATR)
atr = ta.atr(length)
// Plot the ATR on the chart
plot(atr, color=color.blue, linewidth=2, title="ATR")
// Calculate the upper and lower breakouts
upper_breakout = high + atr
lower_breakout = low - atr
// Plot the upper and lower breakouts on the chart
ul = plot(upper_breakout[1], color = color.new(color.green, 100), linewidth=2, title="Upper Breakout Level")
ll = plot(lower_breakout[1], color = color.new(color.red, 100), linewidth=2, title="Lower Breakout Level")
// Create the signals
long_entry = ta.crossover(close, upper_breakout[1]) and barstate.isconfirmed
short_entry = ta.crossunder(close, lower_breakout[1]) and barstate.isconfirmed
active_signal_color =ta.barssince(long_entry) < ta.barssince(short_entry) ?
color.new(color.green,85) : color.new(color.red,85)
// Plot the signals on the chart
plotshape(long_entry and ta.barssince(long_entry[1]) > ta.barssince(short_entry[1]), location=location.belowbar, style=shape.triangleup,
color=color.green, size=size.normal, text = "Bullish breakout", textcolor = color.green)
plotshape(short_entry and ta.barssince(long_entry[1]) < ta.barssince(short_entry[1]), location=location.abovebar, style=shape.triangledown,
color=color.red, size=size.normal,text = "Bearish breakout", textcolor = color.red)
// Fill the space between the upper and lower levels with the color that indicates the latest signal direction
fill(ul,ll, color=active_signal_color)
long_condition = long_entry and strategy.position_size <= 0 and barstate.isconfirmed
short_condition = short_entry and strategy.position_size >= 0 and barstate.isconfirmed
if long_condition
strategy.entry("Volatility Breakout Long", strategy.long)
if short_condition
strategy.entry("Volatility Breakout Short", strategy.short)
|
Stochastic RSI Strategy (with SMA and VWAP Filters) | https://www.tradingview.com/script/06wt9GNj-Stochastic-RSI-Strategy-with-SMA-and-VWAP-Filters/ | thedoggwalker | https://www.tradingview.com/u/thedoggwalker/ | 64 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © thedoggwalker
//@version=4
strategy("Stochastic RSI Strategy", overlay=true)
// Stochastic RSI
length = input(14, title="Length")
src = input(close, title="Source")
smoothK = input(3, title="K")
smoothD = input(3, title="D")
rsiValue = rsi(src, length)
highestRSI = highest(rsiValue, length)
lowestRSI = lowest(rsiValue, length)
k = (rsiValue - lowestRSI) / (highestRSI - lowestRSI) * 100
d = sma(k, smoothD)
// Moving averages
maShort = sma(close, 9)
maLong = sma(close, 21)
// Spread between moving averages
spread = maShort - maLong
// VWAP
vwapValue = vwap(hlc3)
// Entry conditions
longCondition = crossover(k, 30) and spread > 0 and close < vwapValue
shortCondition = crossunder(k, 70) and spread < 0 and close > vwapValue
// Entry orders
if (longCondition)
strategy.entry("Long", strategy.long)
if (shortCondition)
strategy.entry("Short", strategy.short)
// Exit orders
longStopLoss = close - 20 * syminfo.mintick
longTakeProfit = close + 25 * syminfo.mintick
strategy.exit("Exit Long", "Long", stop=longStopLoss, limit=longTakeProfit)
shortStopLoss = close + 20 * syminfo.mintick
shortTakeProfit = close - 25 * syminfo.mintick
strategy.exit("Exit Short", "Short", stop=shortStopLoss, limit=shortTakeProfit) |
FRAMA & CPMA Strategy [CSM] | https://www.tradingview.com/script/TbHmRsax-FRAMA-CPMA-Strategy-CSM/ | chhagansinghmeena | https://www.tradingview.com/u/chhagansinghmeena/ | 313 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © chhagansinghmeena
//@version=5
strategy("FRAMA & CPMA Strategy [CSM]", shorttitle = "CSM's => FRAMA + CPMA", overlay=true, margin_long=100, margin_short=100)
import chhagansinghmeena/BankNifty_CSM/3 as CM
src = input.source(title = "FRAMA Source", defval = close, group = "Requirements")
length = input.int(title='FRAMA Length', defval=21, minval=1, maxval=200, group = "Requirements")
fracDim = input.float(title='Fractal Dimension', defval=0.8, minval=0.1, maxval=2.0, group = "Requirements")
CPMA_length = input.int(title='CPMA Length', defval=21, minval=1, maxval=200, group = "Requirements")
enableEngulfingFilter = input.bool(title = "Enable Engulfing Candle Filter", defval = false, group = "Requirements")
longTakeProfit = input.float(10, 'Long Take Profit Amount', minval=0.05, step=0.05,group = "Stoploss/Target")
shortTakeProfit = input.float(10, 'Short Take Profit Amount', minval=0.05, step=0.05,group = "Stoploss/Target")
trailingTakeProfit = input.float(0.5, 'Trailing Take Profit Amount', minval=0.01, maxval=100, step=0.01,group = "Stoploss/Target")
LossstratA = input.float(defval=100, minval=0, maxval=10000, title="Stop Loss", step=5,group="Stoploss/Target")
start = input.time(title='Start Date', defval=timestamp('01 Jan 2023 03:30 +0000'), group='Backtesting', tooltip='Date & time to begin trading from')
finish = input.time(title='End Date', defval=timestamp('1 Jan 2099 15:30 +0000'), group='Backtesting', tooltip='Date & time to stop trading')
window() =>
time >= start and time <= finish ? true : false
// Get various price types
[Open, price, High, Low , HL2, HLC3, HLCC4, OHLC4 ] = request.security(syminfo.tickerid, timeframe.period, [open, close, high, low, hl2, hlc3, hlcc4, ohlc4])
//Get CPMA from Library
CPMA = CM.CSM_CPMA(length = CPMA_length, price = price, HL2 = HL2, Open = Open , High = High, Low = Low, OHLC4 = OHLC4, HLC3 = HLC3, HLCC4 = HLCC4)
//Get FRAMA from Library
FRAMA = CM.frama_Calculation(src = src, length = length, mult = fracDim)
plot(CPMA, color=color.orange, linewidth=2, title="CPMA")
plot(FRAMA, color=color.blue, linewidth=2, title="FRAMA")
// Detect bullish and bearish engulfing patterns
bullishEngulfing = CM.candlepatternbullish()
bearishEngulfing = CM.candlepatternbearish()
longCondition = (ta.cross(close, FRAMA) and close > FRAMA) or (ta.cross(close, CPMA) and close > CPMA )
shortCondition = (ta.cross(close, FRAMA) and close < FRAMA) or (ta.cross(close, CPMA) and close < CPMA)
Signal = 0
if enableEngulfingFilter
longCondition := bullishEngulfing and (longCondition or ta.crossover(FRAMA, CPMA))
shortCondition := bearishEngulfing and (shortCondition or ta.crossunder(FRAMA, CPMA))
else
Signal := longCondition ? 1 : shortCondition ? -1 : nz(Signal[1])
isDifferentSignalType = ta.change(Signal)
longCondition := longCondition and isDifferentSignalType
shortCondition := shortCondition and isDifferentSignalType
longTakeProfitPerc = longTakeProfit/close
shortTakeProfitPerc = shortTakeProfit/close
trailingTakeProfitPerc = trailingTakeProfit == 0.01 ? syminfo.mintick/close : trailingTakeProfit/close
bool longIsActive = longCondition or strategy.position_size > 0
bool shortIsActive = shortCondition or strategy.position_size < 0
longIsActive := longCondition or strategy.position_size > 0
shortIsActive := shortCondition or strategy.position_size < 0
//Long Stop Loss added
float longStopLossprice = na
longStopLossprice := if longIsActive
if longCondition and not (strategy.opentrades.size(strategy.opentrades - 1) > 0)
low - LossstratA
else
nz(longStopLossprice[1], low - LossstratA)
else
na
//Long Take Profir Added
float longTakeProfitPrice = na
longTakeProfitPrice := if longIsActive
if longCondition and not (strategy.position_size > 0)
close * (1 + longTakeProfitPerc)
else
nz(longTakeProfitPrice[1], high * (1 - longTakeProfitPerc))
else
na
//Short StopLoss added
float shortStopLossprice = na
shortStopLossprice := if shortIsActive
if shortCondition and not (strategy.position_size < 0)
high + LossstratA
else
nz(shortStopLossprice[1], high + LossstratA)
else
na
//Short Take profit added
float shortTakeProfitPrice = na
shortTakeProfitPrice := if shortIsActive
if shortCondition and not (strategy.position_size < 0)
close * (1 - shortTakeProfitPerc)
else
nz(shortTakeProfitPrice[1], close * (1 - shortTakeProfitPrice))
else
na
float longTrailingTakeProfitStepTicks = longTakeProfitPrice * trailingTakeProfitPerc / syminfo.mintick
float shortTrailingTakeProfitStepTicks = shortTakeProfitPrice * trailingTakeProfitPerc / syminfo.mintick
if window()
switch
longCondition=> strategy.entry("Long",strategy.long)
shortCondition=> strategy.entry("Short", strategy.short)
strategy.exit(id = 'Long TP/SL', from_entry = 'Long', trail_price = longTakeProfitPrice , trail_offset = longTrailingTakeProfitStepTicks, stop = longStopLossprice)
strategy.exit(id = 'Short TP/SL', from_entry = 'Short', trail_price = shortTakeProfitPrice, trail_offset = shortTrailingTakeProfitStepTicks, stop = shortStopLossprice) |
Break even stop loss (% of instrument price) | https://www.tradingview.com/script/bdrABiYK-Break-even-stop-loss-of-instrument-price/ | osmaras | https://www.tradingview.com/u/osmaras/ | 30 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © osmaras
// based on https://kodify.net/tradingview/orders/percentage-trail/
//@version=5
strategy("Break even stop loss (% of instrument price)", overlay=true)
// Configure trail stop level with input options (optional)
longTrailPerc = input.float(defval=3.0,step=0.1,title="Trail Long Loss (%)")* 0.01
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
// Determine trail stop loss prices
longStopPrice = 0.0
lastEntryPrice = strategy.opentrades.entry_price(strategy.opentrades - 1)
longStopPrice := if (strategy.position_size > 0 and close > (lastEntryPrice * (1 + longTrailPerc)))
stopValue = lastEntryPrice
math.max(stopValue, longStopPrice[1])
else
longStopPrice := if (strategy.position_size > 0)
stopValue = lastEntryPrice * (1 - longTrailPerc)
math.max(stopValue, longStopPrice[1])
else
0
// Plot stop loss values for confirmation
plot(series=(strategy.position_size > 0) ? longStopPrice : na,
color=color.fuchsia, style=plot.style_cross,
linewidth=2, title="Long Trail Stop")
// set strategy only long
strategy.risk.allow_entry_in(strategy.direction.long)
// Submit entry orders
if (longCondition)
strategy.entry("Long", strategy.long)
shortCondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))
if (shortCondition)
strategy.close("Long")
// Submit exit orders for trail stop loss price
if (strategy.position_size > 0)
strategy.exit(id="Stop Loss", stop=longStopPrice)
|
Slight Swing Momentum Strategy. | https://www.tradingview.com/script/6l9kcw7j/ | fzj20020403 | https://www.tradingview.com/u/fzj20020403/ | 78 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © fzj20020403
//@version=5
strategy("Slight Swing Momentum Strategy.", overlay=true)
// Position Status Definition
var inPosition = false
// Moving Average Definition
ma60 = ta.sma(close, 60)
// A1 Condition Definition
A1 = high / close < 1.03 and open / low < 1.03 and high / close[1] > 1.06
// A2 Condition Definition
A2 = close / open > 1.05 or close / close[1] > 1.05
// A3 Condition Definition
highestVol = ta.highest(volume, 60)
A3 = ta.crossover(volume, highestVol[1])
// B1 Condition Definition
ema5 = ta.ema(close, 5)
B1 = close / ema5
// XG Condition Definition
A1andA2 = (A1 and A2) and (A1[1] and A2[1])
XG = ta.crossover(B1, ta.sma(B1, 9))
// Weekly Trend Factor Definition
weeklyMa = ta.sma(close, 50)
weeklySlope = (weeklyMa - weeklyMa[4]) / 4 > 0
// Buy Signal using XG Condition
buySignal = A1 and close > ma60 or A2 and A3 and XG and close > ma60 and weeklySlope
// Sell Signal Condition
sellSignal = close < ta.ema(close, 10)
// Buy and Sell Conditions
buyCondition = buySignal and not inPosition
sellCondition = sellSignal and inPosition
// Execute Buy and Sell Operations
if (buyCondition)
strategy.entry("Buy", strategy.long)
inPosition := true
if (sellCondition)
strategy.close("Buy")
inPosition := false
// Stop Loss and Take Profit Levels
stopLoss = strategy.position_avg_price * 0.5
takeProfit = strategy.position_avg_price * 1.30
// Apply Stop Loss and Take Profit Levels
if inPosition
strategy.exit("Long Stop Loss", "Buy", stop=stopLoss)
strategy.exit("Long Take Profit", "Buy", limit=takeProfit)
// Plot Buy and Sell Signal Shapes
plotshape(buyCondition, style=shape.arrowdown, location=location.belowbar, color=color.green, size=size.small)
plotshape(sellCondition, style=shape.arrowup, location=location.abovebar, color=color.red, size=size.small)
// EMA Variable Definition
ema = ta.ema(close, 5)
// Plot Indicator Line
plot(ema, color=color.green, title="EMA")
|
D-BoT Alpha 'Short' SMA and RSI Strategy | https://www.tradingview.com/script/YAidkd8K/ | Genesis-Trader | https://www.tradingview.com/u/Genesis-Trader/ | 31 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © abdllhatn
//@version=5
strategy("Alpha Short SMA and RSI Strategy", overlay=true, initial_capital=10000, default_qty_value=100)
// Inputs
sma_length = input(200, title="SMA Length")
rsi_length = input(14, title="RSI Length")
rsi_entry = input(51, title="RSI Entry Level")
rsi_stop = input(54, title="RSI Stop Level")
rsi_take_profit = input(32, title="RSI Take Profit Level")
// Indicators
sma_value = ta.sma(close, sma_length)
rsi_value = ta.rsi(close, rsi_length)
var float trailingStop = na
var float lastLow = na
// Conditions
shortCondition = ta.crossover(rsi_value, rsi_entry) and close < sma_value
if (shortCondition)
strategy.entry("Sell", strategy.short)
trailingStop := na
lastLow := na
if (strategy.position_size < 0)
if (na(lastLow) or close < lastLow)
lastLow := close
trailingStop := close
if not na(trailingStop) and close > trailingStop
strategy.close("Sell")
if (rsi_value >= rsi_stop)
strategy.close("Sell")
if (rsi_value <= rsi_take_profit)
strategy.close("Sell")
// Plot
plot(sma_value, color=color.red, linewidth=2)
|
BBPullback1.0.2 | https://www.tradingview.com/script/AmGzpixE-BBPullback1-0-2/ | westofpluto | https://www.tradingview.com/u/westofpluto/ | 53 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © westofpluto
//@version=5
strategy("BBPullback", overlay=true, margin_long=100, margin_short=100,process_orders_on_close=true)
TAKE_PROFIT_HILO = 0
TAKE_PROFIT_CLOSE = 1
TAKE_PROFIT_BB = 2
OPTION0 = "high crosses MA"
OPTION1 = "closes beyond MA"
OPTION2 = "high crosses opposite band"
tpoption=input.string(OPTION0,title="Take Proft trigger",options=[OPTION0,OPTION1,OPTION2])
i_from = input.time(defval = timestamp("23 Feb 2023 00:00 +0000"), title = "From")
i_thru = input.time(defval = timestamp("09 Apr 2023 00:00 +0000"), title = "Thru")
var take_profit_option=TAKE_PROFIT_HILO
if tpoption == OPTION0
take_profit_option := TAKE_PROFIT_HILO
else if tpoption == OPTION1
take_profit_option := TAKE_PROFIT_CLOSE
else
take_profit_option := TAKE_PROFIT_BB
//
// COMPUTE BOLLINGER BANDS INTERNALLY
//
source = close
length = 20
mult = 2.0
basis = ta.sma(source, length)
dev = mult * ta.stdev(source, length)
upperBBValue = basis + dev
lowerBBValue = basis - dev
NO_SETUP = 0
BB_BREAK_DOWN = 1
RETRACE_BAR_UP = 2
PENDING_ENTRY_LONG = 3
ENTRY_LONG = 4
BB_BREAK_UP = 5
RETRACE_BAR_DOWN = 6
PENDING_ENTRY_SHORT = 7
ENTRY_SHORT = 8
ID_STATE = 0
ID_BUY_ENTRY = 0
ID_SELL_ENTRY = 1
ID_BUY_STOPLOSS = 2
ID_SELL_STOPLOSS = 3
ID_SWING_HIGH = 4
ID_SWING_LOW = 5
LARGE_NUMBER = 99999999.9
var state = NO_SETUP
var buy_entry_price = 0.0
var sell_entry_price = 0.0
var buy_stoploss_price = 0.0
var sell_stoploss_price = 0.0
var swing_low = LARGE_NUMBER
var swing_high = 0.0
var themax = 0.0
var themin = 99999999.0
//global_float = array.new_bool(1)
//array.set(global_bool,ID_TRENDMODEON,trendMode)
global_int = array.new_int(1)
array.set(global_int,ID_STATE,state)
global_float = array.new_float(6)
array.set(global_float,ID_BUY_ENTRY,buy_entry_price)
array.set(global_float,ID_SELL_ENTRY,sell_entry_price)
array.set(global_float,ID_BUY_STOPLOSS,buy_stoploss_price)
array.set(global_float,ID_SELL_STOPLOSS,sell_stoploss_price)
array.set(global_float,ID_SWING_HIGH,swing_high)
array.set(global_float,ID_SWING_LOW,swing_low)
//
// Main code starts here, executes every bar
//
dateok() =>
time >= i_from and time <= i_thru
minval(x, y) =>
(x < y ? x : y)
maxval(x, y) =>
(x > y ? x : y)
IsFlat() =>
strategy.position_size == 0
HasPosition() =>
strategy.position_size != 0
PullbackCandleLong() =>
close >= open or low > low[1]
PullbackCandleShort() =>
close <= open or high < high[1]
isUpCandle() =>
close >= open
isDownCandle() =>
open > close
StateInTrade() =>
array.get(global_int,ID_STATE) == ENTRY_LONG or array.get(global_int,ID_STATE) == ENTRY_SHORT
StatePendingLong() =>
array.get(global_int,ID_STATE) == PENDING_ENTRY_LONG
StatePendingShort() =>
array.get(global_int,ID_STATE) == PENDING_ENTRY_SHORT
StateInLongTrade() =>
array.get(global_int,ID_STATE) == ENTRY_LONG
StateInShortTrade() =>
array.get(global_int,ID_STATE) == ENTRY_SHORT
LongTakeProfitHigh() =>
high > basis
ShortTakeProfitLow() =>
low < basis
LongTakeProfitClose() =>
close > basis
ShortTakeProfitClose() =>
close < basis
LongTakeProfitBB() =>
high > upperBBValue
ShortTakeProfitBB() =>
low < lowerBBValue
LongTakeProfitHit() =>
if take_profit_option == TAKE_PROFIT_HILO
LongTakeProfitHigh()
else if take_profit_option == TAKE_PROFIT_CLOSE
LongTakeProfitClose()
else
LongTakeProfitBB()
ShortTakeProfitHit() =>
if take_profit_option == TAKE_PROFIT_HILO
ShortTakeProfitLow()
else if take_profit_option == TAKE_PROFIT_CLOSE
ShortTakeProfitClose()
else
ShortTakeProfitBB()
LongTriggerCondition() =>
if (dateok() and isUpCandle() and minval(open,close) < lowerBBValue and high < basis and high > lowerBBValue)
true
else
false
ShortTriggerCondition() =>
if (dateok() and isDownCandle() and maxval(open,close) > upperBBValue and low > basis and low < upperBBValue)
true
else
false
if (HasPosition() and StatePendingLong())
array.set(global_int,ID_STATE,ENTRY_LONG)
else if (HasPosition() and StatePendingShort())
array.set(global_int,ID_STATE,ENTRY_SHORT)
else if (IsFlat() and StateInTrade())
array.set(global_int,ID_STATE,NO_SETUP)
//
// If an order didn't trigger this bar then cancel it
//
var cancel_long=false
var cancel_short=false
if IsFlat()
if (array.get(global_int,ID_STATE) == PENDING_ENTRY_LONG)
cancel_long := true
strategy.cancel("Enter Long")
array.set(global_int,ID_STATE,NO_SETUP)
else if (array.get(global_int,ID_STATE) == PENDING_ENTRY_SHORT)
cancel_short := true
strategy.cancel("Enter Short")
array.set(global_int,ID_STATE,NO_SETUP)
//
// Trading logic long
//
if IsFlat()
if (array.get(global_int,ID_STATE) == NO_SETUP)
if (LongTriggerCondition())
//array.set(global_int,ID_STATE,BB_BREAK_DOWN)
array.set(global_float,ID_BUY_ENTRY,high)
if (cancel_long)
array.set(global_float,ID_SWING_LOW,minval(low,array.get(global_float,ID_SWING_LOW)))
else
array.set(global_float,ID_SWING_LOW,low)
array.set(global_float,ID_SWING_HIGH,0.0)
//array.set(global_float,ID_BUY_STOPLOSS,array.get(global_float,ID_SWING_LOW))
array.set(global_float,ID_BUY_STOPLOSS,low)
strategy.entry("Enter Long", strategy.long,stop=array.get(global_float,ID_BUY_ENTRY),limit=array.get(global_float,ID_BUY_ENTRY))
array.set(global_int,ID_STATE,PENDING_ENTRY_LONG)
strategy.exit("Stop Out",from_entry="Enter Long",stop=array.get(global_float,ID_BUY_STOPLOSS))
else if (array.get(global_int,ID_STATE) == BB_BREAK_DOWN)
if (PullbackCandleLong())
array.set(global_float,ID_BUY_ENTRY,high)
array.set(global_float,ID_BUY_STOPLOSS,low)
strategy.entry("Enter Long", strategy.long,stop=array.get(global_float,ID_BUY_ENTRY),limit=array.get(global_float,ID_BUY_ENTRY))
array.set(global_int,ID_STATE,PENDING_ENTRY_LONG)
else if (array.get(global_int,ID_STATE) == PENDING_ENTRY_LONG)
strategy.cancel("Enter Long")
array.set(global_int,ID_STATE,NO_SETUP)
//if (array.get(global_int,ID_STATE) == PENDING_ENTRY_LONG)
// strategy.exit("Stop Out",from_entry="Enter Long",stop=array.get(global_float,ID_BUY_STOPLOSS))
//
// Trading logic short
//
if IsFlat()
if (array.get(global_int,ID_STATE) == NO_SETUP)
if (ShortTriggerCondition())
//array.set(global_int,ID_STATE,BB_BREAK_UP)
array.set(global_float,ID_SELL_ENTRY,low)
if (cancel_short)
array.set(global_float,ID_SWING_HIGH,maxval(high,array.get(global_float,ID_SWING_HIGH)))
else
array.set(global_float,ID_SWING_HIGH,high)
array.set(global_float,ID_SWING_LOW,LARGE_NUMBER)
//array.set(global_float,ID_SELL_STOPLOSS,array.get(global_float,ID_SWING_HIGH))
array.set(global_float,ID_SELL_STOPLOSS,high)
strategy.entry("Enter Short", strategy.short,stop=array.get(global_float,ID_SELL_ENTRY))
array.set(global_int,ID_STATE,PENDING_ENTRY_SHORT)
strategy.exit("Stop Out",from_entry="Enter Short",stop=array.get(global_float,ID_SELL_STOPLOSS))
else if (array.get(global_int,ID_STATE) == BB_BREAK_UP)
if (PullbackCandleShort())
//array.set(global_int,ID_STATE,RETRACE_BAR_DOWN)
array.set(global_float,ID_SELL_ENTRY,low)
array.set(global_float,ID_SELL_STOPLOSS,high)
strategy.entry("Enter Short", strategy.short,stop=array.get(global_float,ID_SELL_ENTRY))
array.set(global_int,ID_STATE,PENDING_ENTRY_SHORT)
else if (array.get(global_int,ID_STATE) == PENDING_ENTRY_SHORT)
strategy.cancel("Enter Short")
array.set(global_int,ID_STATE,NO_SETUP)
//if (array.get(global_int,ID_STATE) == PENDING_ENTRY_SHORT)
// strategy.exit("Stop Out",from_entry="Enter Short",stop=array.get(global_float,ID_SELL_STOPLOSS))
if StateInLongTrade()
if (LongTakeProfitHit())
strategy.close("Enter Long",comment="Take Profit")
array.set(global_int,ID_STATE,NO_SETUP)
else if StateInShortTrade()
if (ShortTakeProfitHit())
strategy.close("Enter Short",comment="Take Profit")
array.set(global_int,ID_STATE,NO_SETUP)
state := array.get(global_int,ID_STATE)
buy_entry_price := array.get(global_float,ID_BUY_ENTRY)
sell_entry_price := array.get(global_float,ID_SELL_ENTRY)
buy_stoploss_price := array.get(global_float,ID_BUY_STOPLOSS)
sell_stoploss_price := array.get(global_float,ID_SELL_STOPLOSS)
themin := minval(open,close)
themax := maxval(open,close)
plotchar(state, "State", "", location = location.top)
plotchar(themin, "TheMin", "", location = location.top)
plotchar(themax, "TheMax", "", location = location.top)
plotchar(upperBBValue, "UpperBB", "", location = location.top)
plotchar(lowerBBValue, "LowerBB", "", location = location.top)
plotchar(buy_stoploss_price, "buy stoploss", "", location = location.top)
plotchar(sell_stoploss_price, "sell stoploss", "", location = location.top)
swing_low := array.get(global_float,ID_SWING_LOW)
plotchar(swing_low, "SwingLow", "", location = location.top)
|
RSI TrueLevel Strategy | https://www.tradingview.com/script/47AmMd56-RSI-TrueLevel-Strategy/ | Julien_Eche | https://www.tradingview.com/u/Julien_Eche/ | 121 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Julien_Eche
//@version=4
strategy("RSI TrueLevel Strategy", shorttitle="RSI TL", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=10)
// Input parameters for RSI
rsiPeriod = input(14, title="RSI Period", type=input.integer)
rsiOverbought = input(65, title="RSI Overbought Level", type=input.integer)
rsiOversold = input(40, title="RSI Oversold Level", type=input.integer)
// Inputs for selecting bands
entry_band = input(12, title="Entry TrueLevel Band", type=input.integer, minval=1, maxval=14)
exit_band = input(12, title="Exit TrueLevel Band", type=input.integer, minval=1, maxval=14)
// Input for long and short mode
long_and_short = input(false, title="Enable Long and Short", type=input.bool)
// Calculate the RSI
rsi = rsi(close, rsiPeriod)
// User inputs
len1 = input(title="Length 1", type=input.integer, defval=126)
len2 = input(title="Length 2", type=input.integer, defval=189)
len3 = input(title="Length 3", type=input.integer, defval=252)
len4 = input(title="Length 4", type=input.integer, defval=378)
len5 = input(title="Length 5", type=input.integer, defval=504)
len6 = input(title="Length 6", type=input.integer, defval=630)
len7 = input(title="Length 7", type=input.integer, defval=756)
len8 = input(title="Length 8", type=input.integer, defval=1008)
len9 = input(title="Length 9", type=input.integer, defval=1260)
len10 = input(title="Length 10", type=input.integer, defval=1638)
len11 = input(title="Length 11", type=input.integer, defval=2016)
len12 = input(title="Length 12", type=input.integer, defval=2646)
len13 = input(title="Length 13", type=input.integer, defval=3276)
len14 = input(title="Length 14", type=input.integer, defval=4284)
fill_color = input(title="Fill Color", type=input.color, defval=color.rgb(0, 191, 255, 95))
mult = input(title="Multiple", type=input.float, defval=1, step=0.2, options=[0.6, 0.8, 1, 1.2, 1.4])
src = input(title="Source", type=input.source, defval=close)
// Upper band calculation function
upperBand(length) =>
linreg = linreg(src, length, 0)
stddev = mult * stdev(src, length)
upperband = linreg + stddev
upperband
// Lower band calculation function
lowerBand(length) =>
linreg = linreg(src, length, 0)
stddev = mult * stdev(src, length)
lowerband = linreg - stddev
lowerband
// Calculate upper and lower bands for each length
upperband_1 = upperBand(len1)
upperband_2 = upperBand(len2)
upperband_3 = upperBand(len3)
upperband_4 = upperBand(len4)
upperband_5 = upperBand(len5)
upperband_6 = upperBand(len6)
upperband_7 = upperBand(len7)
upperband_8 = upperBand(len8)
upperband_9 = upperBand(len9)
upperband_10 = upperBand(len10)
upperband_11 = upperBand(len11)
upperband_12 = upperBand(len12)
upperband_13 = upperBand(len13)
upperband_14 = upperBand(len14)
lowerband_1 = lowerBand(len1)
lowerband_2 = lowerBand(len2)
lowerband_3 = lowerBand(len3)
lowerband_4 = lowerBand(len4)
lowerband_5 = lowerBand(len5)
lowerband_6 = lowerBand(len6)
lowerband_7 = lowerBand(len7)
lowerband_8 = lowerBand(len8)
lowerband_9 = lowerBand(len9)
lowerband_10 = lowerBand(len10)
lowerband_11 = lowerBand(len11)
lowerband_12 = lowerBand(len12)
lowerband_13 = lowerBand(len13)
lowerband_14 = lowerBand(len14)
// Plot envelope bands for each length
upperband_1_plot = plot(upperband_1, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 1")
lowerband_1_plot = plot(lowerband_1, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Lower Band 1")
upperband_2_plot = plot(upperband_2, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 2")
lowerband_2_plot = plot(lowerband_2, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Lower Band 2")
upperband_3_plot = plot(upperband_3, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 3")
lowerband_3_plot = plot(lowerband_3, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Lower Band 3")
upperband_4_plot = plot(upperband_4, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 4")
lowerband_4_plot = plot(lowerband_4, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Lower Band 4")
upperband_5_plot = plot(upperband_5, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 5")
lowerband_5_plot = plot(lowerband_5, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Lower Band 5")
upperband_6_plot = plot(upperband_6, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 6")
lowerband_6_plot = plot(lowerband_6, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Lower Band 6")
upperband_7_plot = plot(upperband_7, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 7")
lowerband_7_plot = plot(lowerband_7, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Lower Band 7")
upperband_8_plot = plot(upperband_8, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 8")
lowerband_8_plot = plot(lowerband_8, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Lower Band 8")
upperband_9_plot = plot(upperband_9, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 9")
lowerband_9_plot = plot(lowerband_9, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Lower Band 9")
upperband_10_plot = plot(upperband_10, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 10")
lowerband_10_plot = plot(lowerband_10, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Lower Band 10")
upperband_11_plot = plot(upperband_11, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 11")
lowerband_11_plot = plot(lowerband_11, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Lower Band 11")
upperband_12_plot = plot(upperband_12, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 12")
lowerband_12_plot = plot(lowerband_12, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Lower Band 12")
upperband_13_plot = plot(upperband_13, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 13")
lowerband_13_plot = plot(lowerband_13, color=color.rgb(14, 139, 212, 95), linewidth=1, title="Lower Band 13")
upperband_14_plot = plot(upperband_14, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 14")
lowerband_14_plot = plot(lowerband_14, color=color.rgb(14, 139, 212, 95), linewidth=1, title="Lower Band 14")
// Plot fills for each length
fill(upperband_1_plot, lowerband_1_plot, color=fill_color, title="Fill 1")
fill(upperband_2_plot, lowerband_2_plot, color=fill_color, title="Fill 2")
fill(upperband_3_plot, lowerband_3_plot, color=fill_color, title="Fill 3")
fill(upperband_4_plot, lowerband_4_plot, color=fill_color, title="Fill 4")
fill(upperband_5_plot, lowerband_5_plot, color=fill_color, title="Fill 5")
fill(upperband_6_plot, lowerband_6_plot, color=fill_color, title="Fill 6")
fill(upperband_7_plot, lowerband_7_plot, color=fill_color, title="Fill 7")
fill(upperband_8_plot, lowerband_8_plot, color=fill_color, title="Fill 8")
fill(upperband_9_plot, lowerband_9_plot, color=fill_color, title="Fill 9")
fill(upperband_10_plot, lowerband_10_plot, color=fill_color, title="Fill 10")
fill(upperband_11_plot, lowerband_11_plot, color=fill_color, title="Fill 11")
fill(upperband_12_plot, lowerband_12_plot, color=fill_color, title="Fill 12")
fill(upperband_13_plot, lowerband_13_plot, color=fill_color, title="Fill 13")
fill(upperband_14_plot, lowerband_14_plot, color=fill_color, title="Fill 14")
// Add variables to store the highest upper band and lowest lower band values
var float highestUpperBand = na
var float lowestLowerBand = na
// Calculate the trueLevelUpperBand and trueLevelLowerBand
trueLevelUpperBand = max(upperband_1, max(upperband_2, max(upperband_3, max(upperband_4, max(upperband_5, max(upperband_6, max(upperband_7, max(upperband_8, max(upperband_9, max(upperband_10, max(upperband_11, max(upperband_12, max(upperband_13, upperband_14)))))))))))))
trueLevelLowerBand = min(lowerband_1, min(lowerband_2, min(lowerband_3, min(lowerband_4, min(lowerband_5, min(lowerband_6, min(lowerband_7, min(lowerband_8, min(lowerband_9, min(lowerband_10, min(lowerband_11, min(lowerband_12, min(lowerband_13, lowerband_14)))))))))))))
// Update the highest upper band and lowest lower band
highestUpperBand := highest(trueLevelUpperBand, 1)
lowestLowerBand := lowest(trueLevelLowerBand, 1)
// Store the upper and lower bands in an array for easy access
upperbands = array.new_float(14)
lowerbands = array.new_float(14)
array.set(upperbands, 0, upperband_1)
array.set(upperbands, 1, upperband_2)
array.set(upperbands, 2, upperband_3)
array.set(upperbands, 3, upperband_4)
array.set(upperbands, 4, upperband_5)
array.set(upperbands, 5, upperband_6)
array.set(upperbands, 6, upperband_7)
array.set(upperbands, 7, upperband_8)
array.set(upperbands, 8, upperband_9)
array.set(upperbands, 9, upperband_10)
array.set(upperbands, 10, upperband_11)
array.set(upperbands, 11, upperband_12)
array.set(upperbands, 12, upperband_13)
array.set(upperbands, 13, upperband_14)
array.set(lowerbands, 0, lowerband_1)
array.set(lowerbands, 1, lowerband_2)
array.set(lowerbands, 2, lowerband_3)
array.set(lowerbands, 3, lowerband_4)
array.set(lowerbands, 4, lowerband_5)
array.set(lowerbands, 5, lowerband_6)
array.set(lowerbands, 6, lowerband_7)
array.set(lowerbands, 7, lowerband_8)
array.set(lowerbands, 8, lowerband_9)
array.set(lowerbands, 9, lowerband_10)
array.set(lowerbands, 10, lowerband_11)
array.set(lowerbands, 11, lowerband_12)
array.set(lowerbands, 12, lowerband_13)
array.set(lowerbands, 13, lowerband_14)
// Get the selected bands for entry and exit
selected_entry_lowerband = array.get(lowerbands, entry_band - 1)
selected_exit_upperband = array.get(upperbands, exit_band - 1)
// Entry conditions
longCondition = crossover(rsi, rsiOversold) or crossover(close, selected_entry_lowerband)
shortCondition = crossunder(rsi, rsiOverbought) or crossunder(close, selected_exit_upperband)
if (longCondition)
strategy.entry("Long", strategy.long)
if (long_and_short and shortCondition)
strategy.entry("Short", strategy.short)
// Exit conditions
exitLongCondition = crossunder(rsi, rsiOverbought) or crossunder(close, selected_exit_upperband)
exitShortCondition = crossover(rsi, rsiOversold) or crossover(close, selected_entry_lowerband)
strategy.close("Long", when=exitLongCondition)
strategy.close("Short", when=long_and_short and exitShortCondition)
|
MACD TrueLevel Strategy | https://www.tradingview.com/script/kkLgubYm-MACD-TrueLevel-Strategy/ | Julien_Eche | https://www.tradingview.com/u/Julien_Eche/ | 70 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Julien_Eche
//@version=4
strategy("MACD TrueLevel Strategy", shorttitle="MACD TL", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=10)
// Input parameters for MACD
fastLength = input(12, title="Fast Length", type=input.integer)
slowLength = input(26, title="Slow Length", type=input.integer)
signalLength = input(9, title="Signal Length", type=input.integer)
// Inputs for selecting bands
entry_band = input(12, title="Entry TrueLevel Band", type=input.integer, minval=1, maxval=14)
exit_band = input(12, title="Exit TrueLevel Band", type=input.integer, minval=1, maxval=14)
// Input for long and short mode
long_and_short = input(false, title="Enable Long and Short", type=input.bool)
// Calculate the MACD
[macdLine, signalLine, _] = macd(close, fastLength, slowLength, signalLength)
// User inputs
len1 = input(title="Length 1", type=input.integer, defval=126)
len2 = input(title="Length 2", type=input.integer, defval=189)
len3 = input(title="Length 3", type=input.integer, defval=252)
len4 = input(title="Length 4", type=input.integer, defval=378)
len5 = input(title="Length 5", type=input.integer, defval=504)
len6 = input(title="Length 6", type=input.integer, defval=630)
len7 = input(title="Length 7", type=input.integer, defval=756)
len8 = input(title="Length 8", type=input.integer, defval=1008)
len9 = input(title="Length 9", type=input.integer, defval=1260)
len10 = input(title="Length 10", type=input.integer, defval=1638)
len11 = input(title="Length 11", type=input.integer, defval=2016)
len12 = input(title="Length 12", type=input.integer, defval=2646)
len13 = input(title="Length 13", type=input.integer, defval=3276)
len14 = input(title="Length 14", type=input.integer, defval=4284)
fill_color = input(title="Fill Color", type=input.color, defval=color.rgb(0, 191, 255, 95))
mult = input(title="Multiple", type=input.float, defval=1, step=0.2, options=[0.6, 0.8, 1, 1.2, 1.4])
src = input(title="Source", type=input.source, defval=close)
// Upper band calculation function
upperBand(length) =>
linreg = linreg(src, length, 0)
stddev = mult * stdev(src, length)
upperband = linreg + stddev
upperband
// Lower band calculation function
lowerBand(length) =>
linreg = linreg(src, length, 0)
stddev = mult * stdev(src, length)
lowerband = linreg - stddev
lowerband
// Calculate upper and lower bands for each length
upperband_1 = upperBand(len1)
upperband_2 = upperBand(len2)
upperband_3 = upperBand(len3)
upperband_4 = upperBand(len4)
upperband_5 = upperBand(len5)
upperband_6 = upperBand(len6)
upperband_7 = upperBand(len7)
upperband_8 = upperBand(len8)
upperband_9 = upperBand(len9)
upperband_10 = upperBand(len10)
upperband_11 = upperBand(len11)
upperband_12 = upperBand(len12)
upperband_13 = upperBand(len13)
upperband_14 = upperBand(len14)
lowerband_1 = lowerBand(len1)
lowerband_2 = lowerBand(len2)
lowerband_3 = lowerBand(len3)
lowerband_4 = lowerBand(len4)
lowerband_5 = lowerBand(len5)
lowerband_6 = lowerBand(len6)
lowerband_7 = lowerBand(len7)
lowerband_8 = lowerBand(len8)
lowerband_9 = lowerBand(len9)
lowerband_10 = lowerBand(len10)
lowerband_11 = lowerBand(len11)
lowerband_12 = lowerBand(len12)
lowerband_13 = lowerBand(len13)
lowerband_14 = lowerBand(len14)
// Plot envelope bands for each length
upperband_1_plot = plot(upperband_1, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 1")
lowerband_1_plot = plot(lowerband_1, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Lower Band 1")
upperband_2_plot = plot(upperband_2, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 2")
lowerband_2_plot = plot(lowerband_2, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Lower Band 2")
upperband_3_plot = plot(upperband_3, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 3")
lowerband_3_plot = plot(lowerband_3, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Lower Band 3")
upperband_4_plot = plot(upperband_4, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 4")
lowerband_4_plot = plot(lowerband_4, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Lower Band 4")
upperband_5_plot = plot(upperband_5, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 5")
lowerband_5_plot = plot(lowerband_5, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Lower Band 5")
upperband_6_plot = plot(upperband_6, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 6")
lowerband_6_plot = plot(lowerband_6, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Lower Band 6")
upperband_7_plot = plot(upperband_7, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 7")
lowerband_7_plot = plot(lowerband_7, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Lower Band 7")
upperband_8_plot = plot(upperband_8, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 8")
lowerband_8_plot = plot(lowerband_8, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Lower Band 8")
upperband_9_plot = plot(upperband_9, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 9")
lowerband_9_plot = plot(lowerband_9, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Lower Band 9")
upperband_10_plot = plot(upperband_10, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 10")
lowerband_10_plot = plot(lowerband_10, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Lower Band 10")
upperband_11_plot = plot(upperband_11, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 11")
lowerband_11_plot = plot(lowerband_11, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Lower Band 11")
upperband_12_plot = plot(upperband_12, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 12")
lowerband_12_plot = plot(lowerband_12, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Lower Band 12")
upperband_13_plot = plot(upperband_13, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 13")
lowerband_13_plot = plot(lowerband_13, color=color.rgb(14, 139, 212, 95), linewidth=1, title="Lower Band 13")
upperband_14_plot = plot(upperband_14, color=color.rgb(14, 116, 212, 95), linewidth=1, title="Upper Band 14")
lowerband_14_plot = plot(lowerband_14, color=color.rgb(14, 139, 212, 95), linewidth=1, title="Lower Band 14")
// Plot fills for each length
fill(upperband_1_plot, lowerband_1_plot, color=fill_color, title="Fill 1")
fill(upperband_2_plot, lowerband_2_plot, color=fill_color, title="Fill 2")
fill(upperband_3_plot, lowerband_3_plot, color=fill_color, title="Fill 3")
fill(upperband_4_plot, lowerband_4_plot, color=fill_color, title="Fill 4")
fill(upperband_5_plot, lowerband_5_plot, color=fill_color, title="Fill 5")
fill(upperband_6_plot, lowerband_6_plot, color=fill_color, title="Fill 6")
fill(upperband_7_plot, lowerband_7_plot, color=fill_color, title="Fill 7")
fill(upperband_8_plot, lowerband_8_plot, color=fill_color, title="Fill 8")
fill(upperband_9_plot, lowerband_9_plot, color=fill_color, title="Fill 9")
fill(upperband_10_plot, lowerband_10_plot, color=fill_color, title="Fill 10")
fill(upperband_11_plot, lowerband_11_plot, color=fill_color, title="Fill 11")
fill(upperband_12_plot, lowerband_12_plot, color=fill_color, title="Fill 12")
fill(upperband_13_plot, lowerband_13_plot, color=fill_color, title="Fill 13")
fill(upperband_14_plot, lowerband_14_plot, color=fill_color, title="Fill 14")
// Add variables to store the highest upper band and lowest lower band values
var float highestUpperBand = na
var float lowestLowerBand = na
// Calculate the trueLevelUpperBand and trueLevelLowerBand
trueLevelUpperBand = max(upperband_1, max(upperband_2, max(upperband_3, max(upperband_4, max(upperband_5, max(upperband_6, max(upperband_7, max(upperband_8, max(upperband_9, max(upperband_10, max(upperband_11, max(upperband_12, max(upperband_13, upperband_14)))))))))))))
trueLevelLowerBand = min(lowerband_1, min(lowerband_2, min(lowerband_3, min(lowerband_4, min(lowerband_5, min(lowerband_6, min(lowerband_7, min(lowerband_8, min(lowerband_9, min(lowerband_10, min(lowerband_11, min(lowerband_12, min(lowerband_13, lowerband_14)))))))))))))
// Update the highest upper band and lowest lower band
highestUpperBand := highest(trueLevelUpperBand, 1)
lowestLowerBand := lowest(trueLevelLowerBand, 1)
// Store the upper and lower bands in an array for easy access
upperbands = array.new_float(14)
lowerbands = array.new_float(14)
array.set(upperbands, 0, upperband_1)
array.set(upperbands, 1, upperband_2)
array.set(upperbands, 2, upperband_3)
array.set(upperbands, 3, upperband_4)
array.set(upperbands, 4, upperband_5)
array.set(upperbands, 5, upperband_6)
array.set(upperbands, 6, upperband_7)
array.set(upperbands, 7, upperband_8)
array.set(upperbands, 8, upperband_9)
array.set(upperbands, 9, upperband_10)
array.set(upperbands, 10, upperband_11)
array.set(upperbands, 11, upperband_12)
array.set(upperbands, 12, upperband_13)
array.set(upperbands, 13, upperband_14)
array.set(lowerbands, 0, lowerband_1)
array.set(lowerbands, 1, lowerband_2)
array.set(lowerbands, 2, lowerband_3)
array.set(lowerbands, 3, lowerband_4)
array.set(lowerbands, 4, lowerband_5)
array.set(lowerbands, 5, lowerband_6)
array.set(lowerbands, 6, lowerband_7)
array.set(lowerbands, 7, lowerband_8)
array.set(lowerbands, 8, lowerband_9)
array.set(lowerbands, 9, lowerband_10)
array.set(lowerbands, 10, lowerband_11)
array.set(lowerbands, 11, lowerband_12)
array.set(lowerbands, 12, lowerband_13)
array.set(lowerbands, 13, lowerband_14)
// Get the selected bands for entry and exit
selected_entry_lowerband = array.get(lowerbands, entry_band - 1)
selected_exit_upperband = array.get(upperbands, exit_band - 1)
// Entry conditions
longCondition = crossover(macdLine, signalLine) or crossover(close, selected_entry_lowerband)
shortCondition = crossunder(macdLine, signalLine) or crossunder(close, selected_exit_upperband)
// Exit conditions
exitLongCondition = crossunder(macdLine, signalLine) or crossunder(close, selected_exit_upperband)
exitShortCondition = crossover(macdLine, signalLine) or crossover(close, selected_entry_lowerband)
// Strategy execution
strategy.entry("Long", strategy.long, when = longCondition)
strategy.entry("Short", strategy.short, when = shortCondition and long_and_short)
strategy.close("Long", when = exitLongCondition)
strategy.close("Short", when = exitShortCondition) |
AUTOMATIC GRID BOT STRATEGY [ilovealgotrading] | https://www.tradingview.com/script/6qZpzElZ-AUTOMATIC-GRID-BOT-STRATEGY-ilovealgotrading/ | projeadam | https://www.tradingview.com/u/projeadam/ | 1,139 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © lovealgotrading
// First of all I want to say thank you to © thequantscience.
//@version=5
strategy(
title = 'AUTOMATIC GRID BOT STRATEGY [lovealgotrading]',
overlay = true,
commission_type = strategy.commission.percent,
commission_value = 0.075,
pyramiding = 20,
default_qty_type = strategy.percent_of_equity,
close_entries_rule = 'ANY',
initial_capital = 1000
)
/////////////////////////////// ALGORITHM BACKTEST SOURCE CODE ////////////////////////////////////
startDate = input.time(defval=timestamp('1 nov 2022 13:30 +0000'), title='Start_Date', group = " ############# ⏰ BACKTEST DATE ⏰ ############ " )
endDate = input.time(defval=timestamp('20 oct 2030 13:30 +0000'), title='End_Date', group = " ############# ⏰ BACKTEST DATE ⏰ ############ " )
inDateRange = time > startDate and time < endDate
high_price = input.price(
defval = 0.00,
title = 'Range High price: ',
group = " ############## ➡️ HIGH GRID PRICE ⬅️ ############ ",
confirm = true,
tooltip = "Top grid price."
)
low_price = input.price(
defval = 0.00,
title = 'Range Low price: ',
group = " ############## ➡️ LOW GRID PRICE ⬅️ ############# ",
confirm = true,
tooltip = "Bottom grid price."
)
// ###########################################################################################
trade_direction = input.string(title='Trade Direction', group = " ##############🎯 TRADE DIRECTION 🎯############# ", options=['LONG', 'SHORT', 'BOTH'], defval='BOTH')
// ###########################################################################################
use_stop = input.bool(defval = false , title = "Use StopLoss", group = " ############# ⛔️ Strategy STOP Settings ⛔️ ############ ")
close_bot_after_stop = input.bool(defval = false , title = "Close Bot After Stop Loss",tooltip = "Dont open new positions after stop loss", group = " ############# ⛔️ Strategy STOP Settings ⛔️ ############ ")
stop_close_all = ""
if stop_close_all[1] != "" and close_bot_after_stop
stop_close_all := "DONT"
use_stop_default = input.bool(defval = true , title = "Use StopLoss Where HIGH and LOW GRID PRICE", group = " ############# ⛔️ Strategy STOP Settings ⛔️ ############ ")
high_price_stop = input.price(
defval = 99999,
title = 'High STOP Price: ',
group = " ############# ⛔️ Strategy STOP Settings ⛔️ ############ ",
confirm = false,
tooltip = "Top STOP price."
)
low_price_stop = input.price(
defval = 0.00,
title = 'Low STOP Price: ',
group = " ############# ⛔️ Strategy STOP Settings ⛔️ ############ ",
confirm = false,
tooltip = "Bottom STOP price."
)
if use_stop_default
high_price_stop := high_price
low_price_stop := low_price
// ###########################################################################################
dolar = input.int(defval = 100, title = "$ Per Position", group = " ############# 🤖 ALGO TRADE ALERTS 🤖 ############ ")
// ###########################################################################################
Long_message = input("", group = " ############# 🤖 ALGO TRADE ALERTS 🤖 ############ ")
Long_Exit_message = input("", group = " ############# 🤖 ALGO TRADE ALERTS 🤖 ############ ")
Long_Stop_message = input("", group = " ############# 🤖 ALGO TRADE ALERTS 🤖 ############ ")
Short_message = input("", group = " ############# 🤖 ALGO TRADE ALERTS 🤖 ############ ")
Short_Exit_message = input("", group = " ############# 🤖 ALGO TRADE ALERTS 🤖 ############ ")
Short_Stop_message = input("", group = " ############# 🤖 ALGO TRADE ALERTS 🤖 ############ ")
// ###########################################################################################
float qty_new = dolar / close
if close > 5000
qty_new := math.round(dolar / close, 3)
else if close < 5000 and close > 200
qty_new := math.round(dolar / close, 2)
else if close < 200 and close > 50
qty_new := math.round(dolar / close, 1)
else if close < 50
qty_new := math.round(dolar / close, 0)
// ###########################################################################################
ten_grid = input.bool(
defval = false,
title = "10 grid levels",
group = " ############ GRID CONFIGURATION ############ ",
tooltip = "10 grid levels",
confirm = true
)
tewnty_grid = input.bool(
defval = true,
title = "20 grid levels",
group = " ############ GRID CONFIGURATION ############ ",
tooltip = "20 grid levels",
confirm = true
)
// ###########################################################################################
show_stop_res = input.bool(true, title = "Show Stop Price",group = " ############# 📈 Graphics Settings 📈 ########### ")
show_grid_level_bg = input.bool(true, title = "Show Grid Levels BG",group = " ############# 📈 Graphics Settings 📈 ########### ")
// ###########################################################################################
grid_range = high_price - low_price
percent_change = ((high_price - low_price) / low_price) * (1.00 / 9.00)
var float grid_1 = 0
var float grid_2 = 0
var float grid_3 = 0
var float grid_4 = 0
var float grid_5 = 0
var float grid_6 = 0
var float grid_7 = 0
var float grid_8 = 0
var float grid_9 = 0
var float grid_10 = 0
var float grid_11 = 0
var float grid_12 = 0
var float grid_13 = 0
var float grid_14 = 0
var float grid_15 = 0
var float grid_16 = 0
var float grid_17 = 0
var float grid_18 = 0
var float grid_19 = 0
var float grid_20 = 0
var float factor = 0
long_1 = false
long_2 = false
long_3 = false
long_4 = false
long_5 = false
long_6 = false
long_7 = false
long_8 = false
long_9 = false
long_10 = false
short_1 = false
short_2 = false
short_3 = false
short_4 = false
short_5 = false
short_6 = false
short_7 = false
short_8 = false
short_9 = false
short_10 = false
if ten_grid == true
percent_change := ((high_price - low_price) / low_price) * (1.00 / 9.00)
factor := grid_range / 9
grid_1 := (high_price)
grid_2 := (high_price - (factor * 1))
grid_3 := (high_price - (factor * 2))
grid_4 := (high_price - (factor * 3))
grid_5 := (high_price - (factor * 4))
grid_6 := (high_price - (factor * 5))
grid_7 := (high_price - (factor * 6))
grid_8 := (high_price - (factor * 7))
grid_9 := (high_price - (factor * 8))
grid_10 := (low_price)
long_1 := ta.crossunder(close, ((grid_5+grid_6)/2))
long_2 := ta.crossunder(close, ((grid_6+grid_7)/2))
long_3 := ta.crossunder(close, ((grid_7+grid_8)/2))
long_4 := ta.crossunder(close, ((grid_8+grid_9)/2))
long_5 := ta.crossunder(close, ((grid_9+grid_10)/2))
short_1 := ta.crossover(close, ((grid_6+grid_5)/2))
short_2 := ta.crossover(close, ((grid_5+grid_4)/2))
short_3 := ta.crossover(close, ((grid_4+grid_3)/2))
short_4 := ta.crossover(close, ((grid_3+grid_2)/2))
short_5 := ta.crossover(close, ((grid_2+grid_1)/2))
if tewnty_grid == true
percent_change := ((high_price - low_price) / low_price) * (1.00 / 19.00)
factor := grid_range / 19
grid_1 := (high_price)
grid_2 := (high_price - (factor * 1))
grid_3 := (high_price - (factor * 2))
grid_4 := (high_price - (factor * 3))
grid_5 := (high_price - (factor * 4))
grid_6 := (high_price - (factor * 5))
grid_7 := (high_price - (factor * 6))
grid_8 := (high_price - (factor * 7))
grid_9 := (high_price - (factor * 8))
grid_10 := (high_price - (factor * 9))
grid_11 := (high_price - (factor * 10))
grid_12 := (high_price - (factor * 11))
grid_13 := (high_price - (factor * 12))
grid_14 := (high_price - (factor * 13))
grid_15 := (high_price - (factor * 14))
grid_16 := (high_price - (factor * 15))
grid_17 := (high_price - (factor * 16))
grid_18 := (high_price - (factor * 17))
grid_19 := (high_price - (factor * 18))
grid_20 := (low_price)
long_1 := close < ((grid_10+grid_11)/2)
long_2 := close < ((grid_11+grid_12)/2)
long_3 := close < ((grid_12+grid_13)/2)
long_4 := close < ((grid_13+grid_14)/2)
long_5 := close < ((grid_14+grid_15)/2)
long_6 := close < ((grid_15+grid_16)/2)
long_7 := close < ((grid_16+grid_17)/2)
long_8 := close < ((grid_17+grid_18)/2)
long_9 := close < ((grid_18+grid_19)/2)
long_10 := close < ((grid_19+grid_20)/2)
short_10 := close >((grid_1+grid_2)/2)
short_9 := close >((grid_2+grid_3)/2)
short_8 := close >((grid_3+grid_4)/2)
short_7 := close >((grid_4+grid_5)/2)
short_6 := close >((grid_5+grid_6)/2)
short_5 := close >((grid_6+grid_7)/2)
short_4 := close >((grid_7+grid_8)/2)
short_3 := close >((grid_8+grid_9)/2)
short_2 := close >((grid_9+grid_10)/2)
short_1 := close > ((grid_10+grid_11)/2)
// ###########################################################################################
// ###########################################################################################
if ten_grid and ( trade_direction == 'LONG' or trade_direction == 'BOTH')
if long_1 and strategy.opentrades == 0 and inDateRange and stop_close_all == ""
strategy.entry(id = "L_1", direction = strategy.long,alert_message = Long_message, qty = qty_new )
if strategy.opentrades == 1
strategy.exit(id = "E_1",from_entry = "L_1", qty_percent = 100,alert_message =Long_Exit_message,stop = 0, limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
if long_2 and strategy.opentrades == 1 and inDateRange and stop_close_all == ""
strategy.entry(id = "L_2", direction = strategy.long,alert_message = Long_message, qty = qty_new )
if strategy.opentrades == 2
strategy.exit(id = "E_2",from_entry = "L_2", qty_percent = 100,alert_message =Long_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
if long_3 and strategy.opentrades == 2 and inDateRange and stop_close_all == ""
strategy.entry(id = "L_3", direction = strategy.long,alert_message = Long_message, qty = qty_new )
if strategy.opentrades == 3
strategy.exit(id = "E_3",from_entry = "L_3", qty_percent = 100,alert_message =Long_Exit_message,limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
if long_4 and strategy.opentrades == 3 and inDateRange and stop_close_all == ""
strategy.entry(id = "L_4", direction = strategy.long,alert_message = Long_message, qty = qty_new )
if strategy.opentrades == 4
strategy.exit(id = "E_4",from_entry = "L_4", qty_percent = 100,alert_message =Long_Exit_message,limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
if long_5 and strategy.opentrades == 4 and inDateRange and stop_close_all == ""
strategy.entry(id = "L_5", direction = strategy.long,alert_message = Long_message, qty = qty_new )
if strategy.opentrades == 5
strategy.exit(id = "E_5",from_entry = "L_5", qty_percent = 100,alert_message =Long_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
// ###########################################################################################
if ten_grid and ( trade_direction == 'SHORT' or trade_direction == 'BOTH')
if short_1 and strategy.opentrades == 0 and inDateRange and stop_close_all == ""
strategy.entry(id = "S_1", direction = strategy.short,alert_message = Short_message, qty = qty_new )
if strategy.opentrades == 1
strategy.exit(id = "ES_1",from_entry = "S_1", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
if short_2 and strategy.opentrades == 1 and inDateRange and stop_close_all == ""
strategy.entry(id = "S_2",direction = strategy.short,alert_message = Short_message, qty = qty_new )
if strategy.opentrades == 2
strategy.exit(id = "ES_2",from_entry = "S_2", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
if short_3 and strategy.opentrades == 2 and inDateRange and stop_close_all == ""
strategy.entry(id = "S_3", direction = strategy.short,alert_message = Short_message, qty = qty_new )
if strategy.opentrades == 3
strategy.exit(id = "ES_3",from_entry = "S_3", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
if short_4 and strategy.opentrades == 3 and inDateRange and stop_close_all == ""
strategy.entry(id = "S_4", direction = strategy.short,alert_message = Short_message, qty = qty_new )
if strategy.opentrades == 4
strategy.exit(id = "ES_4",from_entry = "S_4", qty_percent = 100,alert_message =Short_Exit_message,limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
if short_5 and strategy.opentrades == 4 and inDateRange and stop_close_all == ""
strategy.entry(id = "S_5", direction = strategy.short,alert_message = Short_message, qty = qty_new )
if strategy.opentrades == 5
strategy.exit(id = "ES_5",from_entry = "S_5", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
// ###########################################################################################
// ###########################################################################################
long_exit_price = str.tostring(math.round_to_mintick(close*(1+percent_change)))
short_exit_price = str.tostring(math.round_to_mintick(close*(1-percent_change)))
if tewnty_grid and close > low_price and ( trade_direction == 'LONG' or trade_direction == 'BOTH')
if long_1 and strategy.opentrades == 0 and inDateRange and stop_close_all == ""
strategy.entry(id = "L_1", direction = strategy.long,alert_message = Long_message, qty = qty_new )
if strategy.opentrades == 1
strategy.exit(id = "E_1",from_entry = "L_1", qty_percent = 100,alert_message = Long_Exit_message,stop = 0, limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
if long_2 and strategy.opentrades == 1 and inDateRange and close < strategy.opentrades.entry_price(strategy.opentrades - 1) * (1-percent_change) and stop_close_all == ""
strategy.entry(id = "L_2", direction = strategy.long,alert_message = Long_message, qty = qty_new )
if strategy.opentrades == 2
strategy.exit(id = "E_2",from_entry = "L_2", qty_percent = 100,alert_message =Long_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
if long_3 and strategy.opentrades == 2 and inDateRange and close < strategy.opentrades.entry_price(strategy.opentrades - 1) * (1-percent_change) and stop_close_all == ""
strategy.entry(id = "L_3", direction = strategy.long,alert_message = Long_message, qty = qty_new )
if strategy.opentrades == 3
strategy.exit(id = "E_3",from_entry = "L_3", qty_percent = 100,alert_message =Long_Exit_message,limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
if long_4 and strategy.opentrades == 3 and inDateRange and close < strategy.opentrades.entry_price(strategy.opentrades - 1) * (1-percent_change) and stop_close_all == ""
strategy.entry(id = "L_4", direction = strategy.long,alert_message = Long_message, qty = qty_new )
if strategy.opentrades == 4
strategy.exit(id = "E_4",from_entry = "L_4", qty_percent = 100,alert_message =Long_Exit_message,limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
if long_5 and strategy.opentrades == 4 and inDateRange and close < strategy.opentrades.entry_price(strategy.opentrades - 1) * (1-percent_change) and stop_close_all == ""
strategy.entry(id = "L_5", direction = strategy.long,alert_message = Long_message, qty = qty_new )
if strategy.opentrades == 5
strategy.exit(id = "E_5",from_entry = "L_5", qty_percent = 100,alert_message =Long_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
if long_6 and strategy.opentrades == 5 and inDateRange and close < strategy.opentrades.entry_price(strategy.opentrades - 1) * (1-percent_change) and stop_close_all == ""
strategy.entry(id = "L_6", direction = strategy.long,alert_message = Long_message, qty = qty_new )
if strategy.opentrades == 6
strategy.exit(id = "E_6",from_entry = "L_6", qty_percent = 100,alert_message =Long_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
if long_7 and strategy.opentrades == 6 and inDateRange and close < strategy.opentrades.entry_price(strategy.opentrades - 1) * (1-percent_change) and stop_close_all == ""
strategy.entry(id = "L_7", direction = strategy.long,alert_message = Long_message, qty = qty_new )
if strategy.opentrades == 7
strategy.exit(id = "E_7",from_entry = "L_7", qty_percent = 100,alert_message =Long_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
if long_8 and strategy.opentrades == 7 and inDateRange and close < strategy.opentrades.entry_price(strategy.opentrades - 1) * (1-percent_change) and stop_close_all == ""
strategy.entry(id = "L_8", direction = strategy.long,alert_message = Long_message, qty = qty_new )
if strategy.opentrades == 8
strategy.exit(id = "E_8",from_entry = "L_8", qty_percent = 100,alert_message =Long_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
if long_9 and strategy.opentrades == 8 and inDateRange and close < strategy.opentrades.entry_price(strategy.opentrades - 1) * (1-percent_change) and stop_close_all == ""
strategy.entry(id = "L_9", direction = strategy.long,alert_message = Long_message, qty = qty_new )
if strategy.opentrades == 9
strategy.exit(id = "E_9",from_entry = "L_9", qty_percent = 100,alert_message =Long_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
if long_10 and strategy.opentrades == 9 and inDateRange and close < strategy.opentrades.entry_price(strategy.opentrades - 1) * (1-percent_change) and stop_close_all == ""
strategy.entry(id = "L_10", direction = strategy.long,alert_message = Long_message, qty = qty_new )
if strategy.opentrades == 10
strategy.exit(id = "E_10",from_entry = "L_10", qty_percent = 100,alert_message =Long_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
// ##### STOP LOSS CODES #####
if use_stop and low < low_price_stop and strategy.position_size > 0
strategy.close_all(alert_message =Long_Stop_message, immediately = true)
stop_close_all := "DONT"
// ###########################################################################################
if tewnty_grid and close < high_price and ( trade_direction == 'SHORT' or trade_direction == 'BOTH')
if short_1 and strategy.opentrades == 0 and inDateRange and stop_close_all == ""
strategy.entry(id = "S_1", direction = strategy.short,alert_message = Short_message, qty = qty_new )
if strategy.opentrades == 1
strategy.exit(id = "ES_1",from_entry = "S_1", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
if short_2 and strategy.opentrades == 1 and inDateRange and close > strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change) and stop_close_all == ""
strategy.entry(id = "S_2",direction = strategy.short,alert_message = Short_message, qty = qty_new )
if strategy.opentrades == 2
strategy.exit(id = "ES_2",from_entry = "S_2", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
if short_3 and strategy.opentrades == 2 and inDateRange and close > strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change) and stop_close_all == ""
strategy.entry(id = "S_3", direction = strategy.short,alert_message = Short_message, qty = qty_new )
if strategy.opentrades == 3
strategy.exit(id = "ES_3",from_entry = "S_3", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
if short_4 and strategy.opentrades == 3 and inDateRange and close > strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change) and stop_close_all == ""
strategy.entry(id = "S_4", direction = strategy.short,alert_message = Short_message, qty = qty_new )
if strategy.opentrades == 4
strategy.exit(id = "ES_4",from_entry = "S_4", qty_percent = 100,alert_message =Short_Exit_message,limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
if short_5 and strategy.opentrades == 4 and inDateRange and close > strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change) and stop_close_all == ""
strategy.entry(id = "S_5", direction = strategy.short,alert_message = Short_message, qty = qty_new )
if strategy.opentrades == 5
strategy.exit(id = "ES_5",from_entry = "S_5", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
if short_6 and strategy.opentrades == 5 and inDateRange and close > strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change) and stop_close_all == ""
strategy.entry(id = "S_6", direction = strategy.short,alert_message = Short_message, qty = qty_new )
if strategy.opentrades == 6
strategy.exit(id = "ES_6",from_entry = "S_6", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
if short_7 and strategy.opentrades == 6 and inDateRange and close > strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change) and stop_close_all == ""
strategy.entry(id = "S_7", direction = strategy.short,alert_message = Short_message, qty = qty_new )
if strategy.opentrades == 7
strategy.exit(id = "ES_7",from_entry = "S_7", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
if short_8 and strategy.opentrades == 7 and inDateRange and close > strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change) and stop_close_all == ""
strategy.entry(id = "S_8", direction = strategy.short,alert_message = Short_message, qty = qty_new )
if strategy.opentrades == 8
strategy.exit(id = "ES_8",from_entry = "S_8", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
if short_9 and strategy.opentrades == 8 and inDateRange and close > strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change) and stop_close_all == ""
strategy.entry(id = "S_9", direction = strategy.short,alert_message = Short_message, qty = qty_new )
if strategy.opentrades == 9
strategy.exit(id = "ES_9",from_entry = "S_9", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
if short_10 and strategy.opentrades == 9 and inDateRange and close > strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change) and stop_close_all == ""
strategy.entry(id = "S_10", direction = strategy.short,alert_message = Short_message, qty = qty_new )
if strategy.opentrades == 10
strategy.exit(id = "ES_10",from_entry = "S_10", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
// ###########################################################################################
if use_stop and high > high_price_stop and strategy.position_size < 0
strategy.close_all(alert_message =Short_Stop_message, immediately = true)
stop_close_all := "DONT"
bgcolor(stop_close_all == "DONT" and stop_close_all[1] != "DONT" ? color.rgb(255, 42, 42) : na )
//// ########################################################################
// Plot Functions
plot(strategy.position_size < 0 ? strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change) : na , color= color.rgb(247, 85, 85), linewidth= 1, style=plot.style_cross)
plot(strategy.position_size > 0 ? strategy.opentrades.entry_price(strategy.opentrades - 1)*(1+percent_change) : na , color= color.rgb(136, 247, 85), linewidth= 1, style=plot.style_cross)
plot(inDateRange ? high_price_stop : na, color= color.rgb(255, 37, 37), linewidth =4 )
plot(inDateRange ? low_price_stop : na, color= color.rgb(255, 34, 37), linewidth =4 )
plot(inDateRange ? high_price : na, color= color.rgb(0, 0, 0), linewidth =3 )
plot(inDateRange ? low_price : na, color= color.rgb(255, 255, 255), linewidth =3 )
plot(inDateRange ? (high_price + low_price) / 2 : na , color= color.rgb(0, 68, 255), linewidth = 2 )
// ###########################################################################################
var float new_ten_grid_1 = na
var float new_ten_grid_2 = na
var float new_ten_grid_3 = na
var float new_ten_grid_4 = na
var float new_ten_grid_5 = na
var float new_ten_grid_6 = na
var float new_ten_grid_7 = na
var float new_ten_grid_8 = na
var float new_ten_grid_9 = na
var float new_ten_grid_10 = na
if ten_grid == true and show_grid_level_bg and inDateRange
new_ten_grid_1 := grid_1
new_ten_grid_2 := grid_2
new_ten_grid_3 := grid_3
new_ten_grid_4 := grid_4
new_ten_grid_5 := grid_5
new_ten_grid_6 := grid_6
new_ten_grid_7 := grid_7
new_ten_grid_8 := grid_8
new_ten_grid_9 := grid_9
new_ten_grid_10 := grid_10
else if ten_grid == false
new_ten_grid_1 := na
new_ten_grid_2 := na
new_ten_grid_3 := na
new_ten_grid_4 := na
new_ten_grid_5 := na
new_ten_grid_6 := na
new_ten_grid_7 := na
new_ten_grid_8 := na
new_ten_grid_9 := na
new_ten_grid_10 := na
fill(plot(inDateRange ? new_ten_grid_1 : na , color = color.new(color.green, 90)),
plot(inDateRange ? new_ten_grid_2 : na , color = color.new(color.green, 90)),
color = color.new(color.green, 90))
fill(plot(inDateRange ? new_ten_grid_2 : na , color = color.new(color.green, 85)),
plot(inDateRange ? new_ten_grid_3 : na , color = color.new(color.green, 85)),
color = color.new(color.green, 85))
fill(plot(inDateRange ? new_ten_grid_3 : na , color = color.new(color.green, 80)),
plot(inDateRange ? new_ten_grid_4 : na , color = color.new(color.green, 80)),
color = color.new(color.green, 80))
fill(plot(inDateRange ? new_ten_grid_4 : na , color = color.new(color.green, 70)),
plot(inDateRange ? new_ten_grid_5 : na , color = color.new(color.green, 70)),
color = color.new(color.green, 70))
fill(plot(inDateRange ? new_ten_grid_5 : na , color = color.new(color.green, 60)),
plot(inDateRange ? new_ten_grid_6 : na, color = color.new(color.green, 60)),
color = color.new(color.green, 60))
fill(plot(inDateRange ? new_ten_grid_6 : na, color = color.new(color.red, 60)),
plot(inDateRange ? new_ten_grid_7 : na, color = color.new(color.red, 60)),
color = color.new(color.red, 60))
fill(plot(inDateRange ? new_ten_grid_7 : na, color = color.new(color.red, 70)),
plot(inDateRange ? new_ten_grid_8 : na, color = color.new(color.red, 70)),
color = color.new(color.red, 70))
fill(plot(inDateRange ? new_ten_grid_8 : na, color = color.new(color.red, 80)),
plot(inDateRange ? new_ten_grid_9 : na, color = color.new(color.red, 80)),
color = color.new(color.red, 80))
fill(plot(inDateRange ? new_ten_grid_9 : na, color = color.new(color.red, 85)),
plot(inDateRange ? new_ten_grid_10 : na, color = color.new(color.red, 85)),
color = color.new(color.red, 85))
// // ###########################################################################################
var float new_twenty_grid_1 = na
var float new_twenty_grid_2 = na
var float new_twenty_grid_3 = na
var float new_twenty_grid_4 = na
var float new_twenty_grid_5 = na
var float new_twenty_grid_6 = na
var float new_twenty_grid_7 = na
var float new_twenty_grid_8 = na
var float new_twenty_grid_9 = na
var float new_twenty_grid_10 = na
var float new_twenty_grid_11 = na
var float new_twenty_grid_12 = na
var float new_twenty_grid_13 = na
var float new_twenty_grid_14 = na
var float new_twenty_grid_15 = na
var float new_twenty_grid_16 = na
var float new_twenty_grid_17 = na
var float new_twenty_grid_18 = na
var float new_twenty_grid_19 = na
var float new_twenty_grid_20 = na
if tewnty_grid == true and show_grid_level_bg and inDateRange
new_twenty_grid_1 := grid_1
new_twenty_grid_2 := grid_2
new_twenty_grid_3 := grid_3
new_twenty_grid_4 := grid_4
new_twenty_grid_5 := grid_5
new_twenty_grid_6 := grid_6
new_twenty_grid_7 := grid_7
new_twenty_grid_8 := grid_8
new_twenty_grid_9 := grid_9
new_twenty_grid_10 := grid_10
new_twenty_grid_11 := grid_11
new_twenty_grid_12 := grid_12
new_twenty_grid_13 := grid_13
new_twenty_grid_14 := grid_14
new_twenty_grid_15 := grid_15
new_twenty_grid_16 := grid_16
new_twenty_grid_17 := grid_17
new_twenty_grid_18 := grid_18
new_twenty_grid_19 := grid_19
new_twenty_grid_20 := grid_20
else if tewnty_grid == false
new_twenty_grid_1 := na
new_twenty_grid_2 := na
new_twenty_grid_3 := na
new_twenty_grid_4 := na
new_twenty_grid_5 := na
new_twenty_grid_6 := na
new_twenty_grid_7 := na
new_twenty_grid_8 := na
new_twenty_grid_9 := na
new_twenty_grid_10 := na
new_twenty_grid_11 := na
new_twenty_grid_12 := na
new_twenty_grid_13 := na
new_twenty_grid_14 := na
new_twenty_grid_15 := na
new_twenty_grid_16 := na
new_twenty_grid_17 := na
new_twenty_grid_18 := na
new_twenty_grid_19 := na
new_twenty_grid_20 := na
fill(plot(inDateRange ? new_twenty_grid_1 : na , color = color.new(color.green, 90)),
plot(inDateRange ? new_twenty_grid_2 : na , color = color.new(color.green, 90)),
color = color.new(color.green, 90))
fill(plot(inDateRange ? new_twenty_grid_2 : na , color = color.new(color.green, 85)),
plot(inDateRange ? new_twenty_grid_3 : na , color = color.new(color.green, 85)),
color = color.new(color.green, 85))
fill(plot(inDateRange ? new_twenty_grid_3 : na , color = color.new(color.green, 80)),
plot(inDateRange ? new_twenty_grid_4 : na , color = color.new(color.green, 80)),
color = color.new(color.green, 80))
fill(plot(inDateRange ? new_twenty_grid_4 : na , color = color.new(color.green, 70)),
plot(inDateRange ? new_twenty_grid_5 : na , color = color.new(color.green, 70)),
color = color.new(color.green, 70))
fill(plot(inDateRange ? new_twenty_grid_5 : na , color = color.new(color.green, 60)),
plot(inDateRange ? new_twenty_grid_6 : na , color = color.new(color.green, 60)),
color = color.new(color.green, 60))
fill(plot(inDateRange ? new_twenty_grid_6 : na , color = color.new(color.green, 60)),
plot(inDateRange ? new_twenty_grid_7 : na , color = color.new(color.green, 60)),
color = color.new(color.green, 60))
fill(plot(inDateRange ? new_twenty_grid_7 : na , color = color.new(color.green, 70)),
plot(inDateRange ? new_twenty_grid_8 : na , color = color.new(color.green, 70)),
color = color.new(color.green, 70))
fill(plot(inDateRange ? new_twenty_grid_8 : na , color = color.new(color.green, 80)),
plot(inDateRange ? new_twenty_grid_9 : na , color = color.new(color.green, 80)),
color = color.new(color.green, 80))
fill(plot(inDateRange ? new_twenty_grid_9 : na , color = color.new(color.green, 85)),
plot(inDateRange ? new_twenty_grid_10 : na , color = color.new(color.green, 85)),
color = color.new(color.green, 85))
fill(plot(inDateRange ? new_twenty_grid_10 : na , color = color.new(color.red, 90)),
plot(inDateRange ? new_twenty_grid_11 : na , color = color.new(color.red, 90)),
color = color.new(color.red, 90))
fill(plot(inDateRange ? new_twenty_grid_11 : na , color = color.new(color.red, 85)),
plot(inDateRange ? new_twenty_grid_12 : na , color = color.new(color.red, 85)),
color = color.new(color.red, 85))
fill(plot(inDateRange ? new_twenty_grid_12 : na , color = color.new(color.red, 80)),
plot(inDateRange ? new_twenty_grid_13 : na , color = color.new(color.red, 80)),
color = color.new(color.red, 80))
fill(plot(inDateRange ? new_twenty_grid_13 : na , color = color.new(color.red, 70)),
plot(inDateRange ? new_twenty_grid_14 : na , color = color.new(color.red, 70)),
color = color.new(color.red, 70))
fill(plot(inDateRange ? new_twenty_grid_14 : na , color = color.new(color.red, 60)),
plot(inDateRange ? new_twenty_grid_15 : na , color = color.new(color.red, 60)),
color = color.new(color.red, 60))
fill(plot(inDateRange ? new_twenty_grid_15 : na , color = color.new(color.red, 60)),
plot(inDateRange ? new_twenty_grid_16 : na , color = color.new(color.red, 60)),
color = color.new(color.red, 60))
fill(plot(inDateRange ? new_twenty_grid_16 : na , color = color.new(color.red, 70)),
plot(inDateRange ? new_twenty_grid_17 : na , color = color.new(color.red, 70)),
color = color.new(color.red, 70))
fill(plot(inDateRange ? new_twenty_grid_17 : na , color = color.new(color.red, 80)),
plot(inDateRange ? new_twenty_grid_18 : na , color = color.new(color.red, 80)),
color = color.new(color.red, 80))
fill(plot(inDateRange ? new_twenty_grid_18 : na , color = color.new(color.red, 85)),
plot(inDateRange ? new_twenty_grid_19 : na , color = color.new(color.red, 85)),
color = color.new(color.red, 85))
fill(plot(inDateRange ? new_twenty_grid_19 : na , color = color.new(color.red, 85)),
plot(inDateRange ? new_twenty_grid_20 : na , color = color.new(color.red, 85)),
color = color.new(color.red, 85))
// // ###########################################################################################
//###############################################################################################
//------------------------------Table
//###############################################################################################
showDashboard = input.bool(true, "Show Table", group=" ############# 🔳 TABLE Settings 🔳 ############ ")
locationDashboard = input.string("Top Right", "Table Location", ["Top Right", "Middle Right", "Bottom Right", "Top Center", "Middle Center", "Bottom Center", "Top Left", "Middle Left", "Bottom Left"], group=" ############# 🔳 TABLE Settings 🔳 ############ ")
sizeDashboard = input.string("Normal", "Table Size", ["Large", "Normal", "Small", "Tiny"], group=" ############# 🔳 TABLE Settings 🔳 ############ ")
var dashboard_loc = locationDashboard == "Top Right" ? position.top_right : locationDashboard == "Middle Right" ? position.middle_right : locationDashboard == "Bottom Right" ? position.bottom_right : locationDashboard == "Top Center" ? position.top_center : locationDashboard == "Middle Center" ? position.middle_center : locationDashboard == "Bottom Center" ? position.bottom_center : locationDashboard == "Top Left" ? position.top_left : locationDashboard == "Middle Left" ? position.middle_left : position.bottom_left
var dashboard_size = sizeDashboard == "Large" ? size.large : sizeDashboard == "Normal" ? size.normal : sizeDashboard == "Small" ? size.small : size.tiny
if showDashboard
var myTable = table.new(position = dashboard_loc, columns = 5, rows = 2,bgcolor = color.white, border_width = 1, frame_color = color.rgb(25, 150, 25), frame_width = 3, border_color = color.rgb(25, 150, 25))
table.cell(table_id = myTable, column = 0, row = 0, text = "Open positions" , text_color = color.white, bgcolor = color.orange, text_size=dashboard_size)
table.cell(table_id = myTable, column = 1, row = 0, text = "Open profit" , text_color = color.white, bgcolor = color.orange, text_size=dashboard_size)
table.cell(table_id = myTable, column = 2, row = 0, text = "Total trades" , text_color = color.white, bgcolor = color.orange, text_size=dashboard_size)
table.cell(table_id = myTable, column = 3, row = 0, text = "Total profit" , text_color = color.white, bgcolor = color.orange, text_size=dashboard_size)
table.cell(table_id = myTable, column = 4, row = 0, text = "Current equity" , text_color = color.white, bgcolor = color.orange, text_size=dashboard_size)
table.cell(table_id = myTable, column = 0, row = 1, text = str.tostring(strategy.opentrades) , text_font_family = font.family_monospace, text_size=dashboard_size)
table.cell(table_id = myTable, column = 1, row = 1, text = "$" + str.tostring(math.round(strategy.openprofit, 1)) , bgcolor = strategy.openprofit >= 0 ? color.green : color.red , text_font_family = font.family_monospace, text_size=dashboard_size)
table.cell(table_id = myTable, column = 2, row = 1, text = str.tostring(strategy.closedtrades) , text_font_family = font.family_monospace, text_size=dashboard_size)
table.cell(table_id = myTable, column = 3, row = 1, text = "$" + str.tostring(math.round(strategy.netprofit, 1)) , bgcolor = strategy.netprofit >= 0 ? color.green : color.red , text_font_family = font.family_monospace, text_size=dashboard_size)
table.cell(table_id = myTable, column = 4, row = 1, text = "$" + str.tostring(math.round(strategy.equity, 1)) , bgcolor = strategy.equity >= 0 ? color.green : color.red , text_font_family = font.family_monospace, text_size=dashboard_size) |
Optimized Zhaocaijinbao strategy | https://www.tradingview.com/script/lqsxAH8y/ | fzj20020403 | https://www.tradingview.com/u/fzj20020403/ | 80 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © fzj20020403
////@version=5
//@version=5
strategy("Optimized Zhaocaijinbao", overlay=true, margin_long=100, margin_short=0, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
// Define two moving averages
ma6 = ta.sma(close, 6)
ma35 = ta.sma(close, 35)
// Define buy and sell signal lines
buyLine = ta.ema(close, 2)
sellSlope = (close - close[8]) / 8
sellLine = sellSlope * 1 + ta.sma(close, 8)
// Define volume indicator
volumeEMA = ta.ema(volume, 20)
// Define weekly slope factor
weeklyMa = ta.sma(close, 50)
weeklySlope = (weeklyMa - weeklyMa[4]) / 4 > 0
// Generate buy and sell signals
buySignal = ta.crossover(buyLine, sellLine) and close > ma35 and volume > volumeEMA and weeklySlope
sellSignal = ta.crossunder(sellLine, buyLine)
// Define dynamic position sizing factor
equity = strategy.equity
maxPositionSize = equity * input.float(title='Max Position Size (%)', defval=0.01, minval=0.001, maxval=0.5, step=0.001)
riskFactor = input.float(title='Risk Factor', defval=2.0, minval=0.1, maxval=10.0, step=0.1)
atr = ta.atr(14)
positionSize = maxPositionSize * riskFactor / atr
// Define position status
var inPosition = false
// Define buy and sell conditions
buyCondition = buySignal and not inPosition
sellCondition = sellSignal and inPosition
// Perform buy and sell operations
if (buyCondition)
strategy.entry("Long", strategy.long, qty=positionSize)
inPosition := true
if (sellCondition)
strategy.close("Long")
inPosition := false
// Draw vertical line markers for buy and sell signals
plotshape(buyCondition, style=shape.arrowdown, location=location.belowbar, color=color.green, size=size.small)
plotshape(sellCondition, style=shape.arrowup, location=location.abovebar, color=color.red, size=size.small)
// Draw two moving averages
plot(ma6, color=color.blue)
plot(ma35, color=color.orange)
// Draw volume indicator line
plot(volumeEMA, color=color.yellow)
// Define stop loss and take profit
stopLoss = strategy.position_avg_price * 0.5
takeProfit = strategy.position_avg_price * 1.25
if inPosition
strategy.exit("Long Stop Loss", "Long", stop=stopLoss)
strategy.exit("Long Take Profit", "Long", limit=takeProfit)
|
Boftei's Strategy | https://www.tradingview.com/script/c9p5U3DN-boftei-s-strategy/ | boftei | https://www.tradingview.com/u/boftei/ | 73 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © boftei
//@version=5
strategy("Boftei's Strategy", overlay=false, pyramiding=1, default_qty_type= strategy.percent_of_equity, default_qty_value = 100, calc_on_order_fills=false, margin_long = 100, margin_short = 100, slippage=0, commission_type=strategy.commission.percent, commission_value = 0, initial_capital = 40, precision = 6)
strat_dir_input = input.string("all", "strategy direction", options=["long", "short", "all"])
strat_dir_value = strat_dir_input == "long" ? strategy.direction.long : strat_dir_input == "short" ? strategy.direction.short : strategy.direction.all
strategy.risk.allow_entry_in(strat_dir_value)
//////////////////////////////////////////////////////////////////////
//DATA
testStartYear = input(2005, "Backtest Start Year")
testStartMonth = input(7, "Backtest Start Month")
testStartDay = input(16, "Backtest Start Day")
testPeriodStart = timestamp(testStartYear,testStartMonth,testStartDay,0,0)
//Stop date if you want to use a specific range of dates
testStopYear = input(2030, "Backtest Stop Year")
testStopMonth = input(12, "Backtest Stop Month")
testStopDay = input(30, "Backtest Stop Day")
testPeriodStop = timestamp(testStopYear,testStopMonth,testStopDay,0,0)
testPeriod() =>
time >= testPeriodStart and time <= testPeriodStop ? true : false
//////////////////////////////////////////////////////////////////////
sell = input.float(0.0065, "sell level")
buy = input.float(0, "buy level")
long1 = input.float(-0.493, "long retry - too low")
long2 = input.float(2.2, "long close up")
long3 = input.float(-1.5, "long close down")
short1 = input.float(0.8, "short retry - too high")
short2 = input.float(-5, "dead - close the short")
///< botvenko script
nn = input(60, "Histogram Period")
float x = 0
float z = 0
float k = 0
y = math.log(close[0]) - math.log(close[nn])
if y>0
x := y
else
k := y
//---------------------------------------------
plot(y > 0 ? x: 0, color = color.green, linewidth = 4)
plot(y <= 0 ? k: 0, color = color.maroon, linewidth = 4)
plot(y, color = color.yellow, linewidth = 1)
co = ta.crossover(y, buy)
cu = ta.crossunder(y, sell)
retry_long = ta.crossunder(y, long1)
deadline_long_up = ta.crossover(y, long2)
deadline_long_down = ta.crossunder(y, long3)
retry_short = ta.crossover(y, short1)
deadline_short = ta.crossunder(y, short2)
hline(buy, title='buy', color=color.green, linestyle=hline.style_dotted, linewidth=2)
hline(0, title='zero', color=color.white, linestyle=hline.style_dotted, linewidth=1)
hline(sell, title='sell', color=color.red, linestyle=hline.style_dotted, linewidth=2)
hline(long1, title='long retry', color=color.blue, linestyle=hline.style_dotted, linewidth=2)
hline(long2, title='overbought', color=color.teal, linestyle=hline.style_dotted, linewidth=2)
hline(long3, title='oversold', color=color.maroon, linestyle=hline.style_dotted, linewidth=2)
hline(short1, title='short retry', color=color.purple, linestyle=hline.style_dotted, linewidth=2)
hline(short2, title='too low to short - an asset may die', color=color.navy, linestyle=hline.style_dotted, linewidth=2)
////////////////////////////////////////////////////////////EMAprotectionBLOCK
ema_21 = ta.ema(close, 21)
ema_55 = ta.ema(close, 55)
ema_89 = ta.ema(close, 89)
ema_144 = ta.ema(close, 144)
ema_233 = ta.ema(close, 233)
//ema_377 = ta.ema(close, 377)
long_st = ema_21>ema_55 and ema_55>ema_89 and ema_89>ema_144 and ema_144>ema_233// and ema_233>ema_377
short_st = ema_21<ema_55 and ema_55<ema_89 and ema_89<ema_144 and ema_144<ema_233// and ema_233<ema_377
g_v = long_st == true?3:0
r_v = short_st == true?-2:0
y_v = long_st != true and short_st != true?2:0
plot(math.log(ema_21), color = color.new(#ffaf5e, 50))
plot(math.log(ema_55), color = color.new(#b9ff5e, 50))
plot(math.log(ema_89), color = color.new(#5eff81, 50))
plot(math.log(ema_144), color = color.new(#5effe4, 50))
plot(math.log(ema_233), color = color.new(#5e9fff, 50))
//plot(math.log(ema_377), color = color.new(#af5eff, 50))
plot(long_st == true?3:0, color = color.new(color.green, 65), linewidth = 5)
plot(short_st == true?-2:0, color = color.new(color.red, 65), linewidth = 5)
plot(long_st != true and short_st != true?2:0, color = color.new(color.yellow, 65), linewidth = 5)
////////////////////////////////////////////////////////////EMAprotectionBLOCK
if (co and testPeriod() and (g_v == 3 or y_v == 2))
strategy.close("OH BRO", comment = "EXIT-SHORT")
strategy.close("OH DUDE", comment = "EXIT-SHORT")
strategy.entry("OH DAMN", strategy.long, comment="ENTER-LONG 'co'")
if (retry_long and testPeriod() and (g_v == 3 or y_v == 2))
strategy.close("OH DAMN", comment = "EXIT-LONG")
strategy.entry("OH BRUH", strategy.long, comment="ENTER-LONG 'retry_long'")
if (cu and testPeriod() and (r_v == -2 or y_v == 2))
strategy.close("OH DAMN", comment = "EXIT-LONG")
strategy.close("OH BRUH", comment = "EXIT-LONG")
strategy.entry("OH BRO", strategy.short, comment="ENTER-SHORT 'cu'")
if (retry_short and testPeriod() and (r_v == -2 or y_v == 2))
strategy.close("OH BRO", comment = "EXIT-SHORT")
strategy.entry("OH DUDE", strategy.short, comment="ENTER-SHORT 'retry_short'")
if (deadline_long_up and testPeriod() or r_v == -2 and testPeriod())
strategy.close("OH DAMN", comment = "EXIT-LONG 'deadline_long_up'")
strategy.close("OH BRUH", comment = "EXIT-LONG 'deadline_long_up'")
if (deadline_long_down and testPeriod())
strategy.close("OH DAMN", comment = "EXIT-LONG 'deadline_long_down'")
strategy.close("OH BRUH", comment = "EXIT-LONG 'deadline_long_down'")
if (deadline_short and testPeriod() or g_v == 3 and testPeriod())
strategy.close("OH BRO", comment = "EXIT-SHORT 'deadline_short'")
strategy.close("OH DUDE", comment = "EXIT-SHORT 'deadline_short'")
// (you can use strategy.close_all(comment = "close all entries") here)
|
Strategy Designer | https://www.tradingview.com/script/Hp05f5Dq/ | only_fibonacci | https://www.tradingview.com/u/only_fibonacci/ | 2,123 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © only_fibonacci
//@version=5
strategy("Strategy Designer", overlay=true)
// FUNCTIONS
operatorReturn(i1,selected,i2)=>
switch selected
">" => i1 > i2
"<" => i1 < i2
">=" => i1 >= i2
"<=" => i1 <= i2
"=" => i1 == i2
"!=" => i1 != i2
"CROSS ABOVE" => ta.crossover(i1, i2)
"CROSS BELOW" => ta.crossunder(i1,i2)
maTypeToMa(maType,maPeriod,src)=>
switch maType
"EMA" => ta.ema(src, maPeriod)
"SMA" => ta.sma(src, maPeriod)
"RMA" => ta.rma(src, maPeriod)
=> ta.wma(src, maPeriod)
// Indicators
// ATR
atrLen = input.int(defval = 14,minval = 1, title = "ATR Length", group = "ATR")
atr = ta.atr(atrLen) // ATR
// BB
bbMiddle = input.source(defval = close, title = "BB Middle", group = "BB")
bbLen = input.int(defval = 5, title = "BB Length",minval = 1, group = "BB")
bbMult = input.int(defval = 4, title = "BB Mult",minval = 1, group = "BB" )
[middle, upper, lower] = ta.bb(bbMiddle, bbLen, bbMult) // BB
bbw = ta.bbw(middle, bbLen, bbMult) // BB Genişlik
// CCI
cciSrc = input.source(defval = close, title = "CCI Source", group = "CCI")
cciLen = input.int(defval = 10, title = "CCI Len", minval = 1, group = "CCI")
cci = ta.cci(cciSrc,cciLen) // CCI
// MA1
ma1Type = input.string("EMA", "", options = ["EMA", "SMA", "RMA", "WMA"], group = "MA 1", inline = "2ma1")
ma1Period = input.int(defval = 20, title = "Period", minval = 1, group = "MA 1", inline = "2ma1")
ma1Src = input.source(defval = close, title = "Source", group = "MA 1", inline = "2ma1")
ma1 = maTypeToMa(ma1Type,ma1Period,ma1Src)
// MA2
ma2Type = input.string("EMA", "", options = ["EMA", "SMA", "RMA", "WMA"], group = "MA 2", inline = "2ma2")
ma2Period = input.int(defval = 50, title = "Period", minval = 1, group = "MA 2", inline = "2ma2")
ma2Src = input.source(defval = close, title = "Source", group = "MA 2", inline = "2ma2")
ma2 = maTypeToMa(ma2Type,ma2Period,ma1Src)
// RSI
rsiSrc = input.source(defval = close, title = "RSI Source", group = "RSI")
rsiLen = input.int(defval = 14, title = "RSI Length", minval = 1, group = "RSI")
rsi = ta.rsi(rsiSrc,rsiLen)
// ADX
lenAdx = input.int(17, minval=1, title="DI Length", group = "ADX")
lensigAdx = input.int(14, title="ADX Smoothing", minval=1, maxval=50, group = "ADX")
[diplus, diminus, adx] = ta.dmi(lenAdx, lensigAdx)
// MFI
mfiSrc = input.source(defval = close, title = "MFI Source", group = "MFI")
mfiLen = input.int(defval = 14, title = "MFI Length", minval = 1, group = "MFI")
mfi = ta.mfi(mfiSrc,mfiLen)
// MOM
momSrc = input.source(defval = close, title = "MOM Source", group = "MOM")
momLen = input.int(defval = 14, title = "MOM Length", minval = 1, group = "MOM")
mom = ta.mom(momSrc,momLen)
indicators(selected)=>
switch selected
"MA 1" => ma1
"MA 2" => ma2
"ATR" => atr
"CCI" => cci
"RSI" => rsi
"BBW" => bbw
"ADX" => adx
"MFI" => mfi
"MOM" => mom
position(data)=>
switch data
"ABOVE" => location.abovebar
=> location.belowbar
location(data)=>
switch data
"ABOVE" => true
=> false
style(data)=>
switch data
"ABOVE" => shape.labeldown
=> shape.labelup
// SETTINGS
/////////// USE BACKTEST START DATE
useFilter = input.bool(true, title="USE Backtest at Start Date", group="SETTINGS")
backtestStartDate = input.time(timestamp("1 Jan 2011"), title="Start Date", group="SETTINGS")
backtestStopDate = input.time(timestamp("2025"), title="Stop Date", group="SETTINGS")
inTrade = not useFilter or (time >= backtestStartDate and time <= backtestStopDate )
tableShow = input.bool(defval = true, title = "Show Table", group = "SETTINGS")
andORLong = input.string(defval = "AND", title = "BUY/LONG CONNECT", options = ["AND","OR"], group = "SETTINGS")
andORShort = input.string(defval = "AND", title = "SELL/SHORT CONNECT", options = ["AND","OR"], group = "SETTINGS")
futureOrSpot = input.string(defval = "SPOT", title = "FUTURE OR SPOT ?", options = ["SPOT","FUTURE"], group = "SETTINGS")
willStop = input.bool(defval = false, title = "STOP", group = "SETTINGS", inline = "stop")
willStopValue = input.float(defval = 5., title = "", group = "SETTINGS", inline = "stop")
percentageStop = input.bool(defval = true, title = "%", group = "SETTINGS", inline = "stop")
willTp = input.bool(defval = false, title = "TP", group = "SETTINGS", inline = "TP")
willTpValue = input.float(defval = 5., title = "", group = "SETTINGS", inline = "TP")
percentageTP = input.bool(defval = true, title = "%", group = "SETTINGS", inline = "TP")
willTSL = input.bool(defval = false, title = "Trailing SL", group = "SETTINGS", inline = "TSL")
willTSLValue = input.float(defval = 2., title = "", group = "SETTINGS", inline = "TSL")
percentageTSL = input.bool(defval = true, title = "%", group = "SETTINGS", inline = "TSL")
buyList = array.new_bool()
sellList = array.new_bool()
detect(status,series,di)=>
if status
if di == "BUY/LONG"
array.push(buyList,series)
else
array.push(sellList,series)
// CONDITION 1
s1Group = "❗️❗️❗️❗️ CONDITION #1 ❗️❗️❗️❗️"
s1Inline = "s1i"
s1Status = input.bool(defval = false, title = "CONDITION Active", group = s1Group )
s1Direction = input.string(defval = "BUY/LONG", title = "Direction",options = ["BUY/LONG","SELL/SHORT"], group = s1Group)
s1Left = input.string(defval = "CCI", title = "1️⃣", options = ["ATR","MA 1","MA 2","RSI","CCI","BBW", "ADX","MFI","MOM"], group = s1Group, inline = s1Inline)
s1Mid = input.string(defval = ">=", title = "", options = [">","<",">=","<=","=","!=","CROSS ABOVE","CROSS BELOW"], group = s1Group, inline = s1Inline)
s1Right = input.string(defval = "CCI", title = "2️⃣", options = ["ATR","MA 1","MA 2","RSI","CCI","BBW", "ADX","MFI","MOM"], group = s1Group, inline = s1Inline)
s1ValueBool = input.bool(defval = false, title = "VALUE ", group = s1Group, inline = "v1")
s1EndRight = input.float(defval = 0. , title = "2️⃣", group = s1Group, inline = "v1")
s1Series = operatorReturn(indicators(s1Left),s1Mid,s1ValueBool ? s1EndRight : indicators(s1Right))
detect(s1Status,s1Series,s1Direction)
// CONDITION 2
s2Group = "❗️❗️❗️❗️ CONDITION #2 ❗️❗️❗️❗️"
s2Inline = "s2i"
s2Status = input.bool(defval = false, title = "CONDITION Active", group = s2Group )
s2Direction = input.string(defval = "BUY/LONG", title = "Direction",options = ["BUY/LONG","SELL/SHORT"], group = s2Group)
s2Left = input.string(defval = "CCI", title = "1️⃣", options = ["ATR","MA 1","MA 2","RSI","CCI","BBW", "ADX","MFI","MOM"], group = s2Group, inline = s2Inline)
s2Mid = input.string(defval = ">=", title = "", options = [">","<",">=","<=","=","!=","CROSS ABOVE","CROSS BELOW"], group = s2Group, inline = s2Inline)
s2Right = input.string(defval = "CCI", title = "2️⃣", options = ["ATR","MA 1","MA 2","RSI","CCI","BBW", "ADX","MFI","MOM"], group = s2Group, inline = s2Inline)
s2ValueBool = input.bool(defval = false, title = "VALUE ", group = s2Group, inline = "v2")
s2EndRight = input.float(defval = 0. , title = "2️⃣", group = s2Group, inline = "v2")
s2Series = operatorReturn(indicators(s2Left),s2Mid,s2ValueBool ? s2EndRight : indicators(s2Right))
detect(s2Status,s2Series,s2Direction)
s3Group = "❗️❗️❗️❗️ CONDITION #3 ❗️❗️❗️❗️"
s3Inline = "s3i"
s3Status = input.bool(defval = false, title = "CONDITION Active", group = s3Group )
s3Direction = input.string(defval = "BUY/LONG", title = "Direction",options = ["BUY/LONG","SELL/SHORT"], group = s3Group)
s3Left = input.string(defval = "CCI", title = "1️⃣", options = ["ATR","MA 1","MA 2","RSI","CCI","BBW", "ADX","MFI","MOM"], group = s3Group, inline = s3Inline)
s3Mid = input.string(defval = ">=", title = "", options = [">","<",">=","<=","=","!=","CROSS ABOVE","CROSS BELOW"], group = s3Group, inline = s3Inline)
s3Right = input.string(defval = "CCI", title = "2️⃣", options = ["ATR","MA 1","MA 2","RSI","CCI","BBW", "ADX","MFI","MOM"], group = s3Group, inline = s3Inline)
s3ValueBool = input.bool(defval = false, title = "VALUE ", group = s3Group, inline = "v3")
s3EndRight = input.float(defval = 0. , title = "2️⃣", group = s3Group, inline = "v3")
s3Series = operatorReturn(indicators(s3Left),s3Mid,s3ValueBool ? s3EndRight : indicators(s3Right))
detect(s3Status,s3Series,s3Direction)
s4Group = "❗️❗️❗️❗️ CONDITION #4 ❗️❗️❗️❗️"
s4Inline = "s4i"
s4Status = input.bool(defval = false, title = "CONDITION Active", group = s4Group )
s4Direction = input.string(defval = "BUY/LONG", title = "Direction",options = ["BUY/LONG","SELL/SHORT"], group = s4Group)
s4Left = input.string(defval = "CCI", title = "1️⃣", options = ["ATR","MA 1","MA 2","RSI","CCI","BBW", "ADX","MFI","MOM"], group = s4Group, inline = s4Inline)
s4Mid = input.string(defval = ">=", title = "", options = [">","<",">=","<=","=","!=","CROSS ABOVE","CROSS BELOW"], group = s4Group, inline = s4Inline)
s4Right = input.string(defval = "CCI", title = "2️⃣", options = ["ATR","MA 1","MA 2","RSI","CCI","BBW", "ADX","MFI","MOM"], group = s4Group, inline = s4Inline)
s4ValueBool = input.bool(defval = false, title = "VALUE ", group = s4Group, inline = "v3")
s4EndRight = input.float(defval = 0. , title = "2️⃣", group = s4Group, inline = "v3")
s4Series = operatorReturn(indicators(s4Left),s4Mid,s4ValueBool ? s4EndRight : indicators(s4Right))
detect(s4Status,s4Series,s4Direction)
s5Group = "❗️❗️❗️❗️ CONDITION #5 ❗️❗️❗️❗️"
s5Inline = "s5i"
s5Status = input.bool(defval = false, title = "CONDITION Active", group = s5Group )
s5Direction = input.string(defval = "BUY/LONG", title = "Direction",options = ["BUY/LONG","SELL/SHORT"], group = s5Group)
s5Left = input.string(defval = "CCI", title = "1️⃣", options = ["ATR","MA 1","MA 2","RSI","CCI","BBW", "ADX","MFI","MOM"], group = s5Group, inline = s5Inline)
s5Mid = input.string(defval = ">=", title = "", options = [">","<",">=","<=","=","!=","CROSS ABOVE","CROSS BELOW"], group = s5Group, inline = s5Inline)
s5Right = input.string(defval = "CCI", title = "2️⃣", options = ["ATR","MA 1","MA 2","RSI","CCI","BBW", "ADX","MFI","MOM"], group = s5Group, inline = s5Inline)
s5ValueBool = input.bool(defval = false, title = "VALUE ", group = s5Group, inline = "v3")
s5EndRight = input.float(defval = 0. , title = "2️⃣", group = s5Group, inline = "v3")
s5Series = operatorReturn(indicators(s5Left),s5Mid,s5ValueBool ? s5EndRight : indicators(s5Right))
detect(s5Status,s5Series,s5Direction)
s6Group = "❗️❗️❗️❗️ CONDITION #6 ❗️❗️❗️❗️"
s6Inline = "s6i"
s6Status = input.bool(defval = false, title = "CONDITION Active", group = s6Group )
s6Direction = input.string(defval = "BUY/LONG", title = "Direction",options = ["BUY/LONG","SELL/SHORT"], group = s6Group)
s6Left = input.string(defval = "CCI", title = "1️⃣", options = ["ATR","MA 1","MA 2","RSI","CCI","BBW", "ADX","MFI","MOM"], group = s6Group, inline = s6Inline)
s6Mid = input.string(defval = ">=", title = "", options = [">","<",">=","<=","=","!=","CROSS ABOVE","CROSS BELOW"], group = s6Group, inline = s6Inline)
s6Right = input.string(defval = "CCI", title = "2️⃣", options = ["ATR","MA 1","MA 2","RSI","CCI","BBW", "ADX","MFI","MOM"], group = s6Group, inline = s6Inline)
s6ValueBool = input.bool(defval = false, title = "VALUE ", group = s6Group, inline = "v3")
s6EndRight = input.float(defval = 0. , title = "2️⃣", group = s6Group, inline = "v3")
s6Series = operatorReturn(indicators(s6Left),s6Mid,s6ValueBool ? s6EndRight : indicators(s6Right))
detect(s6Status,s6Series,s6Direction)
if inTrade and (andORLong == "AND" ? array.every(buyList) : array.includes(buyList,true) )
strategy.entry(id = "BUY", direction = strategy.long)
if inTrade and (andORShort == "AND" ? array.every(sellList) : array.includes(sellList,true))
if futureOrSpot == "SPOT"
strategy.close(id = "BUY")
else
strategy.entry(id = "SELL", direction = strategy.short)
buyStop = 0.
sellStop = 0.
entry = strategy.position_avg_price
buyStop := percentageStop ? entry *(100 - willStopValue) / 100 : entry - willStopValue
sellStop := percentageStop ? entry *(100 + willStopValue) / 100 : entry + willStopValue
buyTp = percentageTP ? entry *(100 + willTpValue) / 100 : entry + willTpValue
sellTp = percentageTP ? entry *(100 - willTpValue) / 100 : entry - willTpValue
//////// TSL
trailingLongPrice = 0.0
trailingShortPrice = 0.0
tslShortPercent = percentageTSL
tslLongPercent = percentageTSL
if strategy.position_size > 0
stopValue = percentageTSL ? low * (100 - willTSLValue) / 100 : low - willTSLValue
trailingLongPrice := math.max(stopValue, trailingLongPrice[1])
else
trailingLongPrice:=0
if strategy.position_size <0
stopValue = percentageTSL ? high * (100 + willTSLValue) / 100 : high + willTSLValue
trailingShortPrice := math.min(stopValue, trailingShortPrice[1])
else
trailingShortPrice :=99999
plot(strategy.position_size > 0 and willTSL ? trailingLongPrice : na , color=color.green, linewidth=3,style = plot.style_linebr)
plot(strategy.position_size < 0 and willTSL ? trailingShortPrice : na , color = color.red, linewidth=3, style = plot.style_linebr)
strategy.exit("EXIT", from_entry = "BUY", stop = willStop and willTSL ? trailingLongPrice : willTSL ? trailingLongPrice : willStop and willTSL == false ? buyStop :na, limit = willTp ? buyTp : na )
strategy.exit("EXIT", from_entry = "SELL", stop = willStop and willTSL ? trailingShortPrice : willTSL ? trailingShortPrice : willStop and willTSL == false ? sellStop :na, limit = willTp ? sellTp : na)
if tableShow
// COLUMNS
var table tablo = table.new(position.top_right,2,7,border_width=4,border_color=color.gray, frame_color=color.gray, frame_width=4)
table.cell(tablo,0,0,bgcolor=color.black,text_color=color.white, text="NET PROFIT")
table.cell(tablo,0,1,bgcolor=color.black,text_color=color.white, text="TOTAL PROFIT")
table.cell(tablo,0,2,bgcolor=color.black,text_color=color.white, text="TOTAL LOSS")
table.cell(tablo,0,3,bgcolor=color.black,text_color=color.white, text="PROFIT FACTOR")
table.cell(tablo,0,4,bgcolor=color.black,text_color=color.white, text="WIN TRADES")
table.cell(tablo,0,5,bgcolor=color.black,text_color=color.white, text="LOSS TRADES")
table.cell(tablo,0,6,bgcolor=color.black,text_color=color.white, text="TOTAL NET PROFIT")
// ROWS
table.cell(tablo,1,0,bgcolor=strategy.netprofit>0 ? color.green : color.red,text_color=color.white, text=str.tostring(strategy.netprofit))
table.cell(tablo,1,1,bgcolor=color.black,text_color=color.white, text=str.tostring(strategy.grossprofit))
table.cell(tablo,1,2,bgcolor=color.black,text_color=color.white, text=str.tostring(strategy.grossloss))
table.cell(tablo,1,3,bgcolor=strategy.grossprofit / strategy.grossloss >1 ? color.green : color.red,text_color=color.white, text=str.tostring(math.round(strategy.grossprofit / strategy.grossloss,3)))
table.cell(tablo,1,4,bgcolor=color.black,text_color=color.white, text=str.tostring(strategy.wintrades))
table.cell(tablo,1,5,bgcolor=color.black,text_color=color.white, text=str.tostring(strategy.losstrades))
table.cell(tablo,1,6,bgcolor=color.black,text_color=color.white, text=str.tostring(math.round(strategy.netprofit/strategy.initial_capital*100,2))+" %") |
Lorentzian Classification Strategy | https://www.tradingview.com/script/SfyBCHIJ/ | StrategiesForEveryone | https://www.tradingview.com/u/StrategiesForEveryone/ | 1,850 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//
// Please, visit the main script that strategy is based in :) Machine Learning: Lorentzian Classification/<<<< ==============================================
// Indicator developed by ©jdehorty
// Strategy devoleped by ©StrategiesForEVeryone
// @version=5
strategy('Machine Learning: Lorentzian Classification', 'Lorentzian Classification Strategy', true, precision=2, initial_capital = 100000, process_orders_on_close = true, calc_on_every_tick = true, commission_value = 0.03)
import jdehorty/MLExtensions/2 as ml
import jdehorty/KernelFunctions/2 as kernels
initial_message = input.bool(defval = true, title = "Show initial message", group = "Initial message")
if barstate.islast and initial_message
label.new(bar_index, 0, "Please, read the entire post " + "\nfor a better understanding." + "\nDo not forget to visit the original" + "\nindicator from ©jdehorty and leave your boost!", xloc = xloc.bar_index, yloc = yloc.abovebar, textcolor = color.white, color = color.rgb(76, 175, 255, 4))
// ======================
// ==== Custom Types ====
// ======================
// This section uses PineScript's new Type syntax to define important data structures
// used throughout the script.
type Settings
float source
int neighborsCount
int maxBarsBack
int featureCount
int colorCompression
bool showExits
bool useDynamicExits
type Label
int long
int short
int neutral
type FeatureArrays
array<float> f1
array<float> f2
array<float> f3
array<float> f4
array<float> f5
type FeatureSeries
float f1
float f2
float f3
float f4
float f5
type MLModel
int firstBarIndex
array<int> trainingLabels
int loopSize
float lastDistance
array<float> distancesArray
array<int> predictionsArray
int prediction
type FilterSettings
bool useVolatilityFilter
bool useRegimeFilter
bool useAdxFilter
float regimeThreshold
int adxThreshold
type Filter
bool volatility
bool regime
bool adx
// ==========================
// ==== Helper Functions ====
// ==========================
series_from(feature_string, _close, _high, _low, _hlc3, f_paramA, f_paramB) =>
switch feature_string
"RSI" => ml.n_rsi(_close, f_paramA, f_paramB)
"WT" => ml.n_wt(_hlc3, f_paramA, f_paramB)
"CCI" => ml.n_cci(_close, f_paramA, f_paramB)
"ADX" => ml.n_adx(_high, _low, _close, f_paramA)
get_lorentzian_distance(int i, int featureCount, FeatureSeries featureSeries, FeatureArrays featureArrays) =>
switch featureCount
5 => math.log(1+math.abs(featureSeries.f1 - array.get(featureArrays.f1, i))) +
math.log(1+math.abs(featureSeries.f2 - array.get(featureArrays.f2, i))) +
math.log(1+math.abs(featureSeries.f3 - array.get(featureArrays.f3, i))) +
math.log(1+math.abs(featureSeries.f4 - array.get(featureArrays.f4, i))) +
math.log(1+math.abs(featureSeries.f5 - array.get(featureArrays.f5, i)))
4 => math.log(1+math.abs(featureSeries.f1 - array.get(featureArrays.f1, i))) +
math.log(1+math.abs(featureSeries.f2 - array.get(featureArrays.f2, i))) +
math.log(1+math.abs(featureSeries.f3 - array.get(featureArrays.f3, i))) +
math.log(1+math.abs(featureSeries.f4 - array.get(featureArrays.f4, i)))
3 => math.log(1+math.abs(featureSeries.f1 - array.get(featureArrays.f1, i))) +
math.log(1+math.abs(featureSeries.f2 - array.get(featureArrays.f2, i))) +
math.log(1+math.abs(featureSeries.f3 - array.get(featureArrays.f3, i)))
2 => math.log(1+math.abs(featureSeries.f1 - array.get(featureArrays.f1, i))) +
math.log(1+math.abs(featureSeries.f2 - array.get(featureArrays.f2, i)))
// ================
// ==== Inputs ====
// ================
// Settings Object: General User-Defined Inputs
Settings settings =
Settings.new(
input.source(title='Source', defval=close, group="General Settings", tooltip="Source of the input data"),
input.int(title='Neighbors Count', defval=8, group="General Settings", minval=1, maxval=100, step=1, tooltip="Number of neighbors to consider"),
input.int(title="Max Bars Back", defval=2000, group="General Settings", tooltip = "Use this to increase or reduce the range of backtesting. If script use much time to load, reduce this"),
input.int(title="Feature Count", defval=5, group="Feature Engineering", minval=2, maxval=5, tooltip="Number of features to use for ML predictions."),
input.int(title="Color Compression", defval=1, group="General Settings", minval=1, maxval=10, tooltip="Compression factor for adjusting the intensity of the color scale."),
input.bool(title="Show Default Exits", defval=false, group="General Settings", tooltip="Default exits occur exactly 4 bars after an entry signal. This corresponds to the predefined length of a trade during the model's training process.", inline="exits"),
input.bool(title="Use Dynamic Exits", defval=false, group="General Settings", tooltip="Dynamic exits attempt to let profits ride by dynamically adjusting the exit threshold based on kernel regression logic.", inline="exits")
)
// Trade Stats Settings
// Note: The trade stats section is NOT intended to be used as a replacement for proper backtesting. It is intended to be used for calibration purposes only.
// showTradeStats = input.bool(false, 'Show Trade Stats', tooltip='Displays the trade stats for a given configuration. Useful for optimizing the settings in the Feature Engineering section. This should NOT replace backtesting and should be used for calibration purposes only. Early Signal Flips represent instances where the model changes signals before 4 bars elapses; high values can indicate choppy (ranging) market conditions.', group="General Settings")
// useWorstCase = input.bool(false, "Use Worst Case Estimates", tooltip="Whether to use the worst case scenario for backtesting. This option can be useful for creating a conservative estimate that is based on close prices only, thus avoiding the effects of intrabar repainting. This option assumes that the user does not enter when the signal first appears and instead waits for the bar to close as confirmation. On larger timeframes, this can mean entering after a large move has already occurred. Leaving this option disabled is generally better for those that use this indicator as a source of confluence and prefer estimates that demonstrate discretionary mid-bar entries. Leaving this option enabled may be more consistent with traditional backtesting results.", group="General Settings")
// Settings object for user-defined settings
FilterSettings filterSettings =
FilterSettings.new(
input.bool(title="Use Volatility Filter", defval=true, tooltip="Whether to use the volatility filter.", group="Filters"),
input.bool(title="Use Regime Filter", defval=true, group="Filters", inline="regime"),
input.bool(title="Use ADX Filter", defval=false, group="Filters", inline="adx"),
input.float(title="Threshold", defval=-0.1, minval=-10, maxval=10, step=0.1, tooltip="Whether to use the trend detection filter. Threshold for detecting Trending/Ranging markets.", group="Filters", inline="regime"),
input.int(title="Threshold", defval=20, minval=0, maxval=100, step=1, tooltip="Whether to use the ADX filter. Threshold for detecting Trending/Ranging markets.", group="Filters", inline="adx")
)
// Filter object for filtering the ML predictions
Filter filter =
Filter.new(
ml.filter_volatility(1, 10, filterSettings.useVolatilityFilter),
ml.regime_filter(ohlc4, filterSettings.regimeThreshold, filterSettings.useRegimeFilter),
ml.filter_adx(settings.source, 14, filterSettings.adxThreshold, filterSettings.useAdxFilter)
)
// Feature Variables: User-Defined Inputs for calculating Feature Series.
f1_string = input.string(title="Feature 1", options=["RSI", "WT", "CCI", "ADX"], defval="RSI", inline = "01", tooltip="The first feature to use for ML predictions.", group="Feature Engineering")
f1_paramA = input.int(title="Parameter A", tooltip="The primary parameter of feature 1.", defval=14, inline = "02", group="Feature Engineering")
f1_paramB = input.int(title="Parameter B", tooltip="The secondary parameter of feature 2 (if applicable).", defval=1, inline = "02", group="Feature Engineering")
f2_string = input.string(title="Feature 2", options=["RSI", "WT", "CCI", "ADX"], defval="WT", inline = "03", tooltip="The second feature to use for ML predictions.", group="Feature Engineering")
f2_paramA = input.int(title="Parameter A", tooltip="The primary parameter of feature 2.", defval=10, inline = "04", group="Feature Engineering")
f2_paramB = input.int(title="Parameter B", tooltip="The secondary parameter of feature 2 (if applicable).", defval=11, inline = "04", group="Feature Engineering")
f3_string = input.string(title="Feature 3", options=["RSI", "WT", "CCI", "ADX"], defval="CCI", inline = "05", tooltip="The third feature to use for ML predictions.", group="Feature Engineering")
f3_paramA = input.int(title="Parameter A", tooltip="The primary parameter of feature 3.", defval=20, inline = "06", group="Feature Engineering")
f3_paramB = input.int(title="Parameter B", tooltip="The secondary parameter of feature 3 (if applicable).", defval=1, inline = "06", group="Feature Engineering")
f4_string = input.string(title="Feature 4", options=["RSI", "WT", "CCI", "ADX"], defval="ADX", inline = "07", tooltip="The fourth feature to use for ML predictions.", group="Feature Engineering")
f4_paramA = input.int(title="Parameter A", tooltip="The primary parameter of feature 4.", defval=20, inline = "08", group="Feature Engineering")
f4_paramB = input.int(title="Parameter B", tooltip="The secondary parameter of feature 4 (if applicable).", defval=2, inline = "08", group="Feature Engineering")
f5_string = input.string(title="Feature 5", options=["RSI", "WT", "CCI", "ADX"], defval="RSI", inline = "09", tooltip="The fifth feature to use for ML predictions.", group="Feature Engineering")
f5_paramA = input.int(title="Parameter A", tooltip="The primary parameter of feature 5.", defval=9, inline = "10", group="Feature Engineering")
f5_paramB = input.int(title="Parameter B", tooltip="The secondary parameter of feature 5 (if applicable).", defval=1, inline = "10", group="Feature Engineering")
// FeatureSeries Object: Calculated Feature Series based on Feature Variables
featureSeries =
FeatureSeries.new(
series_from(f1_string, close, high, low, hlc3, f1_paramA, f1_paramB), // f1
series_from(f2_string, close, high, low, hlc3, f2_paramA, f2_paramB), // f2
series_from(f3_string, close, high, low, hlc3, f3_paramA, f3_paramB), // f3
series_from(f4_string, close, high, low, hlc3, f4_paramA, f4_paramB), // f4
series_from(f5_string, close, high, low, hlc3, f5_paramA, f5_paramB) // f5
)
// FeatureArrays Variables: Storage of Feature Series as Feature Arrays Optimized for ML
// Note: These arrays cannot be dynamically created within the FeatureArrays Object Initialization and thus must be set-up in advance.
var f1Array = array.new_float()
var f2Array = array.new_float()
var f3Array = array.new_float()
var f4Array = array.new_float()
var f5Array = array.new_float()
array.push(f1Array, featureSeries.f1)
array.push(f2Array, featureSeries.f2)
array.push(f3Array, featureSeries.f3)
array.push(f4Array, featureSeries.f4)
array.push(f5Array, featureSeries.f5)
// FeatureArrays Object: Storage of the calculated FeatureArrays into a single object
featureArrays =
FeatureArrays.new(
f1Array, // f1
f2Array, // f2
f3Array, // f3
f4Array, // f4
f5Array // f5
)
// Label Object: Used for classifying historical data as training data for the ML Model
Label direction_s =
Label.new(
long=1,
short=-1,
neutral=0
)
// Derived from General Settings
maxBarsBackIndex = last_bar_index >= settings.maxBarsBack ? last_bar_index - settings.maxBarsBack : 0
// EMA Settings
useEmaFilter = input.bool(title="Use EMA Filter", defval=false, group="Filters", inline="ema")
emaPeriod = input.int(title="Period", defval=200, minval=1, step=1, group="Filters", inline="ema", tooltip="The period of the EMA used for the EMA Filter.")
isEmaUptrend = useEmaFilter ? close > ta.ema(close, emaPeriod) : true
isEmaDowntrend = useEmaFilter ? close < ta.ema(close, emaPeriod) : true
useSmaFilter = input.bool(title="Use SMA Filter", defval=false, group="Filters", inline="sma")
smaPeriod = input.int(title="Period", defval=200, minval=1, step=1, group="Filters", inline="sma", tooltip="The period of the SMA used for the SMA Filter.")
isSmaUptrend = useSmaFilter ? close > ta.sma(close, smaPeriod) : true
isSmaDowntrend = useSmaFilter ? close < ta.sma(close, smaPeriod) : true
// Nadaraya-Watson Kernel Regression Settings
useKernelFilter = input.bool(true, "Trade with Kernel", group="Kernel Settings", inline="kernel")
showKernelEstimate = input.bool(false, "Show Kernel Estimate", group="Kernel Settings", inline="kernel")
useKernelSmoothing = input.bool(false, "Enhance Kernel Smoothing", tooltip="Uses a crossover based mechanism to smoothen kernel color changes. This often results in less color transitions overall and may result in more ML entry signals being generated.", inline='1', group='Kernel Settings')
h = input.int(8, 'Lookback Window', minval=3, tooltip='The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50', group="Kernel Settings", inline="kernel")
r = input.float(8., 'Relative Weighting', step=0.25, tooltip='Relative weighting of time frames. As this value approaches zero, the longer time frames will exert more influence on the estimation. As this value approaches infinity, the behavior of the Rational Quadratic Kernel will become identical to the Gaussian kernel. Recommended range: 0.25-25', group="Kernel Settings", inline="kernel")
x = input.int(25, "Regression Level", tooltip='Bar index on which to start regression. Controls how tightly fit the kernel estimate is to the data. Smaller values are a tighter fit. Larger values are a looser fit. Recommended range: 2-25', group="Kernel Settings", inline="kernel")
lag = input.int(2, "Lag", tooltip="Lag for crossover detection. Lower values result in earlier crossovers. Recommended range: 1-2", inline='1', group='Kernel Settings')
// Display Settings
showBarColors = input.bool(false, "Show Bar Colors", tooltip="Whether to show the bar colors.", group="Display Settings")
showBarPredictions = input.bool(defval = false, title = "Show Bar Prediction Values", tooltip = "Will show the ML model's evaluation of each bar as an integer.", group="Display Settings")
useAtrOffset = input.bool(defval = false, title = "Use ATR Offset", tooltip = "Will use the ATR offset instead of the bar prediction offset.", group="Display Settings")
barPredictionsOffset = input.float(0, "Bar Prediction Offset", minval=0, tooltip="The offset of the bar predictions as a percentage from the bar high or close.", group="Display Settings")
// =================================
// ==== Next Bar Classification ====
// =================================
// This model specializes specifically in predicting the direction_s of price action over the course of the next 4 bars.
// To avoid complications with the ML model, this value is hardcoded to 4 bars but support for other training lengths may be added in the future.
src = settings.source
y_train_series = src[4] < src[0] ? direction_s.short : src[4] > src[0] ? direction_s.long : direction_s.neutral
var y_train_array = array.new_int(0)
// Variables used for ML Logic
var predictions = array.new_float(0)
var prediction = 0.
var signal = direction_s.neutral
var distances = array.new_float(0)
array.push(y_train_array, y_train_series)
// =========================
// ==== Core ML Logic ====
// =========================
lastDistance = -1.0
size = math.min(settings.maxBarsBack-1, array.size(y_train_array)-1)
sizeLoop = math.min(settings.maxBarsBack-1, size)
if bar_index >= maxBarsBackIndex //{
for i = 0 to sizeLoop //{
d = get_lorentzian_distance(i, settings.featureCount, featureSeries, featureArrays)
if d >= lastDistance and i%4 //{
lastDistance := d
array.push(distances, d)
array.push(predictions, math.round(array.get(y_train_array, i)))
if array.size(predictions) > settings.neighborsCount //{
lastDistance := array.get(distances, math.round(settings.neighborsCount*3/4))
array.shift(distances)
array.shift(predictions)
//}
//}
//}
prediction := array.sum(predictions)
//}
// ============================
// ==== Prediction Filters ====
// ============================
// User Defined Filters: Used for adjusting the frequency of the ML Model's predictions
filter_all = filter.volatility and filter.regime and filter.adx
// Filtered Signal: The model's prediction of future price movement direction_s with user-defined filters applied
signal := prediction > 0 and filter_all ? direction_s.long : prediction < 0 and filter_all ? direction_s.short : nz(signal[1])
// Bar-Count Filters: Represents strict filters based on a pre-defined holding period of 4 bars
var int barsHeld = 0
barsHeld := ta.change(signal) ? 0 : barsHeld + 1
isHeldFourBars = barsHeld == 4
isHeldLessThanFourBars = 0 < barsHeld and barsHeld < 4
// Fractal Filters: Derived from relative ============ Appearance ============s of signals in a given time series fractal/segment with a default length of 4 bars
isDifferentSignalType = ta.change(signal)
isEarlySignalFlip = ta.change(signal) and (ta.change(signal[1]) or ta.change(signal[2]) or ta.change(signal[3]))
isBuySignal = signal == direction_s.long and isEmaUptrend and isSmaUptrend
isSellSignal = signal == direction_s.short and isEmaDowntrend and isSmaDowntrend
isLastSignalBuy = signal[4] == direction_s.long and isEmaUptrend[4] and isSmaUptrend[4]
isLastSignalSell = signal[4] == direction_s.short and isEmaDowntrend[4] and isSmaDowntrend[4]
isNewBuySignal = isBuySignal and isDifferentSignalType
isNewSellSignal = isSellSignal and isDifferentSignalType
// Kernel Regression Filters: Filters based on Nadaraya-Watson Kernel Regression using the Rational Quadratic Kernel
// For more information on this technique refer to my other open source indicator located here:
// https://www.tradingview.com/script/AWNvbPRM-Nadaraya-Watson-Rational-Quadratic-Kernel-Non-Repainting/
c_green = color.new(#009988, 20)
c_red = color.new(#CC3311, 20)
transparent = color.new(#000000, 100)
yhat1 = kernels.rationalQuadratic(settings.source, h, r, x)
yhat2 = kernels.gaussian(settings.source, h-lag, x)
kernelEstimate = yhat1
// Kernel Rates of Change
bool wasBearishRate = yhat1[2] > yhat1[1]
bool wasBullishRate = yhat1[2] < yhat1[1]
bool isBearishRate = yhat1[1] > yhat1
bool isBullishRate = yhat1[1] < yhat1
isBearishChange = isBearishRate and wasBullishRate
isBullishChange = isBullishRate and wasBearishRate
// Kernel Crossovers
bool isBullishCrossAlert = ta.crossover(yhat2, yhat1)
bool isBearishCrossAlert = ta.crossunder(yhat2, yhat1)
bool isBullishSmooth = yhat2 >= yhat1
bool isBearishSmooth = yhat2 <= yhat1
// Kernel Colors
color colorByCross = isBullishSmooth ? c_green : c_red
color colorByRate = isBullishRate ? c_green : c_red
color plotColor = showKernelEstimate ? (useKernelSmoothing ? colorByCross : colorByRate) : transparent
plot(kernelEstimate, color=plotColor, linewidth=2, title="Kernel Regression Estimate", display = display.all - display.price_scale - display.status_line)
// Alert Variables
bool alertBullish = useKernelSmoothing ? isBullishCrossAlert : isBullishChange
bool alertBearish = useKernelSmoothing ? isBearishCrossAlert : isBearishChange
// Bullish and Bearish Filters based on Kernel
isBullish = useKernelFilter ? (useKernelSmoothing ? isBullishSmooth : isBullishRate) : true
isBearish = useKernelFilter ? (useKernelSmoothing ? isBearishSmooth : isBearishRate) : true
// ===========================
// ==== Entries and Exits ====
// ===========================
// Entry Conditions: Booleans for ML Model Position Entries
startLongTrade = isNewBuySignal and isBullish and isEmaUptrend and isSmaUptrend
startShortTrade = isNewSellSignal and isBearish and isEmaDowntrend and isSmaDowntrend
// Dynamic Exit Conditions: Booleans for ML Model Position Exits based on Fractal Filters and Kernel Regression Filters
lastSignalWasBullish = ta.barssince(startLongTrade) < ta.barssince(startShortTrade)
lastSignalWasBearish = ta.barssince(startShortTrade) < ta.barssince(startLongTrade)
barsSinceRedEntry = ta.barssince(startShortTrade)
barsSinceRedExit = ta.barssince(alertBullish)
barsSinceGreenEntry = ta.barssince(startLongTrade)
barsSinceGreenExit = ta.barssince(alertBearish)
isValidShortExit = barsSinceRedExit > barsSinceRedEntry
isValidLongExit = barsSinceGreenExit > barsSinceGreenEntry
endLongTradeDynamic = (isBearishChange and isValidLongExit[1])
endShortTradeDynamic = (isBullishChange and isValidShortExit[1])
// Fixed Exit Conditions: Booleans for ML Model Position Exits based on a Bar-Count Filters
endLongTradeStrict = ((isHeldFourBars and isLastSignalBuy) or (isHeldLessThanFourBars and isNewSellSignal and isLastSignalBuy)) and startLongTrade[4]
endShortTradeStrict = ((isHeldFourBars and isLastSignalSell) or (isHeldLessThanFourBars and isNewBuySignal and isLastSignalSell)) and startShortTrade[4]
isDynamicExitValid = not useEmaFilter and not useSmaFilter and not useKernelSmoothing
endLongTrade = settings.useDynamicExits and isDynamicExitValid ? endLongTradeDynamic : endLongTradeStrict
endShortTrade = settings.useDynamicExits and isDynamicExitValid ? endShortTradeDynamic : endShortTradeStrict
// =========================
// ==== Plotting Labels ====
// =========================
// Note: These will not repaint once the most recent bar has fully closed. By default, signals appear over the last closed bar; to override this behavior set offset=0.
//plotshape(startLongTrade ? low : na, 'Buy', shape.labelup, location.belowbar, color=ml.color_green(prediction), size=size.small, offset=0, display = display.all - display.price_scale - display.status_line)
//plotshape(startShortTrade ? high : na, 'Sell', shape.labeldown, location.abovebar, ml.color_red(-prediction), size=size.small, offset=0, display = display.all - display.price_scale - display.status_line)
//plotshape(endLongTrade and settings.showExits ? high : na, 'StopBuy', shape.xcross, location.absolute, color=#3AFF17, size=size.tiny, offset=0, display = display.all - display.price_scale - display.status_line)
//plotshape(endShortTrade and settings.showExits ? low : na, 'StopSell', shape.xcross, location.absolute, color=#FD1707, size=size.tiny, offset=0, display = display.all - display.price_scale - display.status_line)
// ================
// ==== Alerts ====
// ================
// Separate Alerts for Entries and Exits
//alertcondition(startLongTrade, title='Open Long ▲', message='LDC Open Long ▲ | {{ticker}}@{{close}} | ({{interval}})')
//alertcondition(endLongTrade, title='Close Long ▲', message='LDC Close Long ▲ | {{ticker}}@{{close}} | ({{interval}})')
//alertcondition(startShortTrade, title='Open Short ▼', message='LDC Open Short | {{ticker}}@{{close}} | ({{interval}})')
//alertcondition(endShortTrade, title='Close Short ▼', message='LDC Close Short ▼ | {{ticker}}@{{close}} | ({{interval}})')
//
//// Combined Alerts for Entries and Exits
//alertcondition(startShortTrade or startLongTrade, title='Open Position ▲▼', message='LDC Open Position ▲▼ | {{ticker}}@{{close}} | ({{interval}})')
//alertcondition(endShortTrade or endLongTrade, title='Close Position ▲▼', message='LDC Close Position ▲▼ | {{ticker}}@[{{close}}] | ({{interval}})')
//
//// Kernel Estimate Alerts
//alertcondition(condition=alertBullish, title='Kernel Bullish Color Change', message='LDC Kernel Bullish ▲ | {{ticker}}@{{close}} | ({{interval}})')
//alertcondition(condition=alertBearish, title='Kernel Bearish Color Change', message='LDC Kernel Bearish ▼ | {{ticker}}@{{close}} | ({{interval}})')
// =========================
// ==== Display Signals ====
// =========================
atrSpaced = useAtrOffset ? ta.atr(1) : na
compressionFactor = settings.neighborsCount / settings.colorCompression
c_pred = prediction > 0 ? color.from_gradient(prediction, 0, compressionFactor, #787b86, #009988) : prediction <= 0 ? color.from_gradient(prediction, -compressionFactor, 0, #CC3311, #787b86) : na
c_label = showBarPredictions ? c_pred : na
c_bars = showBarColors ? color.new(c_pred, 50) : na
x_val = bar_index
y_val = useAtrOffset ? prediction > 0 ? high + atrSpaced: low - atrSpaced : prediction > 0 ? high + hl2*barPredictionsOffset/20 : low - hl2*barPredictionsOffset/30
label.new(x_val, y_val, str.tostring(prediction), xloc.bar_index, yloc.price, color.new(color.white, 100), label.style_label_up, c_label, size.normal, text.align_left)
barcolor(showBarColors ? color.new(c_pred, 50) : na)
// ==============================================================================================================================================================================================================================================================================================
// ====================================== Strategy code ================================================================
// ------ Inputs for calculating our amount position --------
initial_actual_capital = input.float(defval=10000, title = "Enter initial/current capital", group = "============ Position amount calculator ===========")
risk_c = input.float(2.5, '% account risk per trade', step=1, group = "============ Position amount calculator ===========", tooltip = "Percentage of total account to risk per trade. The USD value that should be used to risk the inserted percentage of the account. Appears as a yellow number in the upper left corner")
// ------ Date filter ---------
initial_date = input.time(title="Initial date", defval=timestamp("10 Feb 2014 13:30 +0000"), group="============ Time filter ============ ", tooltip="Enter the start date and time of the strategy")
final_date = input.time(title="Final date", defval=timestamp("01 Jan 2030 19:30 +0000"), group="============ Time filter ============ ", tooltip="Enter the end date and time of the strategy")
dateFilter(int st, int et) => time >= st and time <= et
colorDate = input.bool(defval=false, title="Date background", tooltip = "Add color to the period of time of the strategy tester")
bgcolor(colorDate and dateFilter(initial_date, final_date) ? color.new(color.blue, transp=90) : na)
date = dateFilter(initial_date, final_date)
// ------ Session limits ------
timeSession = input.session(title="Time session", defval="0000-2400", group="============ Time filter ============ ", tooltip="Session time to operate. It may be different depending on your time zone, you have to find the correct hours manually.")
colorBG = input.bool(title="Session background", defval=false, tooltip = "Add color to session time background")
inSession(sess) => na(time(timeframe.period, sess + ':1234567')) == false
bgcolor(inSession(timeSession) and colorBG ? color.rgb(0, 38, 255, 84) : na)
// ===============================================================================================================================================
// ------------ Super Trend ----------
atrPeriod = input(9, "ATR Length SuperTrend", group = "========= Super Trend filter ==========")
factor = input.float(2.5, "Factor SuperTrend", step = 0.05, group = "========= Super Trend filter ==========")
[supertrend, direction_supertrend] = ta.supertrend(factor, atrPeriod)
show_supertrend = input.bool(defval = false, title="Show supertrend ?", group = "============ Appearance ============")
bodyMiddle = plot(show_supertrend ? ((open + close) / 2) : na, display=display.none)
upTrend = plot(show_supertrend and direction_supertrend < 0 ? supertrend : na, "Up Trend", color = color.green, style=plot.style_linebr, display = display.all - display.status_line)
downTrend = plot(show_supertrend and direction_supertrend > 0 ? supertrend : na, "Down Trend", color = color.red, style=plot.style_linebr, display = display.all - display.status_line)
fill(bodyMiddle, upTrend, color.new(color.green, 95), fillgaps=false, title = "Supertrend background")
fill(bodyMiddle, downTrend, color.new(color.red, 95), fillgaps=false, title = "Supertrend background")
up_trend_plot = direction_supertrend < 0
down_trend_plot = direction_supertrend > 0
// ----------- Ema ----------------------
ema = input.int(200, title='Ema length', minval=1, maxval=500, group = "============ Trend ============")
ema200 = ta.ema(close, ema)
bullish = close > ema200
bearish = close < ema200
show_ema = input.bool(defval=true, title="Show ema ?", group = "============ Appearance ============")
plot(show_ema ? ema200 : na, title = "Ema", color=color.white, linewidth=2, display = display.all - display.status_line - display.price_scale)
// ===============================================================================================================================================
// -------------- Atr stop loss by garethyeo (modified) -----------------
source_atr = input(close, title='Source', group = "================== Stop loss ==================", inline = "A")
length_atr = input.int(14, minval=1, title='Period', group = "================== Stop loss ==================" , inline = "A")
multiplier = input.float(1.5, minval=0.1, step=0.1, title='Atr multiplier', group = "================== Stop loss ==================", inline = "A", tooltip = "Defines the stop loss distance based on the Atr stop loss indicator")
show_stoploss = input.bool(defval = true, title = "Show stop loss ?", group = "============ Appearance ============")
var float shortStopLoss = na
var float longStopLoss = na
var float atr_past_candle_long = na
var float atr_past_candle_short = na
candle_of_stoploss = input.string(defval = "Current candle", title = "Stop loss source for atr stoploss", group = "================== Stop loss ==================", options = ["Current candle","Past candle"])
if candle_of_stoploss == "Current candle"
shortStopLoss := source_atr + ta.atr(length_atr) * multiplier
longStopLoss := source_atr - ta.atr(length_atr) * multiplier
if candle_of_stoploss == "Past candle"
shortStopLoss := close[1] + ta.atr(length_atr)[1] * multiplier[1]
longStopLoss := close[1] - ta.atr(length_atr)[1] * multiplier[1]
// --------- Stop loss based in last swing high/low --------
high_bars = input.int(defval = 10, title = "Highest price bars: ", group = "================== Stop loss ==================")
low_bars = input.int(defval = 10, title = "Lowest price bars: ", group = "================== Stop loss ==================")
stop_high = ta.highest(high, high_bars)
stop_low = ta.lowest(low, low_bars)
// --------- Stop loss source selection ---------------
stoploss_type = input.string(defval = "Atr stop loss", title = "General stop loss source", group = "================== Stop loss ==================", options = ["Atr stop loss","Swing high/low"])
if stoploss_type == "Atr stop loss"
shortStopLoss := source_atr + ta.atr(length_atr) * multiplier
longStopLoss := source_atr - ta.atr(length_atr) * multiplier
if candle_of_stoploss == "Past candle" and stoploss_type == "Atr stop loss"
shortStopLoss := close[1] + ta.atr(length_atr)[1] * multiplier[1]
longStopLoss := close[1] - ta.atr(length_atr)[1] * multiplier[1]
if stoploss_type == "Swing high/low"
shortStopLoss := stop_high
longStopLoss := stop_low
// ======================================== Add/withdraw money frequently (>>>Beta<<<) ==============================================================
// Declare some variables =========================================================
var initial_capital = strategy.initial_capital
var initial_capital_a = strategy.initial_capital
var initial_capital_w = strategy.initial_capital
var float capital_added = 0
var float balance = strategy.initial_capital
var prev_month = 0
var float amount = 0
var add_frequency = 0
var withdraw_frequency = 0
// Choose how often the strategy adds money =========================================================
add_money_frequency = input.string("Monthly", title = "Choose how often would you add money", options = ["Monthly","Weekly","Daily","Yearly"], group = "=============== Adding money frequently ===============")
amount_to_add = input.float(defval = 10, title = "How much you want to add ?", group = "=============== Adding money frequently ===============")
if add_money_frequency == "Monthly"
add_frequency := month
if add_money_frequency == "Weekly"
add_frequency := weekofyear
if add_money_frequency == "Daily"
add_frequency := dayofweek
if add_money_frequency == "Yearly"
add_frequency := year
// Choose if you want to add money or not ====================================
add_money = input.string("No", title = "Add money from time to time ?", options = ["Yes","No"] , group = "=============== Adding money frequently ===============")
if add_frequency != add_frequency[1] and add_money == "Yes" and date
initial_capital_a += amount_to_add
initial_capital += amount_to_add
balance := strategy.netprofit + initial_capital
// Choose how often the strategy withdraws money =========================================================
amount_to_withdraw = input.string("Fixed", title = "Withdraw based in fixed amounts or percentage of earnings", options = ["%","Fixed"], group = "=============== Withdraw money frequently ===============")
amount_for_withdraw = input.float(defval = 2, title = "How much you want to withdraw (fixed amount) ?", group = "=============== Withdraw money frequently ===============")
withdraw_money_frequency = input.string("Monthly", title = "Choose how often would you withdraw money", options = ["Monthly","Weekly","Daily","Yearly"], group = "=============== Withdraw money frequently ===============")
// We use this for being able to choose the frequency of withdrawing money:
if withdraw_money_frequency == "Monthly"
withdraw_frequency := month
if withdraw_money_frequency == "Weekly"
withdraw_frequency := weekofyear
if withdraw_money_frequency == "Daily"
withdraw_frequency := dayofweek
if withdraw_money_frequency == "Yearly"
withdraw_frequency := year
// Choose if you want to withdraw money or not =============================
withdraw_money = input.string("No", title = "Withdraw money from time to time ?", options = ["Yes","No"], group = "=============== Withdraw money frequently ===============")
percentage_of_earnings = input.float(10, title = "Percentage of earnings", group = "=============== Withdraw money frequently ===============", tooltip = "Use this if withdraw is based in % of earnings")
// Percentage of earnings:
if withdraw_frequency != withdraw_frequency[1] and withdraw_money == "Yes" and amount_to_withdraw == "%" and date and strategy.netprofit>0
initial_capital_w -= strategy.netprofit * (percentage_of_earnings / 100)
initial_capital -= strategy.netprofit * (percentage_of_earnings / 100)
balance := strategy.netprofit + initial_capital
// Fixed amount:
if withdraw_frequency != withdraw_frequency[1] and withdraw_money == "Yes" and amount_to_withdraw == "Fixed" and date and strategy.netprofit>0
initial_capital_w -= amount_for_withdraw
initial_capital -= amount_for_withdraw
balance := strategy.netprofit + initial_capital
// Logic
if withdraw_money == "Yes" and add_money == "No"
amount := balance
if withdraw_money =="Yes" and add_money =="Yes"
amount := balance
if withdraw_money == "No" and add_money == "Yes"
amount := balance
if withdraw_money == "No" and add_money == "No"
amount := strategy.equity
// ===============================================================================================================================================
// ------------- Money management --------------
strategy_contracts = amount / close
distance_sl_long = -1 * (longStopLoss - close) / close
distance_sl_short = (shortStopLoss - close) / close
risk = input.float(2.5, '% Account risk per trade for backtesting', step=1, group = "============ Risk management for trades ============", tooltip = "Percentage of total account to risk per trade if fixed amounts is deactivated")
long_amount = strategy_contracts * (risk / 100) / distance_sl_long
short_amount = strategy_contracts * (risk / 100) / distance_sl_short
leverage=input.bool(defval=true, title="Use leverage for backtesting ?", group = "============ Risk management for trades ============", tooltip = "If it is activated, there will be no monetary units or amount of assets limit for each operation (That is, each operation will not be affected by the initial / current capital since it would be using leverage). If it is deactivated, the monetary units or the amount of assets to use for each operation will be limited by the initial/current capital.")
if not leverage and long_amount>strategy_contracts
long_amount:=amount/close
if not leverage and short_amount>strategy_contracts
short_amount:=amount/close
// ---- Fixed amounts ----
fixed_amounts = input.bool(defval = false, title = "Fixed amounts ?", group = "============ Risk management for trades ============", tooltip = "If you activate this, the backtester will use fixed amounts")
fixed_amount_input = input.float(defval = 1000, title = "Fixed amount in usd", group = "============ Risk management for trades ============")
if fixed_amounts
long_amount := fixed_amount_input / close
short_amount := fixed_amount_input / close
// ---------- Risk management ---------------
risk_reward_breakeven_long= input.float(title="Risk/reward for breakeven long", defval=1.0, step=0.1, group = "============ Risk management for trades ============")
risk_reward_take_profit_long= input.float(title="Risk/reward for take profit long", defval=3.0, step=0.1, group = "============ Risk management for trades ============")
risk_reward_breakeven_short= input.float(title="Risk/reward for break even short", defval=1.0, step=0.1, group = "============ Risk management for trades ============")
risk_reward_take_profit_short= input.float(title="Risk/reward for take profit short", defval=3.0, step=0.1, group = "============ Risk management for trades ============")
tp_percent=input.float(title="% of trade for first take profit", defval=50, step=5, group = "============ Risk management for trades ============", tooltip = "Closing percentage of the current position when the first take profit is reached.")
// ===============================================================================================================================================
// ------------ Trade conditions ---------------
// Entry Conditions: Booleans for ML Model Position Entries
//startLongTrade = isNewBuySignal and isBullish and isEmaUptrend and isSmaUptrend
//startShortTrade = isNewSellSignal and isBearish and isEmaDowntrend and isSmaDowntrend
//endLongTrade = settings.useDynamicExits and isDynamicExitValid ? endLongTradeDynamic : endLongTradeStrict
//endShortTrade = settings.useDynamicExits and isDynamicExitValid ? endShortTradeDynamic : endShortTradeStrict
//bullish := close > ema200
//bearish := close < ema200
bought = strategy.position_size > 0
sold = strategy.position_size < 0
buy = startLongTrade
sell = startShortTrade
var float total_commissions_value = 0
var float commission_value_l = 0
var float commission_value_s = 0
var float sl_long = na
var float sl_short = na
var float be_long = na
var float be_short = na
var float tp_long = na
var float tp_short = na
var int totaltrades = 0
close_withsupertrend = input.bool(defval = true, title = "Close positions with supertrend ?", group = "============ Positions management ============")
closeshort_supertrend=ta.crossover(close, supertrend)
closelong_supertrend=ta.crossunder(close, supertrend)
if not bought
be_long:=na
sl_long:=na
tp_long:=na
if not sold
be_short:=na
sl_short:=na
tp_short:=na
long_positions = input.bool(defval = true, title = "Long positions ?", group = "============ Positions management ============")
short_positions = input.bool(defval = true, title = "Short positions ?", group = "============ Positions management ============")
use_takeprofit = input.bool(defval = true, title = "Use take profit ?", group = "============ Risk management for trades ============")
use_breakeven = input.bool(defval = true, title = "Use break even ?", group = "============ Risk management for trades ============")
close_only_tp = input.bool(defval = false, title = "Close just with take profit ?", group = "============ Risk management for trades ============", tooltip = "Activate if you just want to exit from a position until reaching take profit or stop loss. If it´s activated, change % of closing by tp to 100%")
ema_filter_long = input.bool(defval = true, title = "Ema filter for long positions ?", group = "============ Positions management ============", tooltip = "Activate if you just want to long above 200 ema")
ema_filter_short = input.bool(defval = true, title = "Ema filter for short positions ?", group = "============ Positions management ============", tooltip = "Activate if you just want to short under 200 ema")
commission_percent = input.float(0.03, title = "Commission value in %", group = "============ Positions management ============", tooltip = "Set the % of commission. For example, when you enter into a position, you have a commission of 0.04% per entry and 0.04% per exit. You have also to change this value in properties for getting a real return in backtest. (in this case, 0.04%)")
if fixed_amounts
commission_value_l := (close * (long_amount) * (commission_percent/100))
commission_value_s := (close * (short_amount) * (commission_percent/100))
if not fixed_amounts
commission_value_l := (close * ((strategy_contracts * (risk / 100)) / distance_sl_long) * (commission_percent/100))
commission_value_s := (close * ((strategy_contracts * (risk / 100)) / distance_sl_short) * (commission_percent/100))
// ======================= Strategy ===================================================================================================================
// Long position with take profit
if not bought and buy and date and long_positions and inSession(timeSession) and use_takeprofit and not ema_filter_long
sl_long:=longStopLoss
long_stoploss_distance = close - longStopLoss
be_long := close + long_stoploss_distance * risk_reward_breakeven_long
tp_long:=close+(long_stoploss_distance*risk_reward_take_profit_long)
total_commissions_value += commission_value_l
strategy.entry('L', strategy.long, long_amount, alert_message = "Long")
strategy.exit("Tp", "L", stop=sl_long, limit=tp_long, qty_percent=tp_percent)
strategy.exit('Exit', 'L', stop=sl_long)
if bought and high > be_long and use_breakeven
sl_long := strategy.position_avg_price
strategy.exit("Tp", "L", stop=sl_long, limit=tp_long, qty_percent=tp_percent)
strategy.exit('Exit', 'L', stop=sl_long)
if bought and sell and strategy.openprofit>0 and not close_only_tp or bought and closelong_supertrend and close_withsupertrend and strategy.openprofit>0 and not close_only_tp
strategy.close("L", comment="CL")
balance := balance + strategy.openprofit
// Long position without take profit
if not bought and buy and date and long_positions and inSession(timeSession) and not ema_filter_long
sl_long:=longStopLoss
long_stoploss_distance = close - longStopLoss
be_long := close + long_stoploss_distance * risk_reward_breakeven_long
total_commissions_value += commission_value_l
strategy.entry('L', strategy.long, long_amount, alert_message = "Long")
strategy.exit('Exit', 'L', stop=sl_long)
if bought and high > be_long and use_breakeven
sl_long := strategy.position_avg_price
strategy.exit('Exit', 'L', stop=sl_long)
if bought and sell and strategy.openprofit>0
strategy.close("L", comment="CL")
balance := balance + strategy.openprofit
// Short position with take profit
if not sold and sell and date and short_positions and inSession(timeSession) and use_takeprofit and not ema_filter_short
sl_short:=shortStopLoss
short_stoploss_distance=shortStopLoss - close
be_short:=((short_stoploss_distance*risk_reward_breakeven_short)-close)*-1
tp_short:=((short_stoploss_distance*risk_reward_take_profit_short)-close)*-1
total_commissions_value += commission_value_s
strategy.entry("S", strategy.short, short_amount, alert_message = "Short")
strategy.exit("Tp", "S", stop=sl_short, limit=tp_short, qty_percent=tp_percent)
strategy.exit("Exit", "S", stop=sl_short)
if sold and low < be_short and use_breakeven
sl_short:=strategy.position_avg_price
strategy.exit("Tp", "S", stop=sl_short, limit=tp_short, qty_percent=tp_percent)
strategy.exit("Exit", "S", stop=sl_short)
if sold and buy and strategy.openprofit>0 and not close_only_tp or sold and closeshort_supertrend and close_withsupertrend and strategy.openprofit>0 and not close_only_tp
strategy.close("S", comment="CS")
balance := balance + strategy.openprofit
// Short position without take profit
if not sold and sell and date and short_positions and inSession(timeSession) and not ema_filter_short
sl_short:=shortStopLoss
short_stoploss_distance=shortStopLoss - close
be_short:=((short_stoploss_distance*risk_reward_breakeven_short)-close)*-1
total_commissions_value += commission_value_s
strategy.entry("S", strategy.short, short_amount, alert_message = "Short")
strategy.exit("Exit", "S", stop=sl_short)
if sold and low < be_short and use_breakeven
sl_short:=strategy.position_avg_price
strategy.exit("Exit", "S", stop=sl_short)
if sold and buy and strategy.openprofit>0
strategy.close("S", comment="CS")
balance := balance + strategy.openprofit
// ===============================================================================================================================================
// Long position with ema filter
// With take profit
if not bought and buy and date and long_positions and inSession(timeSession) and use_takeprofit and bullish and ema_filter_long
sl_long:=longStopLoss
long_stoploss_distance = close - longStopLoss
be_long := close + long_stoploss_distance * risk_reward_breakeven_long
tp_long:=close+(long_stoploss_distance*risk_reward_take_profit_long)
total_commissions_value += commission_value_l
strategy.entry('L', strategy.long, long_amount, alert_message = "Long")
strategy.exit("Tp", "L", stop=sl_long, limit=tp_long, qty_percent=tp_percent)
strategy.exit('Exit', 'L', stop=sl_long)
if bought and high > be_long and use_breakeven
sl_long := strategy.position_avg_price
strategy.exit("Tp", "L", stop=sl_long, limit=tp_long, qty_percent=tp_percent)
strategy.exit('Exit', 'L', stop=sl_long)
if bought and sell and strategy.openprofit>0 and not close_only_tp or bought and closelong_supertrend and close_withsupertrend and strategy.openprofit>0 and not close_only_tp
strategy.close("L", comment="CL")
balance := balance + strategy.openprofit
// Without take profit
if not bought and buy and date and long_positions and inSession(timeSession) and bullish and ema_filter_long
sl_long:=longStopLoss
long_stoploss_distance = close - longStopLoss
be_long := close + long_stoploss_distance * risk_reward_breakeven_long
total_commissions_value += commission_value_l
strategy.entry('L', strategy.long, long_amount, alert_message = "Long")
strategy.exit('Exit', 'L', stop=sl_long)
if bought and high > be_long and use_breakeven
sl_long := strategy.position_avg_price
strategy.exit('Exit', 'L', stop=sl_long)
if bought and sell and strategy.openprofit>0
strategy.close("L", comment="CL")
balance := balance + strategy.openprofit
// Short positon with ema filter
// With take profit
if not sold and sell and date and short_positions and inSession(timeSession) and use_takeprofit and bearish and ema_filter_short
sl_short:=shortStopLoss
short_stoploss_distance=shortStopLoss - close
be_short:=((short_stoploss_distance*risk_reward_breakeven_short)-close)*-1
tp_short:=((short_stoploss_distance*risk_reward_take_profit_short)-close)*-1
total_commissions_value += commission_value_s
strategy.entry("S", strategy.short, short_amount, alert_message = "Short")
strategy.exit("Tp", "S", stop=sl_short, limit=tp_short, qty_percent=tp_percent)
strategy.exit("Exit", "S", stop=sl_short)
if sold and low < be_short and use_breakeven
sl_short:=strategy.position_avg_price
strategy.exit("Tp", "S", stop=sl_short, limit=tp_short, qty_percent=tp_percent)
strategy.exit("Exit", "S", stop=sl_short)
if sold and buy and strategy.openprofit>0 and not close_only_tp or sold and closeshort_supertrend and close_withsupertrend and strategy.openprofit>0 and not close_only_tp
strategy.close("S", comment="CS")
balance := balance + strategy.openprofit
// Without take profit
if not sold and sell and date and short_positions and inSession(timeSession) and bearish and ema_filter_short
sl_short:=shortStopLoss
short_stoploss_distance=shortStopLoss - close
be_short:=((short_stoploss_distance*risk_reward_breakeven_short)-close)*-1
total_commissions_value += commission_value_s
strategy.entry("S", strategy.short, short_amount, alert_message = "Short")
strategy.exit("Exit", "S", stop=sl_short)
if sold and low < be_short and use_breakeven
sl_short:=strategy.position_avg_price
strategy.exit("Exit", "S", stop=sl_short)
if sold and buy and strategy.openprofit>0
strategy.close("S", comment="CS")
balance := balance + strategy.openprofit
// ===============================================================================================================================================
// ---------- Draw positions and signals on chart (strategy as an indicator) -------------
if high>tp_long
tp_long:=na
if low<tp_short
tp_short:=na
if high>be_long
be_long:=na
if low<be_short
be_short:=na
show_position_on_chart = input.bool(defval=true, title="Draw position on chart ?", group = "============ Appearance ============", tooltip = "Activate to graphically display profit, stop loss and break even")
position_price = plot(show_position_on_chart? strategy.position_avg_price : na, style=plot.style_linebr, color = color.new(#ffffff, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)
sl_long_price = plot(show_position_on_chart and bought ? sl_long : na, style = plot.style_linebr, color = color.new(color.red, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)
sl_short_price = plot(show_position_on_chart and sold ? sl_short : na, style = plot.style_linebr, color = color.new(color.red, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)
tp_long_price = plot(bought and show_position_on_chart and use_takeprofit? tp_long : na, style = plot.style_linebr, color = color.new(#4cd350, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)
tp_short_price = plot(sold and show_position_on_chart and use_takeprofit? tp_short : na, style = plot.style_linebr, color = color.new(#4cd350, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)
breakeven_long = plot(bought and high<be_long and show_position_on_chart and use_breakeven? be_long : na , style = plot.style_linebr, color = color.new(#1fc9fd, 60), linewidth = 1, display = display.all - display.status_line - display.price_scale)
breakeven_short = plot(sold and low>be_short and show_position_on_chart and use_breakeven? be_short : na , style = plot.style_linebr, color = color.new(#1fc9fd, 60), linewidth = 1, display = display.all - display.status_line - display.price_scale)
show_tpbe_on_chart = input.bool(defval=true, title="Draw first take profit/breakeven price on chart ?", group = "============ Appearance ============", tooltip = "Activate to display take profit and breakeven price. It appears as a green point in the chart")
long_stoploss_distance = close - longStopLoss
short_stoploss_distance=shortStopLoss - close
be_long_plot = close + long_stoploss_distance * risk_reward_breakeven_long
be_short_plot =((short_stoploss_distance*risk_reward_breakeven_short)-close)*-1
tp_long_plot = close+(long_stoploss_distance*risk_reward_take_profit_long)
tp_short_plot = ((short_stoploss_distance*risk_reward_take_profit_short)-close)*-1
plot(show_tpbe_on_chart and buy and use_breakeven and bullish and ema_filter_long or show_tpbe_on_chart and buy and use_breakeven and not ema_filter_long ? be_long_plot : na, color=color.new(#1fc9fd, 10), style = plot.style_circles, linewidth = 2, display = display.all - display.price_scale)
plot(show_tpbe_on_chart and sell and use_breakeven and bearish and ema_filter_short or show_tpbe_on_chart and sell and use_breakeven and not ema_filter_short ? be_short_plot : na, color=color.new(#1fc9fd, 10), style = plot.style_circles, linewidth = 2, display = display.all - display.price_scale)
plot(show_tpbe_on_chart and buy and use_takeprofit and bullish and ema_filter_long or show_tpbe_on_chart and buy and use_takeprofit and not ema_filter_long? tp_long_plot : na, color=color.new(#4cd350, 10), style = plot.style_circles, linewidth = 2, display = display.all - display.price_scale)
plot(show_tpbe_on_chart and sell and use_takeprofit and bearish and ema_filter_short or show_tpbe_on_chart and sell and use_takeprofit and not ema_filter_short? tp_short_plot : na, color=color.new(#4cd350, 10), style = plot.style_circles, linewidth = 2, display = display.all - display.price_scale)
plot(show_stoploss and buy and bullish and ema_filter_long or show_stoploss and buy and not ema_filter_long ? longStopLoss : na, title = "stop loss long", color = color.white, style = plot.style_circles, linewidth = 2)
plot(show_stoploss and sell and bearish and ema_filter_short or show_stoploss and sell and not ema_filter_long ? shortStopLoss : na, title = "stop loss short", color = color.white, style = plot.style_circles, linewidth = 2)
position_profit_long = plot(bought and show_position_on_chart and strategy.openprofit>0 ? close : na, style = plot.style_linebr, color = color.new(#4cd350, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)
position_profit_short = plot(sold and show_position_on_chart and strategy.openprofit>0 ? close : na, style = plot.style_linebr, color = color.new(#4cd350, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)
fill(plot1 = position_price, plot2 = position_profit_long, color = color.new(#4cd350, 90))
fill(plot1 = position_price, plot2 = position_profit_short, color = color.new(#4cd350, 90))
fill(plot1 = position_price, plot2 = sl_long_price, color = color.new(color.red,90))
fill(plot1 = position_price, plot2 = sl_short_price, color = color.new(color.red,90))
fill(plot1 = position_price, plot2 = tp_long_price, color = color.new(color.green,90))
fill(plot1 = position_price, plot2 = tp_short_price, color = color.new(color.green,90))
show_signals = input.bool(defval=true, title="Show signals on chart ?", group = "============ Appearance ============")
plotshape(show_signals and buy and bullish and ema_filter_long or show_signals and buy and not ema_filter_long ? low : na, title='Buy', text='Buy', style=shape.labelup, location=location.belowbar, color=color.new(color.green, 20), textcolor=color.new(color.white, 0), size=size.tiny , display = display.all - display.price_scale - display.status_line)
plotshape(show_signals and sell and bearish and ema_filter_long or show_signals and sell and not ema_filter_short ? high : na, title='Sell', text='Sell', style=shape.labeldown, location=location.abovebar, color=color.new(color.red, 20), textcolor=color.new(color.white, 0), size=size.tiny, display = display.all - display.price_scale - display.status_line)
plotshape(show_signals and closelong_supertrend and close_withsupertrend and bought or show_signals and sell and bought ? low : na, title='Cl Buy', text='Cl Buy', style=shape.labelup, location=location.belowbar, color=color.new(#4cafaf, 30), textcolor=color.new(color.white, 0), size=size.tiny , display = display.all - display.price_scale - display.status_line)
plotshape(show_signals and closeshort_supertrend and close_withsupertrend and sold or show_signals and buy and bought? high : na, title='Cl Buy', text='Cl sell', style=shape.labeldown, location=location.abovebar, color=color.new(#4cafaf, 30), textcolor=color.new(color.white, 0), size=size.tiny, display = display.all - display.price_scale - display.status_line)
// ===============================================================================================================================================
// --------------- Positions amount calculator -------------
contracts_amount_c = initial_actual_capital / close
distance_sl_long_c = -1 * (longStopLoss - close) / close
distance_sl_short_c = (shortStopLoss - close) / close
long_amount_c = close * (contracts_amount_c * (risk_c / 100) / distance_sl_long_c)
short_amount_c = close * (contracts_amount_c * (risk_c / 100) / distance_sl_short_c)
long_amount_lev = close * (contracts_amount_c * (risk_c / 100) / distance_sl_long_c)
short_amount_lev = close * (contracts_amount_c * (risk_c / 100) / distance_sl_short_c)
leverage_for_calculator=input.bool(defval=true, title="Use leverage ?", group = "============ Position amount calculator ===========", tooltip = "If it is activated, there will be no monetary units or amount of assets limit for each operation (That is, each operation will not be affected by the initial / current capital since it would be using leverage). If it is deactivated, the monetary units or the amount of assets to use for each operation will be limited by the initial/current capital.")
if not leverage_for_calculator and long_amount_lev>initial_actual_capital
long_amount_lev:=initial_actual_capital
if not leverage_for_calculator and short_amount_lev>initial_actual_capital
short_amount_lev:=initial_actual_capital
plot(buy and leverage_for_calculator ? long_amount_c : na, color = color.rgb(255, 230, 0), display = display.all - display.pane - display.price_scale)
plot(sell and leverage_for_calculator ? short_amount_c : na, color = color.rgb(255, 230, 0), display = display.all - display.pane - display.price_scale)
plot(buy and not leverage_for_calculator ? long_amount_lev : na, color = color.rgb(255, 230, 0), display = display.all - display.pane - display.price_scale)
plot(sell and not leverage_for_calculator ? short_amount_lev : na, color = color.rgb(255, 230, 0), display = display.all - display.pane - display.price_scale)
// ===============================================================================================================================================
// ===================== Drawing stats about add and withdraw money frequently and others on chart ===================
if not bought and buy and date and not ema_filter_long
totaltrades += 1
if not sold and sell and date and not ema_filter_short
totaltrades += 1
if not bought and buy and date and bearish and ema_filter_long
totaltrades += 0
if not sold and sell and date and bullish and ema_filter_short
totaltrades += 0
if not bought and buy and date and bullish and ema_filter_long
totaltrades += 1
if not sold and sell and date and bearish and ema_filter_short
totaltrades += 1
total_money_added = initial_capital_a - strategy.initial_capital
total_money_withdrawn = initial_capital_w - strategy.initial_capital
final_money = total_money_added + strategy.netprofit + strategy.initial_capital - total_money_withdrawn // or current money avaliable
// plot(commission_value_l, color = color.rgb(59, 245, 255), display = display.all - display.pane)
// plot(commission_value_s, color = color.rgb(59, 245, 255), display = display.all - display.pane)
// plot(total_commissions_value, color = color.rgb(252, 59, 255), display = display.all - display.pane)
// plot(total_trades/2, color = color.rgb(59, 245, 255), display = display.all - display.pane)
// plot(final_money, color = color.yellow, display = display.all - display.pane)
// plot(total_money_added, color = color.blue, display = display.all - display.pane)
// plot(total_money_withdrawn, color = color.red, display = display.all - display.pane)
// plot(strategy.netprofit, color = color.green, display = display.all - display.pane)
truncate(_number, _decimalPlaces) =>
_factor = math.pow(10, _decimalPlaces)
int(_number * _factor) / _factor
draw_stats = input.bool(true, "Show stats from add/withdraw money frequently ?", group = "============ Appearance ============")
// Prepare stats table
var table testTable = table.new(position.top_right, 5, 2, border_width=2, frame_color = color.rgb(0, 0, 0), frame_width = 2)
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor,_size,_tooltip) =>
_cellText = _title + "\n" + _value
table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=_size, tooltip = _tooltip)
// Draw stats table
var bgcolor = color.new(#2f5cda, 50)
var bgcolor2 = color.new(color.green, 50)
var bgcolor3 = color.new(color.red,50)
if draw_stats
if barstate.islastconfirmedhistory
f_fillCell(testTable, 0, 0, "Final/current money:", "$" + str.tostring(truncate(final_money,2)), bgcolor, color.white, _size = size.normal, _tooltip = "Total money added + total return from strategy + initial capital - total money withdrawn")
f_fillCell(testTable, 0, 1, "Total money added:", "$" + str.tostring(truncate(total_money_added,2)), bgcolor, color.white, _size = size.normal, _tooltip = "Sum of total money added at the end of the date")
f_fillCell(testTable, 1, 0, "Total money withdrawn:", "$" + str.tostring(truncate(total_money_withdrawn*-1,2)), bgcolor, color.white, _size = size.normal, _tooltip = "Sum of total money withdrawn at the end of the date")
f_fillCell(testTable, 1, 1, "Total return:", "$" + str.tostring(truncate(strategy.netprofit,2)), strategy.netprofit > 0 ? bgcolor2 : bgcolor3 , color.white, _size = size.normal, _tooltip = "Total return from strategy until the end of the date (it could be different from default backtesting if last position have not been closed completly)")
f_fillCell(testTable, 2, 0, "Total trades:", "" + str.tostring(truncate(totaltrades,2)), bgcolor, color.white, _size = size.normal, _tooltip = "Sum of real total trades. The value from default backtester it´s not precise")
f_fillCell(testTable, 2, 1, "Total commissions value:", "" + str.tostring(truncate(total_commissions_value,2)), bgcolor, color.white, _size = size.normal, _tooltip = "Sum of commissions value from all trades. You must set the % value in the script settings (Positions management).")
// ===================================================================== :D |
Risk Reward Calculator [lovealgotrading] | https://www.tradingview.com/script/GbgkGI2h-Risk-Reward-Calculator-lovealgotrading/ | projeadam | https://www.tradingview.com/u/projeadam/ | 291 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Baby_whale_to_moon
// I want to say thank you to © EvoCrypto
//@version=5
strategy('Risk Reward Calculator', shorttitle='R:R', overlay=true, max_bars_back = 2000, pyramiding = 4, initial_capital = 5000, commission_value = 0.1 ,slippage = 1)
//INPUTS -----------------------------------------------------------------------
startDate = input.time(defval=timestamp('1 apr 2023 13:30 +0000'), title='Start_Date', group = " ######### ⏳ STRATEGY WORK TIME ⏳###########" )
endDate = input.time(defval=timestamp('20 oct 2030 13:30 +0000'), title='End_Date', group = " ######### ⏳ STRATEGY WORK TIME ⏳###########" )
inDateRange = time > startDate and time < endDate
take_profit_level = input.float(0, step=0.1, minval=0, title='Take Profit Price', group = " ######### ⚠️ STRATEGY RISK SETTINGS ⚠️#########")
Stop_Level = input.float(0, minval=0, step=0.1, title='Stop Loss Price', group = " ######### ⚠️ STRATEGY RISK SETTINGS ⚠️#########")
Risk_Amount = input.float(100, minval=0, step=0.1, title='Risk Amount In Dollar', group = " ######### ⚠️ STRATEGY RISK SETTINGS ⚠️#########")
Alert = input.bool(true,title = "Sum of transactions weight must be 100%", group = " ######### ⭐️ STRATEGY ENTRY SETTINGS ⭐️########")
Price_1_val = input.float(0, step=0.1, minval=0, title='Entry Price One', group = " ######### ⭐️ STRATEGY ENTRY SETTINGS ⭐️########")
Weight_1 = input.string('NaN', ' ⚖️ Weight', options=['NaN', '90 %', '80 %', '• 75 %', '70 %', '60 %', '• 50 %', '40 %', '30 %', '• 25 %', '20 %', '10 %'], group = " ######### ⭐️ STRATEGY ENTRY SETTINGS ⭐️########")
Price_2_val = input.float(0, step=0.1, minval=0, title='Entry Price Two', group = " ######### ⭐️ STRATEGY ENTRY SETTINGS ⭐️########")
Weight_2 = input.string('NaN', ' ⚖️ Weight', options=['NaN', '90 %', '80 %', '• 75 %', '70 %', '60 %', '• 50 %', '40 %', '30 %', '• 25 %', '20 %', '10 %'], group = " ######### ⭐️ STRATEGY ENTRY SETTINGS ⭐️########")
Price_3_val = input.float(0, step=0.1, minval=0, title='Entry Price Three', group = " ######### ⭐️ STRATEGY ENTRY SETTINGS ⭐️########")
Weight_3 = input.string('NaN', ' ⚖️ Weight', options=['NaN', '90 %', '80 %', '• 75 %', '70 %', '60 %', '• 50 %', '40 %', '30 %', '• 25 %', '20 %', '10 %'], group = " ######### ⭐️ STRATEGY ENTRY SETTINGS ⭐️########")
Price_4_val = input.float(0, step=0.1, minval=0, title='Entry Price Four', group = " ######### ⭐️ STRATEGY ENTRY SETTINGS ⭐️########")
Weight_4 = input.string('NaN', ' ⚖️ Weight', options=['NaN', '90 %', '80 %', '• 75 %', '70 %', '60 %', '• 50 %', '40 %', '30 %', '• 25 %', '20 %', '10 %'], group = " ######### ⭐️ STRATEGY ENTRY SETTINGS ⭐️########")
Alert_message_miss = input.bool(true,title = "DON'T FORGET PASTE YOUR WEBHOOK URL WHEN YOU SET ALERT", group = "############ 🤖 ALGO TRADE ALERTS 🤖 ############")
Long_message = input("",title = "Long Entry Code", group = "############ 🤖 ALGO TRADE ALERTS 🤖 ############")
Long_Exit_message = input("",title = "Long Stop-Take Profit Code", group = "############ 🤖 ALGO TRADE ALERTS 🤖 ############")
Short_message = input("",title = "Short Entry Code", group = "############ 🤖 ALGO TRADE ALERTS 🤖 ############")
Short_Exit_message = input("",title = "Short Stop-Take Profit Code", group = "############ 🤖 ALGO TRADE ALERTS 🤖 ############")
Alert_message = input("{{strategy.order.alert_message}}",title = "Code When Set Alert", group = "############ 🤖 ALGO TRADE ALERTS 🤖 ############")
show_label = input.bool(title=' Show Labels',defval=true, group = " ############ 🏁 LABEL SETTINGS 🏁 ############")
Visual = input.string('All Timeframes', 'Calculator Visual', options=['All Timeframes', 'Intraday Only', 'Daily/Weekly/Monthly Only'], group = " ############ 🏁 LABEL SETTINGS 🏁 ############")
Label_Size = input.string(size.small, 'Label Size', options=[size.tiny, size.small, size.normal, size.large, size.huge], group = " ############ 🏁 LABEL SETTINGS 🏁 ############")
Show_Real_Distance = input(true, title='Real-Time Distance In Label', group = " ############ 🏁 LABEL SETTINGS 🏁 ############")
Show_Stop_Distance = input(true, title='Stop Loss Distance In Label', group = " ############ 🏁 LABEL SETTINGS 🏁 ############")
Show_Order_Amount = input(true, title='Dollar Order Amount In Label', group = " ############ 🏁 LABEL SETTINGS 🏁 ############")
Show_Price = input(true, title='Show Price Inputs In Label', group = " ############ 🏁 LABEL SETTINGS 🏁 ############")
Use_One_Label = input(false, title='Show All Text In One Label', group = " ############ 🏁 LABEL SETTINGS 🏁 ############")
//bgcolor(show_label and inDateRange ? color.rgb(175, 246, 255, 90) : na , title = "STRATEGY WORK TIME BG" )
//TIMEFRAME --------------------------------------------------------------------
Timeframe = timeframe.isintraday and Visual == 'Intraday Only' or timeframe.isdwm and Visual == 'Daily/Weekly/Monthly Only' or Visual == 'All Timeframes'
//QUALIFIERS -------------------------------------------------------------------
take_profit_level_True = Timeframe ? take_profit_level != 0 : na
Stop_True = Timeframe ? Stop_Level != 0 : na
Price_1_val_True = Timeframe ? Price_1_val != 0 : na
Price_2_val_True = Timeframe ? Price_1_val != 0 and Price_2_val != 0 : na
Price_3_val_True = Timeframe ? Price_1_val != 0 and Price_2_val != 0 and Price_3_val != 0 : na
Price_4_val_True = Timeframe ? Price_1_val != 0 and Price_2_val != 0 and Price_3_val != 0 and Price_4_val != 0 : na
Avg_Price_True = Timeframe ? Price_2_val_True or Price_3_val_True : na
quantity(dolar) =>
if close > 5000
math.round(dolar / close, 3)
else if close < 5000 and close > 200
math.round(dolar / close, 2)
else if close < 200 and close > 50
math.round(dolar / close, 1)
else if close < 50
math.round(dolar / close, 0)
//PRICE 1 ----------------------------------------------------------------------
Weight_One_Options = Weight_1 == 'NaN' ? 1 : Weight_1 == '90 %' ? 0.90 : Weight_1 == '80 %' ? 0.80 : Weight_1 == '• 75 %' ? 0.75 : Weight_1 == '70 %' ? 0.70 : Weight_1 == '60 %' ? 0.60 : Weight_1 == '• 50 %' ? 0.50 : Weight_1 == '40 %' ? 0.40 : Weight_1 == '30 %' ? 0.30 : Weight_1 == '• 25 %' ? 0.25 : Weight_1 == '20 %' ? 0.20 : Weight_1 == '10 %' ? 0.10 : na
Weight_One = Price_1_val * Weight_One_Options
Real_Price_1_val_Distance = Price_1_val_True and close > Price_1_val ? (close - Price_1_val) / close * 100 : Price_1_val_True and close < Price_1_val ? (Price_1_val - close) / close * 100 : na
//PRICE 2 ----------------------------------------------------------------------
Weight_Two_Options = Weight_2 == 'NaN' ? 1 : Weight_2 == '90 %' ? 0.90 : Weight_2 == '80 %' ? 0.80 : Weight_2 == '• 75 %' ? 0.75 : Weight_2 == '70 %' ? 0.70 : Weight_2 == '60 %' ? 0.60 : Weight_2 == '• 50 %' ? 0.50 : Weight_2 == '40 %' ? 0.40 : Weight_2 == '30 %' ? 0.30 : Weight_2 == '• 25 %' ? 0.25 : Weight_2 == '20 %' ? 0.20 : Weight_2 == '10 %' ? 0.10 : na
Weight_Two = Price_2_val * Weight_Two_Options
Real_Price_2_val_Distance = Price_2_val_True and close > Price_2_val ? (close - Price_2_val) / close * 100 : Price_2_val_True and close < Price_2_val ? (Price_2_val - close) / close * 100 : na
//PRICE 3 ----------------------------------------------------------------------
Weight_Three_Options = Weight_3 == 'NaN' ? 1 : Weight_3 == '90 %' ? 0.90 : Weight_3 == '80 %' ? 0.80 : Weight_3 == '• 75 %' ? 0.75 : Weight_3 == '70 %' ? 0.70 : Weight_3 == '60 %' ? 0.60 : Weight_3 == '• 50 %' ? 0.50 : Weight_3 == '40 %' ? 0.40 : Weight_3 == '30 %' ? 0.30 : Weight_3 == '• 25 %' ? 0.25 : Weight_3 == '20 %' ? 0.20 : Weight_3 == '10 %' ? 0.10 : na
Weight_Three = Price_3_val * Weight_Three_Options
Real_Price_3_val_Distance = Price_3_val_True and close > Price_3_val ? (close - Price_3_val) / close * 100 : Price_3_val_True and close < Price_3_val ? (Price_3_val - close) / close * 100 : na
//PRICE 4 ----------------------------------------------------------------------
Weight_Four_Options = Weight_4 == 'NaN' ? 1 : Weight_4 == '90 %' ? 0.90 : Weight_4 == '80 %' ? 0.80 : Weight_4 == '• 75 %' ? 0.75 : Weight_4 == '70 %' ? 0.70 : Weight_4 == '60 %' ? 0.60 : Weight_4 == '• 50 %' ? 0.50 : Weight_4 == '40 %' ? 0.40 : Weight_4 == '30 %' ? 0.30 : Weight_4 == '• 25 %' ? 0.25 : Weight_4 == '20 %' ? 0.20 : Weight_4 == '10 %' ? 0.10 : na
Weight_Four = Price_4_val * Weight_Four_Options
Real_Price_4_val_Distance = Price_4_val_True and close > Price_4_val ? (close - Price_4_val) / close * 100 : Price_4_val_True and close < Price_4_val ? (Price_4_val - close) / close * 100 : na
//AVERAGE PRICE ----------------------------------------------------------------
Avg_2_True = Weight_1 == 'NaN' and Weight_2 == 'NaN'
Avg_3_True = Weight_1 == 'NaN' and Weight_2 == 'NaN' and Weight_3 == 'NaN'
Avg_4_True = Weight_1 == 'NaN' and Weight_2 == 'NaN' and Weight_3 == 'NaN' and Weight_4 == 'NaN'
Avg_Price = Price_2_val_True and Avg_2_True and Price_3_val == 0 and Price_4_val == 0 ? math.avg(Price_1_val, Price_2_val) : Price_3_val_True and Avg_3_True ? math.avg(Price_1_val, Price_2_val, Price_3_val) : Price_4_val_True and Avg_4_True ? math.avg(Price_1_val, Price_2_val, Price_3_val, Price_4_val) : Weight_One + Weight_Two + Weight_Three + Weight_Four
Real_Avg_Price_Distance = Avg_Price_True and close > Avg_Price ? (close - Avg_Price) / close * 100 : Avg_Price_True and close < Avg_Price ? (Avg_Price - close) / close * 100 : na
//POSITION SETTINGS ------------------------------------------------------------
Real_Stop_Distance = Stop_True and close > Stop_Level ? (close - Stop_Level) / close * 100 : Stop_True and close < Stop_Level ? (Stop_Level - close) / close * 100 : na
Stop_Distance = Avg_Price != 0 and Stop_True and Avg_Price > Stop_Level ? (Avg_Price - Stop_Level) / Avg_Price * 100 : Avg_Price != 0 and Stop_True and Avg_Price < Stop_Level ? (Stop_Level - Avg_Price) / Avg_Price * 100 : Real_Stop_Distance
Real_TP_Distance = take_profit_level_True and close > take_profit_level ? (close - take_profit_level) / close * 100 : take_profit_level_True and close < take_profit_level ? (take_profit_level - close) / close * 100 : na
TP_Distance = Avg_Price != 0 and take_profit_level_True and Avg_Price > take_profit_level ? (Avg_Price - take_profit_level) / Avg_Price * 100 : Avg_Price != 0 and take_profit_level_True and Avg_Price < take_profit_level ? (take_profit_level - Avg_Price) / Avg_Price * 100 : Real_TP_Distance
Position_Size = Risk_Amount / Stop_Distance * 100
Order_One = Weight_1 != 'NaN' ? Position_Size * Weight_One_Options : Weight_1 == 'NaN' and Price_2_val == 0 and Price_3_val == 0 ? Position_Size : Weight_1 == 'NaN' and Price_2_val_True and Price_3_val == 0 ? Position_Size / 2 : Weight_1 == 'NaN' and Price_3_val_True ? Position_Size / 3 : Weight_1 == 'NaN' and Price_4_val_True ? Position_Size / 4 : na
Order_Two = Weight_2 != 'NaN' ? Position_Size * Weight_Two_Options : Weight_2 == 'NaN' and Price_2_val_True and Price_3_val == 0 ? Position_Size / 2 : Weight_2 == 'NaN' and Price_3_val_True ? Position_Size / 3 : Weight_2 == 'NaN' and Price_4_val_True ? Position_Size / 4 : na
Order_Three = Weight_3 != 'NaN' ? Position_Size * Weight_Three_Options : Weight_3 == 'NaN' and Price_3_val_True ? Position_Size / 3 : Weight_3 == 'NaN' and Price_4_val_True ? Position_Size / 4 : na
Order_Four = Weight_4 != 'NaN' ? Position_Size * Weight_Four_Options : Weight_4 == 'NaN' and Price_4_val_True ? Position_Size / 4 : na
//LABEL LOCATIONS --------------------------------------------------------------
Stop_Location = timenow + math.round(ta.change(time) * (Price_3_val_True ? 115 : Price_2_val_True ? 95 : Price_1_val_True ? 75 : 55))
Price_1_val_Location = timenow + math.round(ta.change(time) * 15 )
Price_2_val_Location = timenow + math.round(ta.change(time) * 35)
Price_3_val_Location = timenow + math.round(ta.change(time) * 55)
Price_4_val_Location = timenow + math.round(ta.change(time) * 75)
Avg_Price_Location = timenow + math.round(ta.change(time) * (Price_3_val_True ? 115 : Price_2_val_True ? 95 : Price_1_val_True ? 75 : 55))
One_Label_Location = timenow + math.round(ta.change(time) * 50)
take_profit_level_Location = timenow + math.round(ta.change(time) * (Price_3_val_True ? 115 : Price_2_val_True ? 95 : Price_1_val_True ? 75 : 55))
//COLORS -----------------------------------------------------------------------
Stop_Color = #b71c1c
Price_Color = #0011ff
Label_Color = #2db3fb
Text_Color = #000000
//Take Profit PLOT ---------------------------------------------------------------
Take_Profit_Line = take_profit_level_True ? line.new(x1=startDate, y1=take_profit_level, x2=endDate, y2=take_profit_level, style=line.style_dashed, xloc = xloc.bar_time, width=2, color=color.lime) : na
line.delete(Take_Profit_Line[1])
plot(take_profit_level_True ? take_profit_level : na, title='Take Profit', color=color.new(color.lime, 100))
Take_Profit_Label = Use_One_Label ? na : Avg_Price != 0 and take_profit_level_True and Avg_Price < take_profit_level or Avg_Price == 0 and take_profit_level_True and close < take_profit_level and show_label and show_label ? label.new(x=take_profit_level_Location, y=take_profit_level, xloc=xloc.bar_time, yloc=yloc.price, style=label.style_label_up, color=color.lime, textcolor=Text_Color, size=Label_Size, text='TP Long' + (Show_Real_Distance ? '\n' + 'Distance → ' + str.tostring(Real_TP_Distance, '0.00') + ' %' : na) + (Show_Stop_Distance ? '\n' + 'TakeProfit → ' + str.tostring(TP_Distance, '0.00') + ' %' + '\n' + 'Win $ → ' + str.tostring(Position_Size * TP_Distance / 100, '#') + ' $' : na) + (Show_Order_Amount ? '\n' + 'Position → ' + str.tostring(Position_Size, '#') + ' $' : na) + (Show_Price ? '\n' + 'Price → ' + str.tostring(take_profit_level) : na)) : Avg_Price != 0 and take_profit_level_True and Avg_Price > take_profit_level or Avg_Price == 0 and take_profit_level_True and close > take_profit_level and show_label ? label.new(x=take_profit_level_Location, y=take_profit_level, xloc=xloc.bar_time, yloc=yloc.price, style=label.style_label_down, color=color.lime, textcolor=Text_Color, size=Label_Size, text='TP Short' + (Show_Real_Distance ? '\n' + 'Distance → ' + str.tostring(Real_TP_Distance, '0.00') + ' %' : na) + (Show_Stop_Distance ? '\n' + 'TakeProfit → ' + str.tostring(TP_Distance, '0.00') + ' %' + '\n' + 'Win $ → ' + str.tostring(Position_Size * TP_Distance / 100, '#') + ' $' : na) + (Show_Order_Amount ? '\n' + 'Position → ' + str.tostring(Position_Size, '#') + ' $' : na) + (Show_Price ? '\n' + 'Price → ' + str.tostring(Stop_Level) : na)) : na
label.delete(Take_Profit_Label[1])
//STOP LOSS PLOT ---------------------------------------------------------------
Stop_Line = Stop_True ? line.new(x1=startDate, y1=Stop_Level, x2=endDate, y2=Stop_Level, style=line.style_dashed,xloc = xloc.bar_time, width=2, color=Stop_Color) : na
line.delete(Stop_Line[1])
plot(Stop_True ? Stop_Level : na, title='Stop Loss', color=color.new(Stop_Color, 100))
Stop_Label = Use_One_Label ? na : Avg_Price != 0 and Stop_True and Avg_Price > Stop_Level or Avg_Price == 0 and Stop_True and close > Stop_Level and show_label ? label.new(x=Stop_Location, y=Stop_Level, xloc=xloc.bar_time, yloc=yloc.price, style=label.style_label_up, color=color.red, textcolor=Text_Color, size=Label_Size, text='Stop LONG' + (Show_Real_Distance ? '\n' + 'Distance → ' + str.tostring(Real_Stop_Distance, '0.00') + ' %' : na) + (Show_Stop_Distance ? '\n' + 'StopLoss → ' + str.tostring(Stop_Distance, '0.00') + ' %' + '\n' + 'Loss $ → ' + str.tostring(Position_Size * Stop_Distance / 100, '#') + ' $' : na) + (Show_Order_Amount ? '\n' + 'Position → ' + str.tostring(Position_Size, '#') + ' $' : na) + (Show_Price ? '\n' + 'Price → ' + str.tostring(Stop_Level) : na)) : Avg_Price != 0 and Stop_True and Avg_Price < Stop_Level or Avg_Price == 0 and Stop_True and close < Stop_Level and show_label ? label.new(x=Stop_Location, y=Stop_Level, xloc=xloc.bar_time, yloc=yloc.price, style=label.style_label_down, color=color.red, textcolor=Text_Color, size=Label_Size, text='Stop SHORT' + (Show_Real_Distance ? '\n' + 'Distance → ' + str.tostring(Real_Stop_Distance, '0.00') + ' %' : na) + (Show_Stop_Distance ? '\n' + 'StopLoss → ' + str.tostring(Stop_Distance, '0.00') + ' %' + '\n' + 'Loss $ → ' + str.tostring(Position_Size * Stop_Distance / 100, '#') + ' $' : na) + (Show_Order_Amount ? '\n' + 'Position → ' + str.tostring(Position_Size, '#') + ' $' : na) + (Show_Price ? '\n' + 'Price → ' + str.tostring(Stop_Level) : na)) : na
label.delete(Stop_Label[1])
//PRICE 1 PLOT -----------------------------------------------------------------
Price_1_val_Line = Price_1_val_True ? line.new(x1=startDate, y1=Price_1_val, x2=endDate, y2=Price_1_val,xloc = xloc.bar_time, color=Price_Color) : na
line.delete(Price_1_val_Line[1])
plot(Price_1_val_True ? Price_1_val : na, title='Price One', color=color.new(Price_Color, 100))
Price_1_val_Label = Use_One_Label ? na : Price_1_val_True and close > Price_1_val and Stop_Level == 0 or Price_1_val_True and Stop_True and Stop_Level < Avg_Price and show_label ? label.new(x=Price_1_val_Location, y=Price_1_val, xloc=xloc.bar_time, yloc=yloc.price, style=label.style_label_up, color=Label_Color, textcolor=Text_Color, size=Label_Size, text='(1) ' + (true ? 'Buy → ' + str.tostring(Order_One, '# $') + '\n' + 'Open Position → ' + str.tostring(Weight_1) : na) + (Show_Real_Distance ? '\n' + 'Distance → ' + str.tostring(Real_Price_1_val_Distance, '0.00') + ' %' : na) + (Show_Price ? '\n' + 'Price → ' + str.tostring(Price_1_val) : na)) : Price_1_val_True and close < Price_1_val and Stop_Level == 0 or Price_1_val_True and Stop_True and Stop_Level > Avg_Price and show_label ? label.new(x=Price_1_val_Location, y=Price_1_val, xloc=xloc.bar_time, yloc=yloc.price, style=label.style_label_down, color=Label_Color, textcolor=Text_Color, size=Label_Size, text='(1) ' + (true ? 'Sell → ' + str.tostring(Order_One, '# $') + '\n' + 'Open Position → ' + str.tostring(Weight_1) : na) + (Show_Real_Distance ? '\n' + 'Distance → ' + str.tostring(Real_Price_1_val_Distance, '0.00') + ' %' : na) + (Show_Price ? '\n' + 'Price → ' + str.tostring(Price_1_val) : na)) : na
label.delete(Price_1_val_Label[1])
//PRICE 2 PLOT -----------------------------------------------------------------
Price_2_val_Line = Price_2_val_True ? line.new(x1=startDate, y1=Price_2_val, x2=endDate, y2=Price_2_val,xloc = xloc.bar_time, color=Price_Color) : na
line.delete(Price_2_val_Line[1])
plot(Price_2_val_True ? Price_2_val : na, title='Price Two', color=color.new(Price_Color, 100))
Price_2_val_Label = Use_One_Label ? na : Price_2_val_True and close > Price_2_val and Stop_Level == 0 or Price_2_val_True and Stop_True and Stop_Level < Avg_Price and show_label ? label.new(x=Price_2_val_Location, y=Price_2_val, xloc=xloc.bar_time, yloc=yloc.price, style=label.style_label_up, color=Label_Color, textcolor=Text_Color, size=Label_Size, text='(2) ' + (true ? 'Buy → ' + str.tostring(Order_Two, '# $') + '\n' + 'Open Position → ' + str.tostring(Weight_2) : na) + (Show_Real_Distance ? '\n' + 'Distance → ' + str.tostring(Real_Price_2_val_Distance, '0.00') + ' %' : na) + (Show_Price ? '\n' + 'Price → ' + str.tostring(Price_2_val) : na)) : Price_2_val_True and close < Price_2_val and Stop_Level == 0 or Price_2_val_True and Stop_True and Stop_Level > Avg_Price and show_label ? label.new(x=Price_2_val_Location, y=Price_2_val, xloc=xloc.bar_time, yloc=yloc.price, style=label.style_label_down, color=Label_Color, textcolor=Text_Color, size=Label_Size, text='(2) ' + (true ? 'Sell → ' + str.tostring(Order_Two, '# $') + '\n' + 'Open Position → ' + str.tostring(Weight_2) : na) + (Show_Real_Distance ? '\n' + 'Distance → ' + str.tostring(Real_Price_2_val_Distance, '0.00') + ' %' : na) + (Show_Price ? '\n' + 'Price → ' + str.tostring(Price_2_val) : na)) : na
label.delete(Price_2_val_Label[1])
//PRICE 3 PLOT -----------------------------------------------------------------
Price_3_val_Line = Price_3_val_True ? line.new(x1=startDate, y1=Price_3_val, x2=endDate, y2=Price_3_val,xloc = xloc.bar_time, color=Price_Color) : na
line.delete(Price_3_val_Line[1])
plot(Price_3_val_True ? Price_3_val : na, title='Price Three', color=color.new(Price_Color, 100))
Price_3_val_Label = Use_One_Label ? na : Price_3_val_True and close > Price_3_val and Stop_Level == 0 or Price_3_val_True and Stop_True and Stop_Level < Avg_Price and show_label ? label.new(x=Price_3_val_Location, y=Price_3_val, xloc=xloc.bar_time, yloc=yloc.price, style=label.style_label_up, color=Label_Color, textcolor=Text_Color, size=Label_Size, text='(3) ' + (true ? 'Buy → ' + str.tostring(Order_Three, '# $') + '\n' + 'Open Position → ' + str.tostring(Weight_3) : na) + (Show_Real_Distance ? '\n' + 'Distance → ' + str.tostring(Real_Price_3_val_Distance, '0.00') + ' %' : na) + (Show_Price ? '\n' + 'Price → ' + str.tostring(Price_3_val) : na)) : Price_3_val_True and close < Price_3_val and Stop_Level == 0 or Price_3_val_True and Stop_True and Stop_Level > Avg_Price and show_label ? label.new(x=Price_3_val_Location, y=Price_3_val, xloc=xloc.bar_time, yloc=yloc.price, style=label.style_label_down, color=Label_Color, textcolor=Text_Color, size=Label_Size, text='(3) ' + (true ? 'Sell → ' + str.tostring(Order_Three, '# $') + '\n' + 'Open Position → ' + str.tostring(Weight_3) : na) + (Show_Real_Distance ? '\n' + 'Distance → ' + str.tostring(Real_Price_3_val_Distance, '0.00') + ' %' : na) + (Show_Price ? '\n' + 'Price → ' + str.tostring(Price_3_val) : na)) : na
label.delete(Price_3_val_Label[1])
//PRICE 4 PLOT -----------------------------------------------------------------
Price_4_val_Line = Price_4_val_True ? line.new(x1=startDate, y1=Price_4_val, x2=endDate, y2=Price_4_val,xloc = xloc.bar_time, color=Price_Color) : na
line.delete(Price_4_val_Line[1])
plot(Price_4_val_True ? Price_4_val : na, title='Price Four', color=color.new(Price_Color, 100))
Price_4_val_Label = Use_One_Label ? na : Price_4_val_True and close > Price_4_val and Stop_Level == 0 or Price_4_val_True and Stop_True and Stop_Level < Avg_Price and show_label ? label.new(x=Price_4_val_Location, y=Price_4_val, xloc=xloc.bar_time, yloc=yloc.price, style=label.style_label_up, color=Label_Color, textcolor=Text_Color, size=Label_Size, text='(4) ' + (true ? 'Buy → ' + str.tostring(Order_Four, '# $') + '\n' + 'Open Position → ' + str.tostring(Weight_4) : na) + (Show_Real_Distance ? '\n' + 'Distance → ' + str.tostring(Real_Price_4_val_Distance, '0.00') + ' %' : na) + (Show_Price ? '\n' + 'Price → ' + str.tostring(Price_4_val) : na)) : Price_4_val_True and close < Price_4_val and Stop_Level == 0 or Price_4_val_True and Stop_True and Stop_Level > Avg_Price and show_label ? label.new(x=Price_4_val_Location, y=Price_4_val, xloc=xloc.bar_time, yloc=yloc.price, style=label.style_label_down, color=Label_Color, textcolor=Text_Color, size=Label_Size, text='(4) ' + (true ? 'Sell → ' + str.tostring(Order_Four, '# $') + '\n' + 'Open Position → ' + str.tostring(Weight_4) : na) + (Show_Real_Distance ? '\n' + 'Distance → ' + str.tostring(Real_Price_4_val_Distance, '0.00') + ' %' : na) + (Show_Price ? '\n' + 'Price → ' + str.tostring(Price_4_val) : na)) : na
label.delete(Price_4_val_Label[1])
//AVERAGE PRICE PLOT -----------------------------------------------------------
Avg_Price_Line = Avg_Price_True ? line.new(x1=startDate, y1=Avg_Price, x2=endDate, y2=Avg_Price, style=line.style_dashed,xloc = xloc.bar_time, color=color.yellow) : na
line.delete(Avg_Price_Line[1])
plot(Avg_Price_True ? Avg_Price : na, title='Average Price', color=color.new(color.yellow, 100))
Avg_Price_Label = Use_One_Label ? na : Avg_Price_True and close > Avg_Price and show_label ? label.new(x=Avg_Price_Location, y=Avg_Price, xloc=xloc.bar_time, yloc=yloc.price, style=label.style_label_up, color=color.yellow, textcolor=Text_Color, size=Label_Size, text='AVR Price → ' + str.tostring(Avg_Price) + '\n' + ' R:R → ' + str.tostring(TP_Distance / Stop_Distance, '0.00') + '\n' + 'All Position → ' + str.tostring(Position_Size, '#') + ' $') : Avg_Price_True and close < Avg_Price and show_label ? label.new(x=Avg_Price_Location, y=Avg_Price, xloc=xloc.bar_time, yloc=yloc.price, style=label.style_label_down, color=color.yellow, textcolor=Text_Color, size=Label_Size, text='AVR Price → ' + str.tostring(Avg_Price) + '\n' + ' R:R → ' + str.tostring(TP_Distance / Stop_Distance, '0.00') + '\n' + 'All Position → ' + str.tostring(Position_Size, '#') + ' $') : na
label.delete(Avg_Price_Label[1])
//ONE LABEL --------------------------------------------------------------------
One_Label = Use_One_Label and Avg_Price != 0 and Stop_True and Avg_Price > Stop_Level or Use_One_Label and Avg_Price == 0 and Stop_True and close > Stop_Level or Use_One_Label and Stop_Level == 0 and Avg_Price_True and close > Avg_Price and show_label ? label.new(x=One_Label_Location, y=close, xloc=xloc.bar_time, yloc=yloc.price, style=label.style_label_up, color=Label_Color, textcolor=Text_Color, size=Label_Size, text='TP Long' + (Show_Real_Distance ? '\n' + 'Distance → ' + str.tostring(Real_TP_Distance, '0.00') + ' %' : na) + (Show_Stop_Distance ? '\n' + 'TakeProfit → ' + str.tostring(TP_Distance, '0.00') + ' %' + '\n' + 'Win $ → ' + str.tostring(Position_Size * TP_Distance / 100, '#') + ' $' : na) + (Show_Order_Amount ? '\n' + 'Position → ' + str.tostring(Position_Size, '#') + ' $' : na) + (Show_Price ? '\n' + 'Price → ' + str.tostring(take_profit_level) : na) + '\n\n\n' +'R:R → ' + str.tostring(TP_Distance / Stop_Distance, '0.00') + '\n' + 'All Position → ' + str.tostring(Position_Size, '#') + ' $' + '\n\n'+(Price_1_val_True ? 'Price 1' + '\n———————' + (Show_Order_Amount ? '\n' + 'Order → ' + str.tostring(Order_One, '# $') : na) + (Show_Real_Distance ? '\n' + 'Distance → ' + str.tostring(Real_Price_1_val_Distance, '0.00') + ' %' : na) + (Show_Price ? '\n' + 'Price → ' + str.tostring(Price_1_val) : na) : na) + (Price_2_val_True ? '\n\n Price 2' + '\n———————' + (Show_Order_Amount ? '\n' + 'Order → ' + str.tostring(Order_Two, '# $') : na) + (Show_Real_Distance ? '\n' + 'Distance → ' + str.tostring(Real_Price_2_val_Distance, '0.00') + ' %' : na) + (Show_Price ? '\n' + 'Price → ' + str.tostring(Price_2_val) : na) : na) + (Price_3_val_True ? '\n\n Price 3' + '\n———————' + (Show_Order_Amount ? '\n' + 'Order → ' + str.tostring(Order_Three, '# $') : na) + (Show_Real_Distance ? '\n' + 'Distance → ' + str.tostring(Real_Price_3_val_Distance, '0.00') + ' %' : na) + (Show_Price ? '\n' + 'Price → ' + str.tostring(Price_3_val) : na) : na) + (Avg_Price_True ? '\n\n Average Price' + '\n———————' + (Show_Real_Distance ? '\n' + 'Distance → ' + str.tostring(Real_Avg_Price_Distance, '0.00') + ' %' : na) + (Show_Price ? '\n' + 'Price → ' + str.tostring(Avg_Price) : na) : na) + (Stop_True ? '\n\n Stop Loss' + '\n———————' + (Show_Real_Distance ? '\n' + 'Distance → ' + str.tostring(Real_Stop_Distance, '0.00') + ' %' : na) + (Show_Stop_Distance ? '\n' + 'StopLoss → ' + str.tostring(Stop_Distance, '0.00') + ' %' : na) + (Show_Order_Amount ? '\n' + 'Position → ' + str.tostring(Position_Size, '#') + ' $' : na) + (Show_Price ? '\n' + 'Price → ' + str.tostring(Stop_Level) : na) : na)) : Use_One_Label and Avg_Price != 0 and Stop_True and Avg_Price < Stop_Level or Use_One_Label and Avg_Price == 0 and Stop_True and close < Stop_Level or Use_One_Label and Stop_Level == 0 and Avg_Price_True and close < Avg_Price and show_label ? label.new(x=One_Label_Location, y=close, xloc=xloc.bar_time, yloc=yloc.price, style=label.style_label_down, color=Label_Color, textcolor=Text_Color, size=Label_Size, text='TP Short' + (Show_Real_Distance ? '\n' + 'Distance → ' + str.tostring(Real_TP_Distance, '0.00') + ' %' : na) + (Show_Stop_Distance ? '\n' + 'TakeProfit → ' + str.tostring(TP_Distance, '0.00') + ' %' + '\n' + 'Win $ → ' + str.tostring(Position_Size * TP_Distance / 100, '#') + ' $' : na) + (Show_Order_Amount ? '\n' + 'Position → ' + str.tostring(Position_Size, '#') + ' $' : na) + (Show_Price ? '\n' + 'Price → ' + str.tostring(take_profit_level) : na) + '\n\n' + (Stop_True ? 'Stop Loss' + '\n———————' + (Show_Real_Distance ? '\n' + 'Distance → ' + str.tostring(Real_Stop_Distance, '0.00') + ' %' : na) + (Show_Stop_Distance ? '\n' + 'StopLoss → ' + str.tostring(Stop_Distance, '0.00') + ' %' : na) + (Show_Order_Amount ? '\n' + 'Position → ' + str.tostring(Position_Size, '#') + ' $' : na) + (Show_Price ? '\n' + 'Price → ' + str.tostring(Stop_Level) : na) : na) + (Avg_Price_True ? '\n\n Average Price' + '\n———————' + (Show_Real_Distance ? '\n' + 'Distance → ' + str.tostring(Real_Avg_Price_Distance, '0.00') + ' %' : na) + (Show_Price ? '\n' + 'Price → ' + str.tostring(Avg_Price) : na) : na) + (Price_3_val_True ? '\n\n Price 3' + '\n———————' + (Show_Order_Amount ? '\n' + 'Order → ' + str.tostring(Order_Three, '# $') : na) + (Show_Real_Distance ? '\n' + 'Distance → ' + str.tostring(Real_Price_3_val_Distance, '0.00') + ' %' : na) + (Show_Price ? '\n' + 'Price → ' + str.tostring(Price_3_val) : na) : na) + (Price_2_val_True ? '\n\n Price 2' + '\n———————' + (Show_Order_Amount ? '\n' + 'Order → ' + str.tostring(Order_Two, '# $') : na) + (Show_Real_Distance ? '\n' + 'Distance → ' + str.tostring(Real_Price_2_val_Distance, '0.00') + ' %' : na) + (Show_Price ? '\n' + 'Price → ' + str.tostring(Price_2_val) : na) : na) + (Price_1_val_True ? '\n\n Price 1' + '\n———————' + (Show_Order_Amount ? '\n' + 'Order → ' + str.tostring(Order_One, '# $') : na) + (Show_Real_Distance ? '\n' + 'Distance → ' + str.tostring(Real_Price_1_val_Distance, '0.00') + ' %' : na) + (Show_Price ? '\n' + 'Price → ' + str.tostring(Price_1_val) : na) + '\n\n\n' +'R:R → ' + str.tostring(TP_Distance / Stop_Distance, '0.00') + '\n' + 'All Position → ' + str.tostring(Position_Size, '#') + ' $' : na)) : na
label.delete(One_Label[1])
// Strategy entries LONG
if strategy.opentrades == 0 and inDateRange and Avg_Price < take_profit_level and Weight_1 != 'NaN' and Price_1_val_True and close[1] > Price_1_val
strategy.entry('Long_Open', strategy.long, qty= quantity(Order_One), limit = Price_1_val, alert_message = Long_message)
if strategy.opentrades == 1 and inDateRange and Avg_Price < take_profit_level and Weight_2 != 'NaN' and Price_2_val_True and close[1] > Price_2_val
strategy.entry('Long_Open', strategy.long, qty= quantity(Order_Two), limit = Price_2_val, alert_message = Long_message)
if strategy.opentrades == 2 and inDateRange and Avg_Price < take_profit_level and Weight_3 != 'NaN' and Price_3_val_True and close[1] > Price_3_val
strategy.entry('Long_Open', strategy.long, qty= quantity(Order_Three), limit = Price_3_val, alert_message = Long_message)
if strategy.opentrades == 3 and inDateRange and Avg_Price < take_profit_level and Weight_4 != 'NaN' and Price_4_val_True and close[1] > Price_4_val
strategy.entry('Long_Open', strategy.long, qty= quantity(Order_Four), limit = Price_4_val, alert_message = Long_message)
// Strategy entries SHORT
if strategy.opentrades == 0 and inDateRange and Avg_Price > take_profit_level and Weight_1 != 'NaN' and Price_1_val_True and close[1] < Price_1_val
strategy.entry('Short_Open', strategy.short, qty= quantity(Order_One), limit = Price_1_val, alert_message = Short_message)
if strategy.opentrades == 1 and inDateRange and Avg_Price > take_profit_level and Weight_2 != 'NaN' and Price_2_val_True and close[1] < Price_2_val
strategy.entry('Short_Open', strategy.short, qty= quantity(Order_Two), limit = Price_2_val, alert_message = Short_message)
if strategy.opentrades == 2 and inDateRange and Avg_Price > take_profit_level and Weight_3 != 'NaN' and Price_3_val_True and close[1] < Price_3_val
strategy.entry('Short_Open', strategy.short, qty= quantity(Order_Three), limit = Price_3_val, alert_message = Short_message)
if strategy.opentrades == 3 and inDateRange and Avg_Price > take_profit_level and Weight_4 != 'NaN' and Price_4_val_True and close[1] < Price_4_val
strategy.entry('Short_Open', strategy.short, qty= quantity(Order_Four), limit = Price_4_val, alert_message = Short_message)
if strategy.opentrades > 0 and inDateRange and strategy.position_size > 0
strategy.exit('Long__Close',from_entry = "Long_Open", stop=Stop_Level, limit = take_profit_level , qty_percent=100, alert_message =Long_Exit_message)
if strategy.opentrades > 0 and inDateRange and strategy.position_size < 0
strategy.exit('Short__Close',from_entry = "Short_Open", stop=Stop_Level, limit = take_profit_level , qty_percent=100, alert_message =Short_Exit_message)
|
Dynamic Stop Loss Demo | https://www.tradingview.com/script/6uNZKDca-Dynamic-Stop-Loss-Demo/ | Tindtily | https://www.tradingview.com/u/Tindtily/ | 131 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Tindtily
//@version=5
strategy("Dynamic Stop Loss Demo",overlay = true,initial_capital = 20000,max_bars_back = 100, pyramiding = 1, default_qty_value = 100, default_qty_type = strategy.percent_of_equity, commission_value=0.04)
// rsi settings
length = input( 14, group="rsi settings" )
overSold = input( 30, group="rsi settings")
overBought = input( 70, group="rsi settings" )
// strategy settings
rr = input.float(1.5,'Profit and loss ratio',step = 0.1, group = 'strategy settings')
atr_times = input.float(2,'ATR times', step = 0.1, group = 'strategy settings')
back_test_length = input.int(14, 'Back test length', group = 'strategy settings')
first_tp_qty = input.int(50, 'First take profit qty percent', group = 'strategy settings')
qty_precision = input.int(2, "qty precision", group = "strategy settings")
highest = ta.highest(high, back_test_length)
lowest = ta.lowest(low, back_test_length)
limit = close
vrsi = ta.rsi(limit, length)
co = ta.crossover(vrsi, overSold)
cu = ta.crossunder(vrsi, overBought)
long_cond = co
short_cond = cu
hasFitFirstProfit = false
curSize = strategy.position_size
curId = strategy.position_entry_name
isShorting = curSize < 0
isLonging = curSize > 0
isOpening = isShorting or isLonging
// enums
LONG = "long"
SHORT = "short"
getStrategyInfoFromId(id)=>
info = str.split(id, "_")
openPrice = float(na)
profitPrice = float(na)
stopPrice = float(na)
entrySize = float(na)
if array.size(info) != 0
openPrice := str.tonumber(array.get(info, 1))
profitPrice := str.tonumber(array.get(info, 3))
stopPrice := str.tonumber(array.get(info, 2))
entrySize := str.tonumber(array.get(info, 4))
[openPrice, profitPrice, stopPrice, entrySize]
getBasicProfit(openPrice, stopPrice) =>
openPrice + (openPrice - stopPrice) * rr
getStrategyId(prefix, openPrice, stopPrice, profitPrice, size) =>
prefix + "_" + str.tostring(openPrice) + "_" + str.tostring(stopPrice) + "_" + str.tostring(profitPrice) + "_" + str.tostring(size)
startStrategy(direction, openPrice, stopPrice, qty, entryComment) =>
prefix = direction
profitPrice = getBasicProfit(openPrice, stopPrice)
id = getStrategyId(prefix, openPrice, stopPrice, profitPrice, qty * (direction == LONG ? 1: -1))
strategy.entry(id, direction == LONG ? strategy.long : strategy.short, comment= entryComment, limit=openPrice, qty = qty)
toOdd(num)=>
2 * math.round(num / 2)
getQty(limit) =>
avaC = strategy.grossprofit - strategy.grossloss + strategy.initial_capital
qtyNum = math.round(avaC / limit, qty_precision)
qtyTimes = math.pow(10, qty_precision)
math.round(toOdd( qtyNum * qtyTimes) / qtyTimes, qty_precision)
decimal(number, precision) =>
numStr = str.tostring(math.round(number, precision + 1))
str.tonumber(str.substring(numStr, 0, str.length(numStr) - 1))
longQty = decimal(getQty(limit) , 2)
shortQty = decimal(getQty(limit) , 2)
calculateDynimacStop()=>
ATR = atr_times * ta.atr(back_test_length)
dynamicLongStop = float(na)
dynamicShortStop = float(na)
if (close > open)
dynamicLongStop := low - ATR
if (isLonging)
dynamicLongStop := math.max(dynamicLongStop, dynamicLongStop[1])
else
dynamicLongStop := dynamicLongStop[1]
if (close < open)
dynamicShortStop := high + ATR
if (isShorting)
dynamicShortStop := math.min(dynamicShortStop, dynamicShortStop[1])
else
dynamicShortStop := dynamicShortStop[1]
[dynamicLongStop, dynamicShortStop]
[dynamicLongStop, dynamicShortStop] = calculateDynimacStop()
[curOpenPrice, curProfitPrice, curStopPrice, curEntrySize] = getStrategyInfoFromId(curId)
hasFitFirstProfit := math.abs(curEntrySize) > math.abs(curSize)
if isLonging == false and isShorting == false
if long_cond and bar_index > back_test_length
long_stop = lowest
long_profit = getBasicProfit(limit, long_stop)
startStrategy(LONG, limit, long_stop, longQty, "entry long")
if short_cond and bar_index > back_test_length
short_stop = highest
short_profit = getBasicProfit(limit, short_stop)
startStrategy(SHORT, limit, short_stop, longQty, "entry short")
else
if isLonging
if hasFitFirstProfit
if low < dynamicLongStop
strategy.close(curId, comment='stop long dynamic')
else if close < curStopPrice
strategy.close(curId, comment='stop long at stop')
else if low < curOpenPrice
strategy.close(curId, comment='stop long at open')
else if short_cond
short_stop = highest
short_profit = getBasicProfit(limit, short_stop)
startStrategy(SHORT, limit, short_stop, shortQty, "entry short")
else
if close < curStopPrice
strategy.close(curId, comment = 'stop long')
if high > curProfitPrice
strategy.close(curId, comment = "take long " + str.tostring(first_tp_qty) + '% profit', qty_percent =first_tp_qty)
if isShorting
if hasFitFirstProfit
if high > dynamicShortStop
strategy.close(curId, comment='stop short dynamic')
else if close > curStopPrice
strategy.close(curId, comment='stop short at stop')
else if high > curOpenPrice
strategy.close(curId, comment='stop short at open')
else if long_cond
long_stop = lowest
long_profit = getBasicProfit(limit, long_stop)
startStrategy(LONG, limit, long_stop, longQty, "entry long")
else
if close > curStopPrice
strategy.close(curId, comment = 'stop short')
if low < curProfitPrice
strategy.close(curId, comment = "take short " + str.tostring(first_tp_qty) + '% profit', qty_percent =first_tp_qty)
// plots
lstop = isLonging ? curStopPrice : na
sStop = isShorting ? curStopPrice: na
lprofit = isLonging ? curProfitPrice :na
sProfit = isShorting ? curProfitPrice : na
lopen = isLonging ? curOpenPrice : na
sopen = isShorting ? curOpenPrice : na
sDStop = dynamicShortStop
lDStop = dynamicLongStop
plot(isOpening?lstop:na, title="long stop color" ,color=color.red,style = plot.style_linebr,linewidth = 1)
plot(isOpening?lprofit:na,title="long profit color",color=color.green,style = plot.style_linebr,linewidth = 1)
plot(isOpening?lopen : na,title="long open color", color = color.silver, style = plot.style_linebr, linewidth = 1)
plot(isLonging and hasFitFirstProfit? lDStop: na,title="long dynamic stop color", color=color.yellow, style = plot.style_linebr, linewidth = 1)
plot(isOpening?sStop:na,title="short stop color" ,color=color.red,style = plot.style_linebr,linewidth = 1)
plot(isOpening?sProfit:na,title="short profit color" ,color=color.green,style = plot.style_linebr,linewidth = 1)
plot(isOpening?sopen : na,title="short open color" , color = color.silver, style = plot.style_linebr, linewidth = 1)
plot(isShorting and hasFitFirstProfit? sDStop:na,title="short dynamic stop color" , color=color.yellow, style = plot.style_linebr, linewidth = 1) |
LowFinder_PyraMider_V2 | https://www.tradingview.com/script/Yfu3aGsY-LowFinder-PyraMider-V2/ | A3Sh | https://www.tradingview.com/u/A3Sh/ | 383 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © A3Sh
//@version=5
// Strategy that finds potential lows in the price action and spreads the risk by entering multiple positions at these lows.
// The low is detected based on the difference between MTF RSI and EMA based RSI, Moving Average and MTF Stochastic indicators.
// The size of each next position that is entered is multiplied by the sequential number of the position.
// Each separate position can exit when a specified take profit is triggered and re-open when detecting a new potential low.
// All positions are closed when the price action crosses over the dynamic blue stop level line.
// Additionally a take profit / trailing stop and a stop loss can be activated to lower the risk.
// This strategy combines open-source code developed by fellow Tradingview community members:
// The Lowfinder code is developed by RafaelZioni
// https://www.tradingview.com/script/GzKq2RVl-Low-finder/
// Both the MTF RSI code and the MTF Stochastic code are adapted from the MTFindicators libary written by Peter_O
// https://www.tradingview.com/script/UUVWSpXR-MTFindicators/
// The Stop Level calculation is inspired by the syminfo-mintick tutorial on Kodify.net
// https://kodify.net/tradingview/info/syminfo-mintick/
strategy("LowFinder_PyraMider",
overlay=true, pyramiding=99,
initial_capital=10000,
default_qty_type=strategy.percent_of_equity,
default_qty_value=10,
commission_type=strategy.commission.percent,
commission_value=0.06,
slippage=1
)
// Backtest Window
start_time = input.time(defval=timestamp("01 April 2021 20:00"), group = "Backtest Window", title="Start Time")
end_time = input.time(defval=timestamp("01 Aug 2030 20:00"), group = "Backtest Window", title="End Time")
window() => time >= start_time and time <= end_time
// Inputs
prec = input.int (4, group = 'Strtaegy Properties', title = 'Precision', minval = 0, maxval = 16, tooltip = "Specifies the number of digits after the floating point of the script's displayed values.")
portfolio_size = input.float (100, group = 'Risk - Portfolio', title = 'Portfolio %', step=1.0) / 100
leverage = input.int (1, group = 'Risk - Portfolio', title = 'Leverage', minval = 1)
q_mode = input.string ('multiply', group = 'Risk - Order Size', title = 'Order Size Mode', options = ['base', 'multiply'], tooltip = 'Base mode: the base quantiy for each sequential order. Multiply mode: each quantity is multiplied by order number')
q_mode_m = input.int (1, group = 'Risk - Order Size', title = 'Order Size Divider (Multiply Mode)', tooltip = 'Divide Multiply by this number to lower the sequential order sizes')
fixed_q = input.bool (false, group = 'Risk - Order Size', title = 'Fixed Order Size', inline = '01', tooltip = 'Use with caution! Overrides all Risk calculations')
amount_q = input.float (1, group = 'Risk - Order Size', title = '. . Base Currency:', inline = '01')
sl_on = input.bool (false, group = 'Risk - Stop Loss', title = 'StopLoss of', inline = '03')
stopLoss = input.float (1.5, group = 'Risk - Stop Loss', title = '', step=0.1, inline = '03') / 100
sl_mode = input.string ('equity', group = 'Risk - Stop Loss', title = '% of', options = ['avg_price', 'equity'], inline = '03')
stop_len = input.int (100, group = 'Risk - Stop Level', title = 'Stop Level Length', tooltip = 'Lookback most recent highest high')
stop_deviation = input.float (0.3, group = 'Risk - Stop Level', title = 'Deviatation % above Stop Level', step=0.1) / 100
cond2_toggle = input.bool (true , group = 'Risk - Take Profit', title = 'Take Profit/Trailing Stop', inline = '04')
tp_all = input.float (1.0, group = 'Risk - Take Profit', title = '..........%', step=0.1, inline = '04') / 100
tp_on = input.bool (true, group = 'Risk - Take Profit', title = 'Exit Crossover Take Profit and .....', inline = '02')
exit_mode = input.string ('stoplevel', group = 'Risk - Take Profit', title = '', options = ['close', 'stoplevel'], inline = '02')
takeProfit = input.float (10.0, group = 'Risk - Take Profit', title = 'Take Profit % per Order', tooltip = 'Each separate order exits when hit', step=0.1)
posCount = input.int (12, group = 'Pyramiding Settings', title = 'Max Number of Orders')
next_entry = input.float (0.2, group = 'Pyramiding Settings', title = 'Next Order % below Avg. Price', step=0.1)
oa_lookback = input.int (0, group = 'Pyramiding Settings', title = 'Next Order after X candles', tooltip = 'Prevents opening too much orders in a Row')
len_rsi = input.int (5, group = 'MTF LowFinder Settings', title = 'Lookback of RSI')
mtf_rsi = input.int (1, group = 'MTF LowFinder Settings', title = 'Higher TimeFrame Multiplier RSI', tooltip='Multiplies the current timeframe by specified value')
ma_length = input.int (26, group = 'MTF LowFinder Settings', title = 'MA Length / Sensitivity')
new_entry = input.float (0.1, group = 'MTF LowFinder Settings', title = 'First Order % below Low',step=0.1, tooltip = 'Open % lower then the found low')/100
ma_signal = input.int (100, group = 'Moving Average Filter', title = 'Moving Average Length')
periodK = input.int (14, group = 'MTF Stochastic Filter', title = 'K', minval=1)
periodD = input.int (3, group = 'MTF Stochastic Filter', title = 'D', minval=1)
smoothK = input.int (3, group = 'MTF Stochastic Filter', title = 'Smooth', minval=1)
lower = input.int (30, group = 'MTF Stochastic Filter', title = 'MTF Stoch Filter (above gets filtered)')
mtf_stoch = input.int (10, group = 'MTF Stochastic Filter', title = 'Higher TimeFrame Multiplier', tooltip='Multiplies the current timeframe by specified value')
avg_on = input.bool (true, group = 'Plots', title = 'Plot Average Price')
plot_ma = input.bool (false, group = 'Plots', title = 'Plot Moving Average')
plot_ts = input.bool (false, group = 'Plots', title = 'Plot Trailing Stop Level')
// variables //
var entry_price = 0.0 // The entry price of the first entry
var iq = 0.0 // Inititial order quantity before risk calculation
var nq = 0.0 // Updated new quantity after the loop
var oq = 0.0 // Old quantity at the beginning or the loop
var q = 0.0 // Final calculated quantity used as base order size
var int order_after = 0 // Candle counter. Prevent opening too much orders in a row
// Order size calaculations //
// Order size based on max amount of pyramiding orders or fixed by user input ///
// Order size calculation based on 'base' mode or ' multiply' mode //
if fixed_q
q := amount_q
else if q_mode == 'multiply'
iq := (math.abs(strategy.equity * portfolio_size / posCount) / open) * leverage
oq := iq
for i = 0 to posCount
nq := oq + (iq * ( i/ q_mode_m + 1))
oq := nq
q := (iq * posCount / oq) * iq
else
q := (math.abs(strategy.equity * portfolio_size / posCount) / open) * leverage
// Function to calcaulate final order size based on order size modes and round the result with 1 decimal //
quantity_mode(index,string q_mode) =>
q_mode == 'base' ? math.round(q,prec) : q_mode == 'multiply' ? math.round(q * (index/q_mode_m + 1),prec) : na
// LowFinder Calculations //
// MTF RSI by Peter_O //
rsi_mtf(float source, simple int mtf,simple int len) =>
change_mtf=source-source[mtf]
up_mtf = ta.rma(math.max(change_mtf, 0), len*mtf)
down_mtf = ta.rma(-math.min(change_mtf, 0), len*mtf)
rsi_mtf = down_mtf == 0 ? 100 : up_mtf == 0 ? 0 : 100 - (100 / (1 + up_mtf / down_mtf))
// Lowfinder by RafaelZioni //
vrsi = rsi_mtf(close,mtf_rsi,len_rsi)
pp=ta.ema(vrsi,ma_length)
dd=(vrsi-pp)*5
cc=(vrsi+dd+pp)/2
lows=ta.crossover(cc,0)
// MTF Stoch Calcualation // MTF Stoch adapted from Peter_O //
stoch_mtfK(source, mtf, len) =>
k = ta.sma(ta.stoch(source, high, low, periodK * mtf), smoothK * mtf)
stoch_mtfD(source, mtf, len) =>
k = ta.sma(ta.stoch(source, high, low, periodK * mtf), smoothK * mtf)
d = ta.sma(k, periodD * mtf)
mtfK = stoch_mtfK(close, mtf_stoch, periodK)
mtfD = stoch_mtfD(close, mtf_stoch, periodK)
// Open next position % below average position price //
below_avg = close < (strategy.position_avg_price * (1 - (next_entry / 100)))
// Moving Average Filter //
moving_average_signal = ta.sma(close, ma_signal)
plot (plot_ma ? moving_average_signal : na, title = 'Moving Average', color = color.rgb(154, 255, 72))
// Buy Signal //
buy_signal = lows and close < moving_average_signal and mtfK < lower
// First Entry % Below lows //
if buy_signal
entry_price := close * (1 - new_entry)
// Plot Average Price of Position//
plot (avg_on ? strategy.position_avg_price : na, title = 'Average Price', style = plot.style_linebr, color = color.new(color.white,0), linewidth = 1)
// Take profit per Open Order //
take_profit_price = close * takeProfit / 100 / syminfo.mintick
// Calculate different Stop Level conditions to exit All //
// Stop Level Caculation //
stop_long1_level = ta.highest (high, stop_len)[1] * (1 + stop_deviation)
stop_long2_level = ta.highest (high, stop_len)[2] * (1 + stop_deviation)
stop_long3_level = ta.highest (high, stop_len)[3] * (1 + stop_deviation)
stop_long4_level = ta.highest (high, stop_len)[1] * (1 - 0.008)
// Stop triggers //
stop_long1 = ta.crossover(close,stop_long1_level)
stop_long2 = ta.crossover(close,stop_long2_level)
stop_long4 = ta.crossunder(close,stop_long4_level)
// Exit Conditions, cond 1 only Stop Level, cond2 Trailing Stop option //
exit_condition_1 = close < strategy.position_avg_price ? stop_long1 : close > strategy.position_avg_price ? stop_long2 : na
exit_condition_2 = close < strategy.position_avg_price * (1 + tp_all) ? stop_long2 :
close > strategy.position_avg_price * (1 + tp_all) ? stop_long4 :
close < strategy.position_avg_price ? stop_long1 : na
// Switch between conditions //
exit_conditions = cond2_toggle ? exit_condition_2 : exit_condition_1
// Exit when take profit //
ex_m = exit_mode == 'close' ? close : stop_long2_level
tp_exit = ta.crossover(ex_m, strategy.position_avg_price * (1 + tp_all)) and close > strategy.position_avg_price * 1.002
// Plot stoplevel, take profit level //
plot_stop_level = strategy.position_size > 0 ? stop_long2_level : na
plot_trailing_stop = cond2_toggle and plot_ts and strategy.position_size > 0 and stop_long4_level > strategy.position_avg_price * (1 + tp_all) ? stop_long4_level : na
plot(plot_stop_level, title = 'Stop Level', style=plot.style_linebr, color = color.new(#41e3ff, 0), linewidth = 1)
plot(plot_trailing_stop, title = 'Trailing Stop', style=plot.style_linebr, color = color.new(#4cfca4, 0), linewidth = 1)
plot_tp_level = cond2_toggle and strategy.position_size > 0 ? strategy.position_avg_price * (1 + tp_all) : na
plot(plot_tp_level, title = 'Take Profit Level', style=plot.style_linebr, color = color.new(#ff41df, 0), linewidth = 1)
// Calculate Stop Loss based on equity and average price //
loss_equity = ((strategy.position_size * strategy.position_avg_price) - (strategy.equity * stopLoss)) / strategy.position_size
loss_avg_price = strategy.position_avg_price * (1 - stopLoss)
stop_loss = sl_mode == 'avg_price' ? loss_avg_price : loss_equity
plot(strategy.position_size > 0 and sl_on ? stop_loss : na, title = 'Stop Loss', color=color.new(color.red,0),style=plot.style_linebr, linewidth = 1)
// Counter to prevent opening too much orders in a row. //
if strategy.position_size > 0
order_after := order_after + 1
// Enter first position //
if ta.crossunder(close,entry_price) and window() and strategy.position_size == 0
strategy.entry('L_1', strategy.long, qty = math.round(q,prec), comment = '+' + str.tostring(math.round(q,prec)))
// Enter Next Pyramiding Orders //
if buy_signal and window() and strategy.position_size > 0 and below_avg
for i = 1 to strategy.opentrades
entry_comment = '+' + str.tostring((quantity_mode(i,q_mode))) // Comment with variable //
if strategy.opentrades == i and i < posCount and order_after > oa_lookback
entry_price := close
entry_id = 'L_' + str.tostring(i + 1)
strategy.entry(id = entry_id, direction=strategy.long, limit=entry_price, qty= quantity_mode(i,q_mode), comment = entry_comment)
order_after := 0 // Reset counter to prevent opening to much orders in a row.
// Exit per Order //
if strategy.opentrades > 0 and window()
for i = 0 to strategy.opentrades
exit_comment = '-' + str.tostring(strategy.opentrades.size(i))
exit_from = 'L_' + str.tostring(i + 1)
exit_id = 'Exit_' + str.tostring(i + 1)
strategy.exit(id= exit_id, from_entry= exit_from, profit = take_profit_price, comment = exit_comment)
// Exit All //
if exit_conditions or (tp_exit and tp_on and cond2_toggle) and window()
strategy.close_all('Exit All')
entry_price := 0
if ta.crossunder(close,stop_loss) and sl_on and window()
strategy.close_all('StopLoss')
entry_price := 0
|
Soheil PKO's 5 min Hitman Scalp - 3MA + Laguerre RSI + ADX [Pt] | https://www.tradingview.com/script/6Uf1wNAR-Soheil-PKO-s-5-min-Hitman-Scalp-3MA-Laguerre-RSI-ADX-Pt/ | PtGambler | https://www.tradingview.com/u/PtGambler/ | 346 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PtGambler
//@version=5
strategy("3MA + Laguerre RSI + ADX [Pt]", shorttitle = "3MA+LaRSI+ADX[Pt]", overlay=true, initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, calc_on_order_fills = false, max_bars_back = 500)
// ********************************** Trade Period / Strategy Setting **************************************
startY = input(title='Start Year', defval=2011, group = "Backtesting window")
startM = input.int(title='Start Month', defval=1, minval=1, maxval=12, group = "Backtesting window")
startD = input.int(title='Start Day', defval=1, minval=1, maxval=31, group = "Backtesting window")
finishY = input(title='Finish Year', defval=2050, group = "Backtesting window")
finishM = input.int(title='Finish Month', defval=12, minval=1, maxval=12, group = "Backtesting window")
finishD = input.int(title='Finish Day', defval=31, minval=1, maxval=31, group = "Backtesting window")
timestart = timestamp(startY, startM, startD, 00, 00)
timefinish = timestamp(finishY, finishM, finishD, 23, 59)
use_entry_sess = input.bool(false, 'Use Entry Session Window', group = "Trading Session")
t1_session = input.session("0930-1555:23456", "Entry Session", group="Trading Session", tooltip = "Entry Signal only generated within this period.")
t1 = time(timeframe.period, t1_session)
window = time >= timestart and time <= timefinish and t1 ? true : false
margin_req = input.float(1, title="Margin Requirement / Leverage", step=0.1, group = "Trading Options")
qty_per_trade = input.float(100, title = "% of initial capital per trade", group = "Trading Options")
reinvest = input.bool(defval=false,title="Reinvest profit", group = "Trading Options")
reinvest_percent = input.float(defval=100, title = "Reinvest percentage", group="Trading Options")
close_eod = input.bool(false, "All trades will close at the close of trading window", group = "Trading Options")
close_b4_open = input.bool(false, "Position must hit either SL/PT before entering new trade", group = "Trading Options")
profit = strategy.netprofit
float trade_amount = math.floor(strategy.initial_capital*margin_req / close)
if strategy.netprofit > 0 and reinvest
trade_amount := math.floor((strategy.initial_capital* (qty_per_trade/100)+(profit*reinvest_percent*0.01))*margin_req/ close)
else
trade_amount := math.floor(strategy.initial_capital* (qty_per_trade/100)*margin_req / close)
// ******************************************************************************************
group_ma = "Moving Average Ribbon"
group_larsi = "Laguerre RSI"
group_adx = "ADX"
group_SL = "Stop Loss / Profit Target"
// ----------------------------------------- MA Ribbon -------------------------------------
ema1_len = input.int(16, "Fast EMA Length", group = group_ma)
ema2_len = input.int(48, "Slow EMA Length ", group = group_ma)
sma1_len = input.int(200, "Slow SMA Length", group = group_ma)
ema1 = ta.ema(close, ema1_len)
ema2 = ta.ema(close, ema2_len)
sma1 = ta.sma(close, sma1_len)
plot(ema1, "EMA 1", color.white, linewidth = 2)
plot(ema2, "EMA 2", color.yellow, linewidth = 2)
plot(sma1, "SMA 1", color.purple, linewidth = 2)
ma_bull = ema1 > ema2 and ema2 > sma1
ma_bear = ema1 < ema2 and ema2 < sma1
// ------------------------------------------ Laguerre RSI ---------------------------------------
alpha = input.float(0.2, title='Alpha', minval=0, maxval=1, step=0.1, group = group_larsi)
long_thres = input.int(80, 'Long entry above this threshold', minval = 1, maxval = 99, group = group_larsi)
short_thres = input.int(20, 'Short entry below this threshold', minval = 1, maxval = 99, group = group_larsi)
gamma = 1 - alpha
L0 = 0.0
L0 := (1 - gamma) * close + gamma * nz(L0[1])
L1 = 0.0
L1 := -gamma * L0 + nz(L0[1]) + gamma * nz(L1[1])
L2 = 0.0
L2 := -gamma * L1 + nz(L1[1]) + gamma * nz(L2[1])
L3 = 0.0
L3 := -gamma * L2 + nz(L2[1]) + gamma * nz(L3[1])
cu = (L0 > L1 ? L0 - L1 : 0) + (L1 > L2 ? L1 - L2 : 0) + (L2 > L3 ? L2 - L3 : 0)
cd = (L0 < L1 ? L1 - L0 : 0) + (L1 < L2 ? L2 - L1 : 0) + (L2 < L3 ? L3 - L2 : 0)
temp = cu + cd == 0 ? -1 : cu + cd
LaRSI = temp == -1 ? 0 : cu / temp
LaRSI := LaRSI * 100
bull_LaRSI = LaRSI > long_thres
bear_LaRSI = LaRSI < short_thres
// --------------------------------------- ADX ------------------------
adxlen = input(14, title="ADX Smoothing", group = group_adx)
dilen = input(14, title="DI Length", group = group_adx)
dirmov(len) =>
up = ta.change(high)
down = -ta.change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
truerange = ta.rma(ta.tr, len)
plus = fixnan(100 * ta.rma(plusDM, len) / truerange)
minus = fixnan(100 * ta.rma(minusDM, len) / truerange)
[plus, minus]
adx(dilen, adxlen) =>
[plus, minus] = dirmov(dilen)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen)
sig = adx(dilen, adxlen)
active_adx = sig > 20 //and sig > sig[1]
// ******************************* Profit Target / Stop Loss *********************************************
use_SLPT = input.bool(false, 'Use Fixed SL / PT', group = group_SL)
SL = input.float(50, 'Stop loss in ticks', step = 1, group = group_SL) * syminfo.mintick
PT = input.float(100, "Profit target in ticks", step = 1, group = group_SL) * syminfo.mintick
limit_entry = input.bool(false, "Limit same direction entry to 1 per trigger", group = group_SL, tooltip = 'Applicable to using fixed SL/PT only. Reset on fast/slow EMA crossovers')
var L_PT = 0.0
var S_PT = 0.0
var L_SL = 0.0
var S_SL = 0.0
if strategy.position_size > 0
L_SL := L_SL[1]
L_PT := L_PT[1]
else if strategy.position_size < 0
S_SL := S_SL[1]
S_PT := S_PT[1]
else
L_SL := close - SL
L_PT := close + PT
S_SL := close + SL
S_PT := close - PT
entry_line = plot(use_SLPT and strategy.position_size != 0 ? strategy.opentrades.entry_price(0) : na, "Entry Price", color.white, linewidth = 1, style = plot.style_linebr)
L_PT_line = plot(use_SLPT and strategy.position_size > 0 ? L_PT : na, "L PT", color.green, linewidth = 2, style = plot.style_linebr)
S_PT_line = plot(use_SLPT and strategy.position_size < 0 ? S_PT : na, "S PT", color.green, linewidth = 2, style = plot.style_linebr)
L_SL_line = plot(use_SLPT and strategy.position_size > 0 ? L_SL : na, "L SL", color.red, linewidth = 2, style = plot.style_linebr)
S_SL_line = plot(use_SLPT and strategy.position_size < 0 ? S_SL : na, "S SL", color.red, linewidth = 2, style = plot.style_linebr)
fill(L_PT_line, entry_line, color = color.new(color.green,90))
fill(S_PT_line, entry_line, color = color.new(color.green,90))
fill(L_SL_line, entry_line, color = color.new(color.red,90))
fill(S_SL_line, entry_line, color = color.new(color.red,90))
// ---------------------------------- Strategy setup ------------------------------------------------------
var L_entry_trigger = true
var S_entry_trigger = true
L_entry1 = ma_bull and bull_LaRSI and active_adx and (use_SLPT and limit_entry ? L_entry_trigger : true)
S_entry1 = ma_bear and bear_LaRSI and active_adx and (use_SLPT and limit_entry ? S_entry_trigger : true)
L_exit1 = ta.crossunder(ema1, ema2)
S_exit1 = ta.crossover(ema1, ema2)
// Trigger zones
bgcolor(ma_bull ? color.new(color.green ,90) : na)
bgcolor(ma_bear ? color.new(color.red,90) : na)
if L_entry1 and (use_entry_sess ? window : true) and (close_b4_open ? strategy.position_size == 0 : true)
strategy.entry("Long", strategy.long, trade_amount)
L_entry_trigger := false
if S_entry1 and (use_entry_sess ? window : true) and (close_b4_open ? strategy.position_size == 0 : true)
strategy.entry("Short", strategy.short, trade_amount)
S_entry_trigger := false
if use_SLPT
strategy.exit("Exit Long", "Long", limit = L_PT, stop = L_SL, comment_profit = "Exit Long, PT hit", comment_loss = "Exit Long, SL hit")
strategy.exit("Exit Short", "Short", limit = S_PT, stop = S_SL, comment_profit = "Exit Short, PT hit", comment_loss = "Exit Short, SL hit")
else
if L_exit1
strategy.close("Long", comment = "Exit Long")
if S_exit1
strategy.close("Short", comment = "Exit Short")
if use_entry_sess and not window and close_eod
strategy.close_all(comment = "EOD close")
//reset entry trigger
if ta.crossunder(ema1, ema2)
L_entry_trigger := true
if ta.crossover(ema1, ema2)
S_entry_trigger := true |
Fair Value Strategy - ekmll | https://www.tradingview.com/script/Hvzsgn8F/ | ekmll | https://www.tradingview.com/u/ekmll/ | 130 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ©ekmll
//@version=5
strategy("Fair Value Strategy ekmll", overlay=false, initial_capital = 1000000, calc_on_every_tick = true)
fv_index_ticker = input.string("SPX", "Fair Value Index", ["SPX", "NDX", "RUT"])
mode = input.string("Long/Short", "Strategy", ["Short Only", "Long Only", "Long/Short"])
scalar = input.float(1.1, "Scalar", 0.0, 5.0, .1)
subtractor = input.int(1425, "Subtractor", step = 25)
ob_threshold = input.int(0, "OB Threshold", step = 25)
os_threshold = input.int(-175, "OS Threshold", step = 25)
inverse = input.bool(false, "Inverse")
startDate = input.int(title="Start Day", defval=20, minval=1, maxval=31)
startMonth = input.int(title="Start Month", defval=12, minval=1, maxval=12)
startYear = input.int(title="Start Year", defval=2021, minval=1800, maxval=2100)
// See if this bar's time happened on/after start date
afterStartDate = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0))
useCloseDate = input.bool(true, title="Use Close Date")
closeDay = input.int(title="Close Day", defval=20, minval=1, maxval=31)
closeMonth = input.int(title="Close Month", defval=12, minval=1, maxval=12)
closeYear = input.int(title="Close Year", defval=2024, minval=1800, maxval=2100)
// See if this bar's time happened on/after end date
afterEndDate = year == closeYear and month == closeMonth and dayofmonth == closeDay
net_liquidity = request.security("(WALCL - WTREGEN - RRPONTSYD)", "D", close)
plotchar(net_liquidity, "net_liquidity", "", location.top)
index_fair_value = net_liquidity/1000000000/scalar - subtractor
index = request.security(fv_index_ticker, "D", close)
diff = index - index_fair_value
plot(index_fair_value > 0 ? diff : na, title = "Spread", color = color.blue, trackprice = true, linewidth = 2)
hline(0, title='Zero', color=color.gray, linestyle=hline.style_dotted, linewidth=2)
hline(ob_threshold, title='Overbought', color=color.red, linestyle=hline.style_dotted, linewidth=2)
hline(os_threshold, title='Oversold', color=color.green, linestyle=hline.style_dotted, linewidth=2)
overbought_signal = net_liquidity > 0.0 and (diff[1] < ob_threshold and diff[0] > ob_threshold)
oversold_signal = net_liquidity > 0.0 and (diff[1] > os_threshold and diff[0] < os_threshold)
barcolor(overbought_signal ? color.purple : oversold_signal ? color.blue : na)
qty = (strategy.initial_capital + strategy.netprofit + strategy.openprofit)/close
qty_adj = strategy.opentrades > 0 ? math.abs(strategy.opentrades.size(0) * 1) : qty[0]
if (mode == "Long/Short")
if (inverse)
if (overbought_signal and afterStartDate)
strategy.entry("Long", strategy.long, qty = qty[0], comment = "LE")
else if ((afterStartDate and oversold_signal) or (useCloseDate and afterEndDate))
strategy.entry("Short", strategy.short, qty = qty[0], comment = "SE")
else if (useCloseDate and afterEndDate)
strategy.close("Short", qty_percent=100, comment="close")
strategy.close("Long", qty_percent=100, comment="close")
else
if (overbought_signal and afterStartDate)
strategy.entry("Short", strategy.short, qty = qty[0], comment = "SE")
else if (afterStartDate and oversold_signal)
strategy.entry("Long", strategy.long, qty = qty[0], comment = "LE")
else if (useCloseDate and afterEndDate)
strategy.close("Short", qty_percent=100, comment="close")
strategy.close("Long", qty_percent=100, comment="close")
else if (mode == "Short Only")
if (inverse)
if (overbought_signal and afterStartDate)
strategy.entry("Long", strategy.long, qty = qty[0], comment = "LE")
if ((afterStartDate and oversold_signal) or (useCloseDate and afterEndDate))
strategy.close("Long", qty_percent=100, comment="close")
else
if (overbought_signal and afterStartDate)
strategy.entry("Short", strategy.short, qty = qty[0], comment = "SE")
if ((afterStartDate and oversold_signal) or (useCloseDate and afterEndDate))
strategy.close("Short", qty_percent=100, comment="close")
else if (mode == "Long Only")
if (inverse)
if (oversold_signal and afterStartDate)
strategy.entry("Short", strategy.short, qty = qty[0], comment = "SE")
if ((afterStartDate and overbought_signal) or (useCloseDate and afterEndDate))
strategy.close("Short", qty_percent=100, comment="close")
else
if (oversold_signal and afterStartDate)
strategy.entry("Long", strategy.long, qty = qty[0], comment = "LE")
if ((afterStartDate and overbought_signal) or (useCloseDate and afterEndDate))
strategy.close("Long", qty_percent=100, comment="close")
|
I11L - Better Buy Low Volatility or High Volatility? | https://www.tradingview.com/script/3foM9CRj/ | I11L | https://www.tradingview.com/u/I11L/ | 66 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © I11L
//@version=5
strategy("I11L - Better Buy Low Volatility or High Volatility?", overlay=false, pyramiding=1, default_qty_value=1000000, initial_capital=1000000, default_qty_type=strategy.cash,process_orders_on_close=false, calc_on_every_tick=false)
mode = input.string("Buy low Volatility",options = ["Buy low Volatility","Buy high Volatility"])
volatilityTargetRatio = input.float(1,minval = 0, maxval = 100,step=0.1, tooltip="1 equals the average atr for the security, a lower value means that the volatility is lower")
atrLength = input.int(14)
atr = ta.atr(atrLength) / close
avg_atr = ta.sma(atr,atrLength*5)
ratio = atr / avg_atr
sellAfterNBarsLength = input.int(5, step=5, minval=0)
var holdingBarsCounter = 0
if(strategy.opentrades > 0)
holdingBarsCounter := holdingBarsCounter + 1
isBuy = false
if(mode == "Buy low Volatility")
isBuy := ratio < volatilityTargetRatio
else
isBuy := ratio > volatilityTargetRatio
isClose = holdingBarsCounter > sellAfterNBarsLength
if(isBuy)
strategy.entry("Buy",strategy.long)
if(isClose)
holdingBarsCounter := 0
strategy.exit("Close",limit=close)
plot(ratio, color=isBuy[1] ? color.green : isClose[1] ? color.red : color.white)
plot(1, color=color.white)
|
Daily Investments Index Scalp | https://www.tradingview.com/script/MmAESU1T-Daily-Investments-Index-Scalp/ | dailycryptoinvestments | https://www.tradingview.com/u/dailycryptoinvestments/ | 127 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © nedled
//@version=5
strategy("Daily Investments Index Scalp", overlay=true,format=format.price,precision = 2, pyramiding = 0, initial_capital = 1000, default_qty_value = 100, default_qty_type = strategy.percent_of_equity)
var entryPrice = 0
StoplossType = input.string(title="Stoploss Type", defval="SWING", options=["ATR", "SWING", "PERCENTAGE"])
takeProfitType = input.string(title="Take Profit Type", defval="ATR", options=["ATR", "SWING", "PERCENTAGE"])
SwingLenght = input.int(title="Swing Stoploss Lookback Candles",defval = 15)
shortLength = input.int(title="Short Length",defval = 3)
mediumLength = input.int(title="Medium Length", defval=8)
longLength = input.int(title="Long Length", defval=20)
src = input.source(title="source", defval = close)
medium = ta.sma(src,mediumLength)
short = ta.sma(src,shortLength) / medium
long = ta.sma(src,longLength) / medium
ema = input.int(150,title = "Ema Long Lenght")
emaShort = input.int(35,title = "Ema Short Length")
//multi profit
multiplierTP1 = input.float(1.5,"TP - ATR Multiplier")
multiplierTP2 = input.float(3,"TP - ATR Multiplier")
RRTP1 = input.float(1.2,"TP - TP RR")
RRTP2 = input.float(2,"TP - TP RR")
multiplierSL = input.float(1.5,"SL - ATR Multiplier")
emaValue = ta.ema(src,ema)
emaShortValue = ta.ema(src,emaShort)
plot(emaValue, color= color.red)
plot(emaShortValue, color = color.blue)
lengthAtr = input.int(title="ATR Length", defval=14,minval = 1)
smoothingAtr = input.string(title="Smoothing ATR", defval="RMA", options=["RMA", "SMA", "EMA", "WMA"])
src1 = input(high)
src2 = input(low)
ma_function(source, length) =>
if smoothingAtr == "RMA"
ta.rma(source, length)
else
if smoothingAtr == "SMA"
ta.sma(source, length)
else
if smoothingAtr == "EMA"
ta.ema(source, length)
else
ta.wma(source, length)
slShort = 0.0
slLong = 0.0
TP_Short_1 = 0.0
TP_Short_2 = 0.0
TP_Long_1 = 0.0
TP_Long_2 = 0.0
if(StoplossType == "ATR")
slShort := ma_function(ta.tr(true), lengthAtr) * multiplierSL + src1
slLong := src2 - ma_function(ta.tr(true), lengthAtr) * multiplierSL
else if(StoplossType == "SWING")
slShort := ta.highest(high,SwingLenght)
slLong := ta.lowest(low, SwingLenght)
if(takeProfitType == "ATR")
TP_Short_1 := src2 - ma_function(ta.tr(true), lengthAtr) * multiplierTP1
TP_Short_2 := src2 - ma_function(ta.tr(true), lengthAtr) * multiplierTP2
TP_Long_1 := ma_function(ta.tr(true), lengthAtr) * multiplierTP1 + src1
TP_Long_2 := ma_function(ta.tr(true), lengthAtr) * multiplierTP2 + src1
else if(takeProfitType == "SWING")
TP_Short_1 := close - ((ta.highest(high,SwingLenght) - close)* RRTP1)
TP_Short_2 := close - ((ta.highest(high,SwingLenght) - close)* RRTP2)
TP_Long_1 := close + ((close - ta.lowest(low, SwingLenght) ) * RRTP1)
TP_Long_2 := close + ((close - ta.lowest(low, SwingLenght) ) * RRTP2)
bool goLong = false
if(ta.crossover(short,long) and close > emaValue and emaShortValue > emaValue and strategy.position_size <= 0)
goLong := true
strategy.close_all()
strategy.entry("Long", strategy.long, stop = slLong, alert_message = "Entered long position")
strategy.exit("Exit Long TP1", from_entry = "Long", limit = TP_Long_1, qty_percent = 50, stop = slLong)
strategy.exit("Exit Long TP2", from_entry = "Long", limit = TP_Long_2, stop = slLong)
bool goShort = false
if(ta.crossunder(short,long) and close < emaValue and emaShortValue < emaValue and strategy.position_size >= 0)
goShort := true
strategy.close_all()
strategy.entry("Short", strategy.short, stop = slShort, alert_message = "Entered short position")
strategy.exit("Exit Short TP1", from_entry = "Short", limit= TP_Short_1, qty_percent = 50, stop = slShort)
strategy.exit("Exit Short TP2", from_entry = "Short", limit= TP_Short_2, stop = slShort)
long_stop_level = float(na)
long_stop_level := goLong ? slLong : long_stop_level[1]
long_limit1_level = float(na)
long_limit1_level := goLong ? TP_Long_1 : long_limit1_level[1]
long_limit2_level = float(na)
long_limit2_level := goLong ? TP_Long_2 : long_limit2_level[1]
short_stop_level = float(na)
short_stop_level := goShort ? slShort : short_stop_level[1]
short_limit1_level = float(na)
short_limit1_level := goShort ? TP_Short_1 : short_limit1_level[1]
short_limit2_level = float(na)
short_limit2_level := goShort ? TP_Short_2 : short_limit2_level[1]
getCurrentStageLong() =>
var stage = 0
if strategy.position_size == 0
stage := 0
if stage == 0 and strategy.position_size > 0
stage := 1
else if stage == 1 and long_limit1_level[1] < high
stage := 2
stage
getCurrentStageShort() =>
var stage = 0
if strategy.position_size == 0
stage := 0
if stage == 0 and strategy.position_size < 0
stage := 1
else if stage == 1 and short_limit1_level[1] > low
stage := 2
stage
curLongStage = getCurrentStageLong()
if(curLongStage == 2)
strategy.exit("Exit Long TP2", from_entry = "Long", limit = long_limit2_level, stop = strategy.opentrades.entry_price(strategy.opentrades - 1))
curShortStage = getCurrentStageShort()
if(curShortStage == 2)
strategy.exit("Exit Short TP2", from_entry = "Short", limit = short_limit2_level, stop = strategy.opentrades.entry_price(strategy.opentrades - 1))
print(txt) =>
// Create label on the first bar.
var lbl = label.new(bar_index, na, txt, xloc.bar_index, yloc.price, color(na), label.style_none, color.gray, size.large, text.align_left)
// On next bars, update the label's x and y position, and the text it displays.
label.set_xy(lbl, bar_index, ta.highest(10)[1])
label.set_text(lbl, txt)
plot(strategy.position_size > 0 ? long_stop_level : na,title= "SL LONG", color = color.red, style = plot.style_steplinebr)
plot(strategy.position_size > 0 ? long_limit1_level : na,title= "TP1 LONG", color = color.green, style = plot.style_steplinebr)
plot(strategy.position_size > 0 ? long_limit2_level : na,title= "TP2 LONG", color = color.green, style = plot.style_steplinebr)
plot(strategy.position_size < 0 ? short_stop_level : na,title= "SL SHORT", color = color.yellow, style = plot.style_steplinebr)
plot(strategy.position_size < 0 ? short_limit1_level : na,title= "TP1 SHORT", color = color.green, style = plot.style_steplinebr)
plot(strategy.position_size < 0 ? short_limit2_level : na,title= "TP2 SHORT", color = color.green, style = plot.style_steplinebr)
// Table Results
//tableBgcolor=#686868
//if barstate.islastconfirmedhistory
// var tbl = table.new(position.bottom_right, 3, 3, bgcolor = tableBgcolor, frame_width = 2, frame_color = color.black, border_width=2,border_color=color.black)
//table.cell(tbl, 0, 1, "Total Trades: " + str.tostring(strategy.closedtrades), bgcolor=color.gray,text_size=size.small,text_color=color.white,text_valign=text.align_center)
//table.cell(tbl, 0, 2, "Win Rate: " + str.tostring(math.round(strategy.wintrades / strategy.closedtrades * 100,2)) + "%", bgcolor=color.gray,text_size=size.small,text_color=color.white,text_valign=text.align_center)
//table.cell(tbl, 0, 0, "Initial Capital: " + str.tostring(strategy.initial_capital), bgcolor=color.gray,text_size=size.small,text_color=color.white,text_valign=text.align_center)
//table.cell(tbl, 1, 0, "Net Profit: " + str.tostring(math.round(strategy.netprofit,2)) + " ("+ str.tostring(math.round(strategy.netprofit / strategy.initial_capital * 100,2)) + "%"+ ")", bgcolor=strategy.netprofit>0?color.teal:color.maroon,text_size=size.small,text_color=color.white,text_valign=text.align_center)
//table.cell(tbl, 1, 1, "Current equity: "+ str.tostring(math.round(strategy.equity,2))+ "", bgcolor=strategy.netprofit>0?color.teal:color.red,text_size=size.small,text_color=color.white,text_valign=text.align_center)
//table.cell(tbl, 1, 2, "Max DrawDown: "+ str.tostring(math.round(strategy.max_drawdown))+ " ("+ str.tostring(math.round(strategy.max_drawdown/ strategy.initial_capital * 100,2))+ "%"+ ")", bgcolor=color.maroon,text_size=size.small,text_color=color.white,text_valign=text.align_center)
|
Cycle Position Trading | https://www.tradingview.com/script/M7d4TjVm/ | I11L | https://www.tradingview.com/u/I11L/ | 63 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © I11L
//@version=5
strategy("Cycle Position Trading", overlay=true, pyramiding=1, default_qty_value=100000, initial_capital=100000, default_qty_type=strategy.cash, process_orders_on_close=false, calc_on_every_tick=false)
// Input for selecting the mode
mode = input.string("Buy Uptrend", options = ["Buy Uptrend", "Buy Downtrend"])
// Input for customizing stop loss and take profit levels
stopLoss = input.float(0.9, title="Stop Loss (SL) level", step=0.01)
takeProfit = input.float(1.1, title="Take Profit (TP) level", step=0.01)
// Calculate the 200-day Simple Moving Average (SMA)
sma = ta.sma(close, 200)
// Plot the SMA on the chart
plot(sma)
// Define the conditions for entering a long position based on the selected mode
longCondition = mode == "Buy Uptrend" ? close > sma and close[5] > sma : close < sma
// Define the conditions for closing a position based on the selected mode
closeCondition = mode == "Buy Uptrend" ? (strategy.position_avg_price * stopLoss > close or strategy.position_avg_price * takeProfit < close or close < sma * 0.95) : (strategy.position_avg_price * stopLoss > close or strategy.position_avg_price * takeProfit < close or close > sma * 1.05)
// Execute a long position if the longCondition is met
if (longCondition)
strategy.entry("My Long Entry Id", strategy.long)
// Close the position if the closeCondition is met
if (closeCondition)
strategy.exit("Exit", limit = close)
|
Kitchen [ilovealgotrading] | https://www.tradingview.com/script/T2juFbHt-Kitchen-ilovealgotrading/ | projeadam | https://www.tradingview.com/u/projeadam/ | 532 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Baby_whale_to_moon
//@version=5
strategy('Kitchen [ilovealgotrading]', overlay=true, format=format.price, initial_capital = 1000)
// BACKTEST DATE
Start_Time = input.time(defval=timestamp('01 January 2017 13:30 +0000'), title='Start_Time', group = " ################# BACKTEST DATE ################ " )
End_Time = input.time(defval=timestamp('30 April 2024 19:30 +0000'), title='End_Time', group = " ################# BACKTEST DATE ################ " )
// supertrend
atrPeriod = input(10, 'ATR Length', group = " ################# Supertrend ################ ")
factor = input(3, 'Factor', group = " ################# Supertrend ################ ")
time1 = input.string(title='Short Time Period', defval='07 1h', options=['01 1m','02 3m','03 5m', '04 15m', '05 30m', '06 45m', '07 1h', '08 2h', '09 3h', '10 4h', '11 1D', '12 1W' ], group = " ################# Supertrend ################ ",tooltip = "this timeframe is the value of our short-time supertrend indicator")
time2 = input.string(title='Long Time Period', defval='10 4h', options=[ '01 1m','02 3m','03 5m', '04 15m', '05 30m', '06 45m', '07 1h', '08 2h', '09 3h', '10 4h', '11 1D', '12 1W' ], group = " ################# Supertrend ################ ",tooltip = "this timeframe is the value of our long-time supertrend indicator")
res(Resolution) =>
if Resolution == '00 Current'
timeframe.period
else
if Resolution == '01 1m'
'1'
else
if Resolution == '02 3m'
'3'
else
if Resolution == '03 5m'
'5'
else
if Resolution == '04 15m'
'15'
else
if Resolution == '05 30m'
'30'
else
if Resolution == '06 45m'
'45'
else
if Resolution == '07 1h'
'60'
else
if Resolution == '08 2h'
'120'
else
if Resolution == '09 3h'
'180'
else
if Resolution == '10 4h'
'240'
else
if Resolution == '11 1D'
'1D'
else
if Resolution == '12 1W'
'1W'
else
if Resolution == '13 1M'
'1M'
// supertrend Long time period
[supertrend2, direction2] = request.security(syminfo.tickerid, res(time2), ta.supertrend(factor, atrPeriod))
bodyMiddle4 = plot((open + close) / 2, display=display.none)
upTrend2 = plot(direction2 < 0 ? supertrend2 : na, 'Up Trend', color=color.new(color.green, 0), style=plot.style_linebr, linewidth=2)
downTrend2 = plot(direction2 < 0 ? na : supertrend2, 'Down Trend', color=color.new(color.red, 0), style=plot.style_linebr, linewidth=2)
// supertrend short time period
[supertrend1, direction1] = request.security(syminfo.tickerid, res(time1), ta.supertrend(factor, atrPeriod))
bodyMiddle = plot((open + close) / 2, display=display.none)
upTrend = plot(direction1 < 0 ? supertrend1 : na, 'Up Trend', color=color.new(color.yellow, 0), style=plot.style_linebr)
downTrend = plot(direction1 < 0 ? na : supertrend1, 'Down Trend', color=color.new(color.orange, 0), style=plot.style_linebr)
// Stochastic RSI
low_limit_stoch_rsi = input.float(title = 'Stoch Rsi Low Limit', step=0.5, defval=15, group = " ################# Stoch RSI ################ ", tooltip = "when Stock rsi value crossover Low Limit value we get Long")
up_limit_stoch_rsi = input.float(title = 'Stoch Rsi Up Limit', step=0.5, defval=85, group = " ################# Stoch RSI ################ ", tooltip = "when Stock rsi value crossunder Up Limit value we get Short")
stocrsi_back_length = input.int(20, 'Stoch Rsi retroactive length', minval=1, group = " ################# Stoch RSI ################ ", tooltip = "How many candles are left behind, even if there is a buy or sell signal, it will be valid now")
smoothK = input.int(3, 'Stochastic RSI K', minval=1, group = " ################# Stoch RSI ################ ")
lengthRSI = input.int(14, 'RSI Length', minval=1, group = " ################# Stoch RSI ################ ")
lengthStoch = input.int(14, 'Stochastic Length', minval=1, group = " ################# Stoch RSI ################ ")
src_rsi = input(close, title='RSI Source', group = " ################# Stoch RSI ################ ")
rsi1 = request.security(syminfo.tickerid, '240', ta.rsi(src_rsi, lengthRSI))
k = request.security(syminfo.tickerid, '240', ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK))
// Strategy settings
dollar = input.float(title='Dollar Cost Per Position ', defval=1000, group = " ################# Strategy Settings ################ ")
trade_direction = input.string(title='Trade_direction', group = " ################# Strategy Settings ################ ", options=['LONG', 'SHORT', 'BOTH'], defval='BOTH')
Long_message_open = input('Long Open', title = "Long Open Message", group = " ################# Strategy Settings ################ ", tooltip = "if you write your alert window this code {{strategy.order.alert_message}} .When trigger Long signal you will get dynamically what you pasted here for Long Open Message ")
Short_message_open = input('Short Open', title = "Short Open Message", group = " ################# Strategy Settings ################ ", tooltip = "if you write your alert window this code {{strategy.order.alert_message}} .When trigger Long signal you will get dynamically what you pasted here for Short Open Message ")
Long_message_close = input('Long Close', title = "Long Close Message", group = " ################# Strategy Settings ################ ", tooltip = "if you write your alert window this code {{strategy.order.alert_message}} .When trigger Long signal you will get dynamically what you pasted here for Long Close Message ")
Short_message_close = input('Short Close', title = "Short Close Message", group = " ################# Strategy Settings ################ ", tooltip = "if you write your alert window this code {{strategy.order.alert_message}} .When trigger Long signal you will get dynamically what you pasted here for Short Close Message ")
Time_interval = time > Start_Time and time < End_Time
bgcolor(Time_interval ? color.rgb(255, 235, 59, 95) : na)
back_long = 0
back_short = 0
for i = 1 to stocrsi_back_length by 1
if ta.crossover(k, low_limit_stoch_rsi)[i] == true
back_long += i
back_long
if ta.crossunder(k, up_limit_stoch_rsi)[i] == true
back_short += i
back_short
// bgcolor(back_long>0?color.rgb(153, 246, 164, 54):na)
// bgcolor(back_short>0?color.rgb(246, 153, 153, 54):na)
buy_signal = false
sell_signal = false
if direction2 < 0 and direction1 < 0 and back_long > 0
buy_signal := true
buy_signal
if direction2 > 0 and direction1 > 0 and back_short > 0
sell_signal := true
sell_signal
//bgcolor(buy_signal ? color.new(color.lime,90) : na ,title="BUY bgcolor")
plotshape( buy_signal[1] == false and strategy.opentrades == 0 and Time_interval and buy_signal ? supertrend2 : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white)
//bgcolor(sell_signal ? color.new(color.red,90) : na ,title="SELL bgcolor")
plotshape(sell_signal[1] == false and strategy.opentrades == 0 and Time_interval and sell_signal ? supertrend2 : na , title="Sell", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.white)
// Strategy entries
if strategy.opentrades == 0 and Time_interval and buy_signal and ( trade_direction == 'LONG' or trade_direction == 'BOTH')
strategy.entry('Long_Open', strategy.long, qty=dollar / close, alert_message=Long_message_open)
if strategy.opentrades == 0 and Time_interval and sell_signal and ( trade_direction == 'SHORT' or trade_direction == 'BOTH')
strategy.entry('Short_Open', strategy.short, qty=dollar / close, alert_message=Short_message_open)
// Strategy Close
if close < supertrend1 and strategy.position_size > 0
strategy.exit('Long_Close',from_entry = "Long_Open", stop=close, qty_percent=100, alert_message=Long_message_close)
if close > supertrend1 and strategy.position_size < 0
strategy.exit('Short_Close',from_entry = "Short_Open", stop=close, qty_percent=100, alert_message=Short_message_close)
|
Mean Reversion and Trendfollowing | https://www.tradingview.com/script/LraBV2zv/ | I11L | https://www.tradingview.com/u/I11L/ | 102 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © I11L
//@version=5
strategy("Mean Reversion and Trendfollowing", overlay=true, pyramiding=1, default_qty_value=100000, initial_capital=100000, default_qty_type=strategy.cash, process_orders_on_close=false, calc_on_every_tick=false)
// Input for the starting date
start_date = input.time(timestamp("1 Feb 2000 12:00"), title="Starting Date")
enableMeanReversion = input.bool(true)
enableTrendfollowing = input.bool(true)
trendPositionFactor = input.float(1)
meanReversionPositionFactor = input.float(0.5)
// Convert the input string to a timestamp
start_ts = timestamp(year(start_date), month(start_date), dayofmonth(start_date), 0, 0)
// Check if the current bar's time is greater than or equal to the start timestamp
start_condition = time >= start_ts
var tradeOrigin = ""
sma200 = ta.sma(close,200)
rsi2 = ta.rsi(close,2)
isMeanReversionMode = close < sma200 or not(enableTrendfollowing)
isTrendfollowingMode = close > sma200 or not(enableMeanReversion)
isRsiBuy = rsi2 < 20 and enableMeanReversion
isRsiClose = rsi2 > 80 and enableMeanReversion
isSmaBuy = close > sma200 and enableTrendfollowing
isSmaClose = close < sma200 * 0.95 and enableTrendfollowing
isBuy = (isMeanReversionMode and isRsiBuy) or (isTrendfollowingMode and isSmaBuy)
positionSizeFactor = isSmaBuy ? trendPositionFactor : meanReversionPositionFactor
// Only execute the strategy after the starting date
if (start_condition)
if (isBuy and strategy.opentrades == 0)
tradeOrigin := isSmaBuy ? "SMA" : "RSI"
strategy.entry("My Long Entry Id", strategy.long, qty=(strategy.equity / close) * positionSizeFactor, comment=str.tostring(positionSizeFactor))
isClose = tradeOrigin == "SMA" ? isSmaClose : isRsiClose
if (isClose)
strategy.exit("Exit", limit = close)
plot(sma200)
plot(sma200 * 0.95, color=color.orange) |
X48 - Strategy | BreakOut & Consecutive (11in1) + Alert | V.1.2 | https://www.tradingview.com/script/nt3wgHEc-X48-Strategy-BreakOut-Consecutive-11in1-Alert-V-1-2/ | X4815162342 | https://www.tradingview.com/u/X4815162342/ | 553 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © X4815162342
//================== Read This First Before Use This Strategy ==============
// *********** Please be aware that this strategy is not a guarantee of success and may lead to losses.
// *********** Trading involves risk and you should always do your own research before making any decisions.
// ================= Thanks Source Script and Explain This Strategy ===================
// This Strategy Are Combine [5] Strategy and [8] Indicators [1] Alert Function For Systematric Trading User.
// [3] Strategy List, Thanks For Original Source Script [1],[2] From Tradingview Build-in Script [3] From fmzquant Github
// [3.1] Channel BreakOut Strategy : Calculate BreakOut Zone For Buy and Sell.
// [3.2] Consecutive Bars UP/Down Strategy : The consecutive bars up/down strategy is a trading strategy used to identify potential buy and sell signals in the stock market. This strategy involves looking for a series of bars (or candles) that are either all increasing or all decreasing in price. If the bars are all increasing, it can be a signal to buy, and if the bars are all decreasing, it can be a signal to sell. This strategy can be used on any timeframe, from a daily chart to an intraday chart.
// [3.3] 15m Range Length SD : Range Of High and Low Candle Price and Lookback For Calculate Buy and Sell.
// [3.4] MA Type CrossOver and CrossUnder
// [3.5] MACD CrossOver and CrossUnder
// [8] Indicators Are Simple Source Script (Almost I'm Chating With CHAT-GPT and Convert pinescript V4 to V5 again for complete almost script and combine after)
// [8.1] SwingHigh and SwingLow Plot For SL (StopLoss by Last Swing).
// [8.2] Engulfing and 3 Candle Engulfing Plot.
// [8.3] Stochastic RSI for Plot and Fill Background Paint and Plot TEXT For BULL and BEAR TREND.
// [8.4] MA TYPE MODE are plot 2 line of MA Type (EMA, SMA, HMA, WMA, VWMA) for Crossover and Crossunder.
// [8.5] Donchian Fans MODE are Plot Dot Line With Triangle Degree Bull Trend is Green Plot and Bear Trend is Red Plot.
// [8.6] Ichimoku Cloud Are Plot Cloud A-B For Bull and Bear Trend.
// [8.7] RSI OB and OS for TEXT PLOT 'OB' , 'OS' you will know after OB and OS, you can combo with other indicators that's make you know what's the similar trend look like?
// [8.8] MACD for Plot Diamond when MACD > 0 and MACD < 0, you can combo with other indicators that's make you know what's the similar trend look like?
// [1] Alert Can Alert Sent When Buy and Sell or TP and SL, you can adjust text to alert sent by your self or use default setting.
// ========== Let'e Me Explain How To Use This Strategy =============
// ========== Properties Setting ==========
// Capital : Default : 500 USDT For Alot Of People Are Beginner Investor = It's Capital Your Cash For Invertment
// Ordersize : Default Are Setting 5% / Order [It's Mean 5% From 1,000] We Call Compounded
// ========== INPUT Setting ==========
// First Part Use Must Choose Checkbox For Use [1] of [3] Strategy and Choose TP/SL by Swing or % (can chosoe both)
// In Detail Of Setting Are Not Too Much, Please Read The Header Of Setting Before Change The Value
// For The Indicator In List You Want To Add Just Check ✅ From MODE Setting, It's Show On Your Chart
// You Can Custom TP/SL % You Want
// ========== ##### No trading strategy is guaranteed to be 100% successful. ###### =========
// For Example In My Systematic Trading
// Select 1/3 Strategy Setting TP/SL % Match With Timeframe TP Long Are Not Set It's Can 161.8 - 423.6% but Short Position Are Not Than 100% Just Fine From Your Aset
// Choose Indicators For Make Sure Trend and Strategy are the same way like Strategy are Long Position but MACD and Sto background is bear. that's mean this time not open position.
// Donchian Fans is Simple Support and Ressistant If You Don't Know How To Plot That's, This indicator plot a simple for you ><.
// Make Sure With Engulfing and 3 Candle Engulfing If You Don't Know, What's The Engulfing, This Indicator are plot for you too ><.
// For a Big Trend You can use Ichimoku Cloud For Check Trend, Candle Upper Than Cloud or Lower Than Cloud for Bull and Bear Trend.
/////////notes////////////////////////////////////////
// This is based on the ATR trailing stop indicator //
// width addition of two levels of stops and //
// different interpretation. //
// This is a fast-reacting system and is better //
// suited for higher volatility markets //
//////////////////////////////////////////////////////
// ========== Confirm Setting ==========
// 1. Confirm by MACD > 0 and < 0
// 2. Confirm by Stochastic RSI Cross
// 3. Confirm by MA Type Fast > Slow or <
// 4. Confirm by Ichimoku Tenkan > Kijun or <
// ========== TP/SL Setting ==========
// 1. By Swing High / Low
// 2. By ATR Trailing Stop
// 3. By Callback [%] From Last H/L
// 4. By FIX [%] TP/SL
// For Forex Setting (For Free Swap And Commission 0 Only)
// Capital = 50$
// Order Size = 1 Contract
// Commission = 0
// Slippage = Average Your Spread Broker
// TP = 0.0055% - 0.0057% (For Forex Use Lot For Easy TP by PNL 7-11 pip)
// For Cryptocurrency Setting
// Capital = 100$
// Order Size = 16.333 USDT
// Commission = 0.1 or 0.04
//@version=5
strategy("X48 - Strategy | Channel BreakOut & Consecutive (17in1) + TL/TP/SL | V.2.13", overlay=true, calc_on_order_fills = true, initial_capital = 50, default_qty_type = strategy.cash, default_qty_value = 16.333, commission_type = strategy.commission.percent, commission_value = 0.1, currency = currency.USDT, calc_on_every_tick = true)
//================ SPOT MODE ==============
GRSPT = "=== 🍀🍀🍀 SPOT MODE 🍀🍀🍀 ==="
Spot_MODE = input.bool(defval = false, title = "🍀 SPOT MODE", group = GRSPT)
//================ CHANNEL BREAKOUT SETTING ===============
GRS = "==1️⃣2️⃣3️⃣4️⃣5️⃣ SELECT [X] STRATEGY + TAKE PROFIT & STOP LOSS ? + CONFIRM MODE ? 5️⃣4️⃣3️⃣2️⃣1️⃣=="
GR1 = "===== 1️⃣1️⃣1️⃣ CHANNEL BREAKOUT STRATEGY 1️⃣1️⃣1️⃣====="
BreakOut_MODE = input.bool(defval = true, title = "1️⃣ CHANNEL BREAKOUT MODE", group = GRS, inline = "MainHEAD", tooltip = "Use Channel BreakOut Strategy")
GRCON = "=====🅰️🅱️ CONFIRM MODE 🅱️🅰️====="
MACDConfirm_MODE = input.bool(defval = false, title = "🅰️ MACD CONFIRM MODE", group = GRCON, tooltip = "Use MACD For Confirm Signal")
//StoConfirm_MODE = input.bool(defval = false, title = "🅱️ STOCHASTIC CONFIRM MODE", group = GRCON, tooltip = "Use Stochastic For Confirm Signal")
RSIConfirm_MODE = input.bool(defval = false, title = "🉐 RSI CONFIRM MODE", group = GRCON, tooltip = "Use Stochastic For Confirm Signal")
MACross_MODE = input.bool(defval = false, title = "💯 MA CROSS X CONFIRM MODE", group = GRCON, tooltip = "Use MA Type Cross For Confirm Signal")
IchiConfirm_MODE = input.bool(defval = false, title = "💮 ICHIMOKU TENKAN&KIJUN CROSS X CONFIRM MODE", group = GRCON, tooltip = "Use Ichimoku Tenkan & Kijun Cross For Confirm Signal")
GRSUB = "=====🆎🆑🅾️🆘 TP & SL SELECT MODE 🆘🅾️🆑🆎====="
Swing_STOP = input.bool(title="🆎 STOP LOSS BY SWING MODE", defval=false, group = GRSUB, tooltip = 'If Mode On = Use Stop Loss By Last Swing', inline = "SubMAIN")
plotcolor = input.bool(defval = false, title = '🆑 ATR Trailing Stop', group = GRSUB)
BOTrail_MODE = input.bool(defval = false, title = "🅾️ CALLBACK Trailing Stop [Low Profit But More TP]", group = GRSUB, tooltip = "BreakOut Length For Who's Want Fast Trailing But This Low Profit But More Time For TP\nIt's Can Combo With Breakout and 15m")
BungToon_Mode = input.bool(defval = false, title = "🅾️ Entry Cover Mode", group = GRSUB, tooltip = "Stop Buy and Sell Cover Your Loss With Entry Price")
/////////////////////////////////////////////////////////////////////////////////////////////////////
Text_Alert_Future = '{{strategy.order.alert_message}}'
copy_Fu = input( defval= Text_Alert_Future , title="Alert Message for BOT", inline = '00' ,group = '═ Bot Setting ═ \n >> If You Dont Use Bot Just Pass It' ,tooltip = 'Alert For X48-BOT > Copy and Paste To Alert Function')
passphrase = input.string(defval='1234', title ='Bot Pass',group='═ Bot Setting ═ \n >> If You Dont Use Bot Just Pass It', tooltip = 'Passphrase Must Be Same as X48-BOT')
leveragex = input.int(125,title='leverage',group='═ Bot Setting ═ \n >> If You Dont Use Bot Just Pass It',tooltip='"NOTHING" to do with Position size For Command To X48-BOT Only',minval=1)
longcommand = input.string(defval='AutoLong', title = 'Bot Long Command',group='═ Bot Setting ═ \n >> If You Dont Use Bot Just Pass It', tooltip = '1.OpenLong\n2.AutoLong\n***If AutoLong = Close(100%) First > Open Long Position Auto')
shortcommand = input.string(defval='AutoShort', title = 'Bot Short Command',group='═ Bot Setting ═ \n >> If You Dont Use Bot Just Pass It', tooltip = '1.OpenShort\n2.AutoShort\n***If AutoShort = Close(100%) First > Open Short Position Auto')
markettype = input.string(defval='bnfuture', title = 'Future/Spot Command',group='═ Bot Setting ═ \n >> If You Dont Use Bot Just Pass It', tooltip = '1. bnfuture = FUTURE MODE\n2. bnspot = SPOT MODE\n 3.bncombo = EZ 2in1 Order')
//////////////// Strategy Alert For X4815162342 BOT //////////////////////
//////// For Use Bot Can Change This Command By Your Self /////////////////////
string Alert_OpenLong = '{"ex":"'+markettype+'","side": "'+longcommand+'", "amount": "@{{strategy.order.contracts}}", "symbol": "{{ticker}}", "passphrase": "'+passphrase+'","leverage":"'+str.tostring(leveragex)+'", "tp" : "25", "sl" : "0", "tl" : "0", "callback" : "0"}'
string Alert_OpenShort = '{"ex":"'+markettype+'","side": "'+shortcommand+'", "amount": "@{{strategy.order.contracts}}", "symbol": "{{ticker}}", "passphrase": "'+passphrase+'","leverage":"'+str.tostring(leveragex)+'", "tp" : "25", "sl" : "0", "tl" : "0", "callback" : "0"}'
//string Alert_LongTP = '{"ex":"bnfuture","side": "CloseLong", "amount": "@{{strategy.order.contracts}}", "symbol": "{{ticker}}", "passphrase": "'+passphrase+'","leverage":"'+str.tostring(leveragex)+'"}'
//string Alert_ShortTP = '{"ex":"bnfuture","side": "CloseShort", "amount": "@{{strategy.order.contracts}}", "symbol": "{{ticker}}", "passphrase": "'+passphrase+'","leverage":"'+str.tostring(leveragex)+'"}'
//var message_closelong = '{"ex":"bnfuture","side": "CloseLong", "amount": "%100", "symbol": "{{ticker}}", "passphrase": "'+passphrase+'","leverage":"'+str.tostring(leveragex)+'"}'
//var message_closeshort = '{"ex":"bnfuture","side": "CloseShort", "amount": "%100", "symbol": "{{ticker}}", "passphrase": "'+passphrase+'","leverage":"'+str.tostring(leveragex)+'"}'
string Alert_StopLosslong = '{"ex":"'+markettype+'","side": "CloseLong", "amount": "%100", "symbol": "{{ticker}}", "passphrase": "'+passphrase+'","leverage":"'+str.tostring(leveragex)+'", "tp" : "0", "sl" : "0", "tl" : "0", "callback" : "0"}'
string Alert_StopLossshort = '{"ex":"'+markettype+'","side": "CloseShort", "amount": "%100", "symbol": "{{ticker}}", "passphrase": "'+passphrase+'","leverage":"'+str.tostring(leveragex)+'", "tp" : "0", "sl" : "0", "tl" : "0", "callback" : "0"}'
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ticker_close_price = request.security(syminfo.tickerid, timeframe = "1", expression = close)
ticker_high_price = request.security(syminfo.tickerid, timeframe = "1", expression = high)
ticker_low_price = request.security(syminfo.tickerid, timeframe = "1", expression = low)
period_close_price = request.security(syminfo.tickerid, timeframe = timeframe.period, expression = close)
period_high_price = request.security(syminfo.tickerid, timeframe = timeframe.period, expression = high)
period_low_price = request.security(syminfo.tickerid, timeframe = timeframe.period, expression = low)
entry_price = strategy.opentrades.entry_price(strategy.opentrades - 1)
PLOTBO_MODE = input.bool(title="[PLOT] BreakOut LINE [PLOT]", defval = false, group = GR1)
lengthBO = input.int(title="1️⃣ Length BreakOut", minval=1, maxval=1000, defval=5, group = GR1)
triling_BO = input.float(title = "🅾️ BreakOut Trailing CALLBACK [%]", defval = 2, minval = 0.01, maxval = 999.99, group = GR1)
upBound = ta.highest(high, lengthBO)
downBound = ta.lowest(low, lengthBO)
SL_LongBO = (ticker_close_price <= upBound-((upBound*triling_BO)/100))
//SL_LongBOPrice = upBound-((upBound*triling_BO)/100)
//SL_LongBOPrice = high[0]-((high[0]*triling_BO)/100)
SL_ShortBO = (ticker_close_price >= downBound+((downBound*triling_BO)/100))
//SL_ShortBOPrice = downBound+((downBound*triling_BO)/100)
//SL_ShortBOPrice = (low[0]+((low[0]*triling_BO)/100))
pvthi_BO = upBound
pvtlo_BO = downBound
ShuntBO = 1 //Wait for close before printing pivot? 1 for true 0 for flase
maxLvlLenBO = 0 //Maximum Extension Length
pvthiBO = pvthi_BO[ShuntBO]
pvtloBO = pvtlo_BO[ShuntBO]
// Count How many candles for current Pivot Level, If new reset.
counthiBO = ta.barssince(not na(pvthiBO))
countloBO = ta.barssince(not na(pvtloBO))
pvthisBO = fixnan(pvthiBO)
pvtlosBO = fixnan(pvtloBO)
hipcBO = ta.change(pvthisBO) != 0 ? na : color.lime
lopcBO = ta.change(pvtlosBO) != 0 ? na : color.red
// Display Pivot lines
plot(PLOTBO_MODE ? maxLvlLenBO == 0 or counthiBO < maxLvlLenBO ? pvthisBO : na : na, color=hipcBO, linewidth=2, title='Top LevelsBO')
plot(PLOTBO_MODE ? maxLvlLenBO == 0 or countloBO < maxLvlLenBO ? pvtlosBO : na : na, color=lopcBO, linewidth=2, title='Bottom LevelsBO')
//================ Consecutive UP/Down ===============
GR2 = "=====2️⃣2️⃣2️⃣ Consecutive Up/Down Strategy 2️⃣2️⃣2️⃣====="
Consecutive_MODE = input.bool(defval = false, title = "2️⃣ CONSECUTIVE BarsUP/DOWN MODE", group = GRS, tooltip = "Use Consecutive Strategy")
consecutiveBarsUp = input.int(defval = 3, title = '2️⃣ Consecutive BarsUp', minval = 1, group = GR2)
consecutiveBarsDown = input.int(defval = 3, title = '2️⃣ Consecutive BarsDown', minval = 1, group = GR2)
price = close
ups = 0.0
ups := price > price[1] ? nz(ups[1]) + 1 : 0
dns = 0.0
dns := price < price[1] ? nz(dns[1]) + 1 : 0
// ============= 15m BREAK RANGE GOLD AND CRYPTO ===============
GR3 = "=====3️⃣3️⃣3️⃣ 15m BREAK RANGE STRATEGY 3️⃣3️⃣3️⃣====="
hlrang_mode = input.bool(defval = false, title = "3️⃣ 15m High/Low Range Break MODE [BUY ONLY]", group = GRS)
hlrang_plot = input.bool(defval = false, title = "[PLOT] 15m High/Low Range Break [PLOT]", group = GR3)
rrange = high-low
lookback = input.int(2, minval=1, title="3️⃣ 15m - Lookback", group = GR3)
xr = input.int(10, minval=1, title="3️⃣ 15m - Range Length", group = GR3)
mult = input.float(2.0, minval=0.001, maxval=50, title="15m - SD", group = GR3)
computation = mult * ta.stdev(rrange, xr) + ta.sma(rrange, xr)
cond1 = rrange > computation
plot(hlrang_plot ? rrange : na, title="Range H-L", style=plot.style_columns)
plot(hlrang_plot ? computation : na, title="H-L SD", style=plot.style_line, color=color.orange)
plot(hlrang_plot ? close - close[lookback] : na, title="Close Direction", color=close > close[lookback] ? color.green : color.red, style=plot.style_histogram)
longCondition15 = hlrang_mode ? cond1 and close > close[lookback] : na
shortCondition15 = hlrang_mode ? cond1 and close < close[lookback] : na
//============== Swing High and Low Mode ===============
// Swing Plot
//Swing_MODE = input.bool(title="PLOT SWING MODE", defval=true, group = '= SWING SETTING =', tooltip = 'If Mode On = Plot Swing High and Swing Low')
pvtLenL = input.int(3, minval=1, title='🆎 Pivot Length Left Hand Side', group = '==🆎🆎🆎 TP/SL SWING SETTING 🆎🆎🆎==')
pvtLenR = input.int(3, minval=1, title='🆎 Pivot Length Right Hand Side', group = '==🆎🆎🆎 TP/SL SWING SETTING 🆎🆎🆎==')
// Get High and Low Pivot Points
pvthi_ = ta.pivothigh(high, pvtLenL, pvtLenR)
pvtlo_ = ta.pivotlow(low, pvtLenL, pvtLenR)
// Force Pivot completion before plotting.
Shunt = 1 //Wait for close before printing pivot? 1 for true 0 for flase
maxLvlLen = 0 //Maximum Extension Length
pvthi = pvthi_[Shunt]
pvtlo = pvtlo_[Shunt]
// Count How many candles for current Pivot Level, If new reset.
counthi = ta.barssince(not na(pvthi))
countlo = ta.barssince(not na(pvtlo))
pvthis = fixnan(pvthi)
pvtlos = fixnan(pvtlo)
hipc = ta.change(pvthis) != 0 ? na : color.maroon
lopc = ta.change(pvtlos) != 0 ? na : color.green
// Display Pivot lines
plot(Swing_STOP ? maxLvlLen == 0 or counthi < maxLvlLen ? pvthis : na : na, color=hipc, linewidth=1, offset=-pvtLenR - Shunt, title='Top Levels')
plot(Swing_STOP ? maxLvlLen == 0 or countlo < maxLvlLen ? pvtlos : na : na, color=lopc, linewidth=1, offset=-pvtLenR - Shunt, title='Bottom Levels')
plot(Swing_STOP ? maxLvlLen == 0 or counthi < maxLvlLen ? pvthis : na : na, color=hipc, linewidth=1, offset=0, title='Top Levels 2')
plot(Swing_STOP ? maxLvlLen == 0 or countlo < maxLvlLen ? pvtlos : na : na, color=lopc, linewidth=1, offset=0, title='Bottom Levels 2')
stopswinglow = ta.crossunder(close,pvtlos)
stopswinghigh = ta.crossover(close,pvthis)
if Swing_STOP == true
if Spot_MODE == false
if (close < pvtlos)
strategy.close("Long", qty_percent = 100, comment = "StopLong🏳️SwLow", alert_message = Alert_StopLosslong)
if (close > pvthis)
strategy.close("Short", qty_percent = 100, comment = "StopShort🏳️SwHi", alert_message = Alert_StopLossshort)
if Spot_MODE == true
if (close < pvtlos)
strategy.close("Long", qty_percent = 100, comment = "StopLong🏳️SwLow", alert_message = Alert_StopLosslong)
///////////////////////////////////////////////////////////////////////////////////
//GRSTO = "==🅱️🅱️🅱️ STOCHASTIC RSI SETTING [BG/Confirm]🅱️🅱️🅱️=="
//stobg_mode = input.bool(title="Stochastic RSI Background Paint", defval=false, group=GRSTO)
//stobg_plot = input.bool(title="STO-TEXT", defval=false, group=GRSTO, inline = 'STOT1')
//stobull_text = input.color(title = 'BULL', defval = color.white, group = GRSTO, inline = 'STOT1')
//stobear_text = input.color(title = 'BEAR', defval = color.orange, group = GRSTO, inline = 'STOT1')
//lengthMACD = input(title='🅱️ Length', defval=21, group = GRSTO, inline = '15')
//offsetMACD = input(title='🅱️ Offset', defval=0, group = GRSTO, inline = '15')
//srcMACD = input(close, title='🅱️ Source', group = GRSTO, inline = '16')
//length2MACD = input(title='🅱️ Trigger Length', defval=6, group = GRSTO, inline = '16')
//bullstobg = input.color(title = 'Bull BG Color', defval = color.green, group = GRSTO, inline = 'STOBG1')
//bearstobg = input.color(title = 'Bear BG Color', defval = color.red, group = GRSTO, inline = 'STOBG1')
//transstobg = input.int(defval = 75, title = 'Trans', minval = 0, maxval = 100, group = GRSTO, inline = 'STOBG1')
//
//lsma = ta.linreg(srcMACD, lengthMACD, offsetMACD)
//lsma2 = ta.linreg(lsma, lengthMACD, offsetMACD)
//b = lsma - lsma2
//zlsma2 = lsma + b
//trig2 = ta.sma(zlsma2, length2MACD)
//
//c1 = zlsma2 > trig2 ? bullstobg : bearstobg
//stobull = ta.crossover(zlsma2,trig2)
//stobear = ta.crossunder(zlsma2, trig2)
//stobullplus = zlsma2 > trig2
//stobearplus = zlsma2 < trig2
//plotshape(stobg_plot ? stobull : na, title = 'STO-BULL', text = 'STO-BULL', location = location.belowbar, textcolor = stobull_text, size = size.tiny)
//plotshape(stobg_plot ? stobear : na, title = 'STO-BULL', text = 'STO-BEAR', location = location.abovebar, textcolor = stobear_text, size = size.tiny)
//
//p1 = plot(stobg_mode ? zlsma2 : na, color=c1, linewidth=0)
//p2 = plot(stobg_mode ? trig2 : na, color=c1, linewidth=0)
//fill(p1, p2, color=color.new(c1,transp = transstobg))
////////////////////////////////////////////////////////////////////////////////////
GRMAC = '===💯💯💯4️⃣ Multi MA SETTING 4️⃣💯💯💯==='
MAStrategy_MODE = input.bool(title='4️⃣ MA CROSS X STRATEGY MODE', defval=false, group = GRS)
MARepeat_Mode = input.bool(title='4️⃣ 🎯MA CROSS X REPEAT MODE', defval=false, group = GRS, tooltip = "Repeat Mode After TP/SL Open Position With Trend Fast >,< Slow Again")
/////////// Normal Setting ////////////////
srcstrategy = input(close, title='💯4️⃣ Source Multi MA', group = GRMAC, tooltip = 'Normal Line = Close \nSmooth Line = ohlc4')
///////////// EMA/SMA SETTING /////////////
pricestrategy = request.security(syminfo.tickerid, timeframe.period, srcstrategy)
fastSW = input.bool(title='Show Fast MA Line', defval=false, group = GRMAC, inline = '11')
fastcolor = input.color(color.new(color.red,0), group = GRMAC, inline = '110', title = 'Fast MA Color')
slowSW = input.bool(title='Show Slow MA Line', defval=false, group = GRMAC, inline = '11')
slowcolor = input.color(color.new(color.yellow,0), group = GRMAC, inline = '110', title = 'Slow MA Color')
ma1strategy = input(12, title='💯4️⃣ Fast MA Length', group = GRMAC, inline = '12')
type1strategy = input.string('EMA', 'Fast MA Type', options=['SMA', 'EMA', 'WMA', 'HMA', 'RMA', 'VWMA'], group = GRMAC, tooltip = 'SMA / EMA / WMA / HMA / RMA / VWMA', inline = '12')
ma3strategy = input(26, title='💯4️⃣ Slow MA Length', group = GRMAC, inline = '13')
type3strategy = input.string('EMA', 'Slow MA Type', options=['SMA', 'EMA', 'WMA', 'HMA', 'RMA', 'VWMA'], group = GRMAC, tooltip = 'SMA / EMA / WMA / HMA / RMA / VWMA', inline = '13')
price1strategy = switch type1strategy
"EMA" => ta.ema(pricestrategy, ma1strategy)
"SMA" => ta.sma(pricestrategy, ma1strategy)
"WMA" => ta.wma(pricestrategy, ma1strategy)
"HMA" => ta.hma(pricestrategy, ma1strategy)
"RMA" => ta.rma(pricestrategy, ma1strategy)
"VWMA" => ta.vwma(pricestrategy, ma1strategy)
price3strategy = switch type3strategy
"EMA" => ta.ema(pricestrategy, ma3strategy)
"SMA" => ta.sma(pricestrategy, ma3strategy)
"WMA" => ta.wma(pricestrategy, ma3strategy)
"HMA" => ta.hma(pricestrategy, ma3strategy)
"RMA" => ta.rma(pricestrategy, ma3strategy)
"VWMA" => ta.vwma(pricestrategy, ma3strategy)
FastL = plot(fastSW ? price1strategy : na, 'Fast MA', color=fastcolor, style = plot.style_line, linewidth=2)
SlowL = plot(slowSW ? price3strategy : na, 'Slow MA', color=slowcolor, style = plot.style_line, linewidth=2)
BullMACross = ta.crossover(price1strategy, price3strategy)
BearMACross = ta.crossunder(price1strategy, price3strategy)
BullMAPlus = price1strategy > price3strategy
BearMAPlus = price1strategy < price3strategy
//********* Background Paint ***********************
prefillFast = plot(fastSW ? price1strategy : na, 'Fast MA', color=color.new(color.red, 100), style = plot.style_line, linewidth=2)
prefillSlow = plot(slowSW ? price3strategy : na, 'Fast MA', color=color.new(color.yellow, 100), style = plot.style_line, linewidth=2)
fcolor = price1strategy > price3strategy ? color.new(color.lime,70) : color.new(color.red,70)
fill(prefillFast,prefillSlow, color=fcolor, title='BACKGROUND PAINT')
// **********************************************
// ==================== DONCHIAN FANS MODE =====================
Donchian_MODE = input.bool(defval = false, title = "DONCHIAN FANS MODE", group = "== DONCHIAN FANS MODE ==")
Donchian_Bollinger = input.bool(defval = false, title = "DONCHIAN BOLLINGER LINE", group = "== DONCHIAN FANS MODE ==")
// Initiate bars:
var int bd = -1
bd += 1
//----------------------------------------------------------------------------------
// Required functions:
f_highest_bar(_source, _bars, _length) =>
float _h_value = _source
int _h_bar = _bars
for _i = 0 to math.max(_length - 1, 0) by 1
bool _isSourceOver = _source[_i] > _h_value
if _isSourceOver
_h_value := _source[_i]
_h_bar := _bars[_i]
_h_bar
[_h_value, _h_bar]
f_lowest_bar(_source, _bars, _length) =>
float _l_value = _source
int _l_bar = _bars
for _i = 0 to math.max(_length - 1, 0) by 1
bool _isSourceUnder = _source[_i] < _l_value
if _isSourceUnder
_l_value := _source[_i]
_l_bar := _bars[_i]
_l_bar
[_l_value, _l_bar]
f_line(_x1, _y1, _r, _color) =>
var line _li = na
line.delete(id=_li)
_li := line.new(x1=_x1 - 1, y1=_y1 - _r, x2=_x1, y2=_y1, xloc=xloc.bar_index, extend=extend.right, color=_color, style=line.style_dashed, width=1)
_li
//----------------------------------------------------------------------------------
int FANSlength = input.int(defval=100, title='FANS length:', minval=1, group = "== DONCHIAN FANS MODE ==")
[h_price, h_bar] = f_highest_bar(high, bd, FANSlength)
[l_price, l_bar] = f_lowest_bar(low, bd, FANSlength)
float mid = (h_price + l_price) / 2
plot(Donchian_Bollinger ? h_price : na, title='H', color=color.new(color.white, 20), linewidth=1, style=plot.style_line)
plot(Donchian_Bollinger ? mid : na, title='M', color=color.new(color.white, 20), linewidth=1, style=plot.style_line)
plot(Donchian_Bollinger ? l_price : na, title='L', color=color.new(color.white, 20), linewidth=1, style=plot.style_line)
var float r = ta.atr(FANSlength)
if ta.change(mid) != 0
r := ta.atr(FANSlength)
r
var line h_1_04 = na
var line h_1_08 = na
var line h_1_16 = na
var line h_1_32 = na
var line h_1_64 = na
var line l_1_04 = na
var line l_1_08 = na
var line l_1_16 = na
var line l_1_32 = na
var line l_1_64 = na
bool is_new_h = h_price > h_price[1]
bool is_new_l = l_price < l_price[1]
vhb = ta.valuewhen(high >= h_price, h_bar, 0)
vhp = ta.valuewhen(high >= h_price, h_price, 0)
vlb = ta.valuewhen(low <= l_price, l_bar, 0)
vlp = ta.valuewhen(low <= l_price, l_price, 0)
if is_new_l and Donchian_MODE == true
h_1_04 := f_line(vhb, vhp, -r * (1. / 04.), color.red)
h_1_08 := f_line(vhb, vhp, -r * (1. / 08.), color.red)
h_1_16 := f_line(vhb, vhp, -r * (1. / 16.), color.red)
h_1_32 := f_line(vhb, vhp, -r * (1. / 32.), color.red)
h_1_64 := f_line(vhb, vhp, -r * (1. / 64.), color.red)
h_1_64
if is_new_h and Donchian_MODE == true
l_1_04 := f_line(vlb, vlp, r * (1. / 04.), color.lime)
l_1_08 := f_line(vlb, vlp, r * (1. / 08.), color.lime)
l_1_16 := f_line(vlb, vlp, r * (1. / 16.), color.lime)
l_1_32 := f_line(vlb, vlp, r * (1. / 32.), color.lime)
l_1_64 := f_line(vlb, vlp, r * (1. / 64.), color.lime)
l_1_64
// **********************************************
GRIC = '===💮💮💮 ICHIMOKU SETTING 💮💮💮==='
Ichi_Mode = input.bool(title="ICHIMOKU PLOT MODE", defval=false, group = GRIC)
tenkan_len = input(9,'💮 Tenkan ',inline='tenkan', group = GRIC, tooltip = 'TENKAN = FAST SIGNAL')
tenkan_mult = input(2.,'',inline='tenkan', group = GRIC)
kijun_len = input(26,'💮 Kijun ',inline='kijun', group = GRIC, tooltip = 'KIJUN = SLOW SIGNAL')
kijun_mult = input(4.,'',inline='kijun', group = GRIC)
spanB_len = input(52,'Senkou Span A/B ',inline='span', group = GRIC, tooltip = 'SENKOU = CLOUD SIGNAL')
spanB_mult = input(6.,'',inline='span', group = GRIC)
cloudacolor = input.color(defval = color.new(color.orange,20), title = 'CLOUD-A', inline='span1', group = GRIC)
cloudbcolor = input.color(defval = color.new(color.purple,20), title = 'CLOUD-B', inline='span1', group = GRIC)
chi_color = input.color(defval = color.new(#73ecff,0), title = "Chikou-Color", group = GRIC, inline = 'CHIKOU')
offset = input(26,'Chikou', group = GRIC, tooltip = 'CHIKOU = CANDLE LOOK BACK DEFAULT = 26', inline = 'CHIKOU')
//------------------------------------------------------------------------------
avg(src,length,mult)=>
atr = ta.atr(length)*mult
up = hl2 + atr
dn = hl2 - atr
upper = 0.,lower = 0.
upper := src[1] < upper[1] ? math.min(up,upper[1]) : up
lower := src[1] > lower[1] ? math.max(dn,lower[1]) : dn
os = 0,max = 0.,min = 0.
os := src > upper ? 1 : src < lower ? 0 : os[1]
spt = os == 1 ? lower : upper
max := ta.cross(src,spt) ? math.max(src,max[1]) : os == 1 ? math.max(src,max[1]) : spt
min := ta.cross(src,spt) ? math.min(src,min[1]) : os == 0 ? math.min(src,min[1]) : spt
math.avg(max,min)
//------------------------------------------------------------------------------
tenkan = avg(close,tenkan_len,tenkan_mult)
kijun = avg(close,kijun_len,kijun_mult)
senkouA = math.avg(kijun,tenkan)
senkouB = avg(close,spanB_len,spanB_mult)
//------------------------------------------------------------------------------
tenkan_css = color.white
kijun_css = #ff5d00
cloud_a = cloudacolor
cloud_b = cloudbcolor
chikou_css = color.new(#73ecff,20)
plot(Ichi_Mode ? tenkan : na,'Tenkan-Sen',tenkan_css,style = plot.style_stepline, linewidth = 2)
plot(Ichi_Mode ? kijun : na,'Kijun-Sen',kijun_css, style = plot.style_stepline, linewidth = 2)
plot(Ichi_Mode ? ta.crossover(tenkan,kijun) ? kijun : na : na,'Crossover',#2157f3,3,plot.style_circles)
plot(Ichi_Mode ? ta.crossunder(tenkan,kijun) ? kijun : na : na,'Crossunder',#ff5d00,3,plot.style_circles)
A = plot(Ichi_Mode ? senkouA : na,'Senkou Span A',na,offset=offset-1)
B = plot(Ichi_Mode ? senkouB : na,'Senkou Span B',na,offset=offset-1)
fill(A,B,senkouA > senkouB ? cloud_a : cloud_b)
ichi_bull = ta.crossover(tenkan,kijun)
ichi_bear = ta.crossunder(tenkan,kijun)
ichi_bullplus = tenkan > kijun
ichi_bearplus = tenkan < kijun
plot(Ichi_Mode ? close : na,'Chikou',chi_color,offset=-offset+1, linewidth = 2)
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
GRCMA = '==🅰️🅰️5️⃣5️⃣ MACD SETTING [PLOT/Confirm]5️⃣5️⃣🅰️🅰️=='
MACDStrategy_MODE = input.bool(title='5️⃣ MACD CROSS [0] STRATEGY MODE', defval=false, group = GRS)
MACDStrategy_Repeat = input.bool(title='5️⃣🎯 MACD CROSS [0] REPEAT MODE', defval=false, group = GRS, tooltip = "Repeat Mode After TP/SL Open Position With Trend Fast >,< Slow Again")
MACD_MODE_SIG= input.bool(title="MACD MODE = MACD Cross Signal", defval=false, group = GRCMA, tooltip = 'If Mode On = Use MACD Strategy for Signal When Cross Up and Cross Down')
//if MACD_MODE_SIG == true
MACDfastLength = input(12, title='🅰️5️⃣ MACD Fast', group = GRCMA, inline = 'MACDSIG1')
MACDslowlength = input(26, title='🅰️5️⃣ MACD Slow', group = GRCMA, inline = 'MACDSIG1')
MACDLength = input(18, title='🅰️5️⃣ MACD Length', group = GRCMA)
macdupcolor = input.color(defval = color.new(color.green,0), title = 'CROSS-UP', inline = 'MACDCO', group = GRCMA)
macddowncolor = input.color(defval = color.new(color.red,0), title = 'CROSS-DOWN', inline = 'MACDCO', group = GRCMA)
MACD = ta.ema(close, MACDfastLength) - ta.ema(close, MACDslowlength)
aMACD = ta.ema(MACD, MACDLength)
delta = MACD - aMACD
macdTPl = (ta.crossover(delta, 0))
macdTPs = (ta.crossunder(delta, 0))
MACDBull = delta > 0
MACDBear = delta < 0
plotshape(MACD_MODE_SIG ? macdTPl : na, title='macdTPl', text = '💎', color=macdupcolor, style=shape.circle, location=location.belowbar, size=size.auto) //plot for buy icon
plotshape(MACD_MODE_SIG ? macdTPs : na, title='macdTPs', text = '💎', color=macddowncolor, style=shape.circle, location=location.abovebar, size=size.auto) //plot for buy icon
//=============== TAKE PROFIT and STOP LOSS by % =================
tpsl(percent) =>
strategy.position_avg_price * percent / 100 / syminfo.mintick
GR4 = "=====🆘🆘🆘 TAKE PROFIT & STOP LOSS BY [%] 🆘🆘🆘====="
mode = input.bool(title="🆘 Take Profit & Stop Loss By Percent (%)", defval=false, group=GRSUB, tooltip = "Take Profit & Stop Loss by % Change")
pnl_mode = input.bool(title="🆘 PNL MODE ($) -->> ", defval=false, group=GRSUB, tooltip = "Take Profit By PNL ($) Ex. 5 = 5$ Then Auto Close Position", inline = "PNL")
pnl_value = input.float(defval = 5, title = "🆘 PNL Value ($)", group = GRSUB, tooltip = "Take Profit By PNL ($) Ex. 5 = 5$ Then Auto Close Position", inline = "PNL")
tp_l = tpsl(input.float(99999, title='🆘 TP [LONG] %', group=GR4))
tp_s = tpsl(input.float(33.3, title='🆘 TP [SHORT] %', group=GR4))
sl = tpsl(input.float(0, title='🆘 Stop Loss %', group=GR4))
current_pnl = strategy.openprofit
pnl_tp = current_pnl >= pnl_value
calcStopLossPrice(OffsetPts) =>
if strategy.position_size > 0
strategy.position_avg_price - OffsetPts * syminfo.mintick
else if strategy.position_size < 0
strategy.position_avg_price + OffsetPts * syminfo.mintick
else
na
calcStopLossL_AlertPrice(OffsetPts) =>
strategy.position_avg_price - OffsetPts * syminfo.mintick
calcStopLossS_AlertPrice(OffsetPts) =>
strategy.position_avg_price + OffsetPts * syminfo.mintick
calcTakeProfitPrice(OffsetPts) =>
if strategy.position_size > 0
strategy.position_avg_price + OffsetPts * syminfo.mintick
else if strategy.position_size < 0
strategy.position_avg_price - OffsetPts * syminfo.mintick
else
na
calcTakeProfitL_AlertPrice(OffsetPts) =>
strategy.position_avg_price + OffsetPts * syminfo.mintick
calcTakeProfitS_AlertPrice(OffsetPts) =>
strategy.position_avg_price - OffsetPts * syminfo.mintick
var stoploss = 0.
var stoploss_l = 0.
var stoploss_s = 0.
var takeprofit = 0.
var takeprofit_l = 0.
var takeprofit_s = 0.
var takeprofit_ll = 0.
var takeprofit_ss = 0.
GRT = "=====🆑🆑🆑 ATR TRAILING STOP 🆑🆑🆑====="
/////////notes////////////////////////////////////////
// This is based on the ATR trailing stop indicator //
// width addition of two levels of stops and //
// different interpretation. //
// This is a fast-reacting system and is better //
// suited for higher volatility markets //
//////////////////////////////////////////////////////
// Fast Trail //
AP1 = input.int(5, '🆑 Fast ATR period', group = GRT) // ATR Period
AF1 = input.float(0.5, '🆑 Fast ATR multiplier', group = GRT) // ATR Factor
SL1 = AF1 * ta.atr(AP1) // Stop Loss
Trail1 = 0.0
iff_1 = close > nz(Trail1[1], 0) ? close - SL1 : close + SL1
iff_2 = close < nz(Trail1[1], 0) and close[1] < nz(Trail1[1], 0) ? math.min(nz(Trail1[1], 0), close + SL1) : iff_1
Trail1 := close > nz(Trail1[1], 0) and close[1] > nz(Trail1[1], 0) ? math.max(nz(Trail1[1], 0), close - SL1) : iff_2
// Slow Trail //
AP2 = input.int(10, '🆑 Slow ATR period', group = GRT) // ATR Period
AF2 = input.float(2, '🆑 Slow ATR multiplier', group = GRT) // ATR Factor
SL2 = AF2 * ta.atr(AP2) // Stop Loss
Trail2 = 0.0
iff_3 = close > nz(Trail2[1], 0) ? close - SL2 : close + SL2
iff_4 = close < nz(Trail2[1], 0) and close[1] < nz(Trail2[1], 0) ? math.min(nz(Trail2[1], 0), close + SL2) : iff_3
Trail2 := close > nz(Trail2[1], 0) and close[1] > nz(Trail2[1], 0) ? math.max(nz(Trail2[1], 0), close - SL2) : iff_4
BuyLong = ta.crossover(Trail1, Trail2)
SellShort = ta.crossunder(Trail1, Trail2)
TS1 = plot(plotcolor ? Trail1 : na, 'Fast Trail', style=plot.style_line, color=Trail1 > Trail2 ? color.blue : color.yellow, linewidth=3, display=display.none)
TS2 = plot(plotcolor ? Trail2 : na, 'Slow Trail', style=plot.style_line, color=Trail1 > Trail2 ? color.lime : color.blue, linewidth=3)
if plotcolor == true
if BuyLong and strategy.position_size < 0
strategy.close('Short', qty_percent = 100, alert_message = Alert_StopLossshort, comment = "🚨ATR TL🚨")
if SellShort and strategy.position_size > 0
strategy.close('Long', qty_percent = 100, alert_message = Alert_StopLosslong, comment = "🚨ATR TL🚨")
GRARO = "===🍩🍩🍩 AROON SETTING 🍩🍩🍩==="
// ######### TRENDLOCK CONFIRM (MACD > 0 and MA FAST > SLOW) ########
AroonConfirm_MODE = input.bool(defval = false, title = "🍩 AROON 100% & -100% CONFIRM", group = GRCON)
lengthAroon = input.int(14, minval=1, title = "AROON LENGTH", group = GRARO)
AroonUpper = 100 * (ta.highestbars(high, lengthAroon) + lengthAroon)/lengthAroon
AroonLower = 100 * (ta.lowestbars(low, lengthAroon) + lengthAroon)/lengthAroon
AroonCrossUp = ta.crossover(AroonUpper, AroonLower)
AroonCrossDown = ta.crossunder(AroonUpper, AroonLower)
AroonHitUp = AroonUpper > AroonLower
AroonHitDown = AroonUpper < AroonLower
GRRSI = "🉐=== RSI MODE ==="
RSI_PLOT = input.bool(defval = false, title = "🉐=== RSI LINE ===", group = GRRSI)
RSI_OB = input.int(defval = 50, title = "🉐 RSI OverBought", minval = 1, maxval = 100, tooltip = "RSI OB", group = GRRSI)
RSI_OS = input.int(defval = 50, title = "🉐 RSI OverSold", minval = 1, maxval = 100, tooltip = "RSI OS", group = GRRSI)
RSI_LENGTH = input.int(defval = 14, title = "RSI LENGTH", minval = 1, maxval = 999, tooltip = "RSI LENGTH", group = GRRSI)
RSI_SMA = input.int(defval = 50, title = "RSI SMA LENGTH", minval = 1, maxval = 999, tooltip = "RSI SMA LENGTH FOR PREDICT TREND", group = GRRSI)
RSI_COL = input.color(defval = color.white, title = "RSI LINE", group = GRRSI, inline = "RSI1")
RSI_SIZE = input.int(defval = 2, title = "SIZE", minval = 0, maxval = 4, tooltip = "Width 0-4", inline = "RSI1", group = GRRSI)
RSI_TRANS = input.int(defval = 0, title = "TRNS", minval = 0, maxval = 100, tooltip = "Transparency 0-100", inline = "RSI1", group = GRRSI)
RSIMA_COL1 = input.color(defval = color.blue, title = "RSIMA LINE", group = GRRSI, inline = "RSI2")
RSIMA_COL2 = input.color(defval = color.teal, title = "", group = GRRSI, inline = "RSI2")
RSIMA_SIZE = input.int(defval = 3, title = "SIZE", minval = 0, maxval = 4, tooltip = "Width 0-4", inline = "RSI2", group = GRRSI)
RSIMA_TRANS = input.int(defval = 0, title = "TRNS", minval = 0, maxval = 100, tooltip = "Transparency 0-100", inline = "RSI2", group = GRRSI)
up = ta.rma(math.max(ta.change(close), 0), RSI_LENGTH)
down = ta.rma(-math.min(ta.change(close), 0), RSI_LENGTH)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
vrsi = ta.rsi(close, RSI_LENGTH)
RSIUP = ta.crossover(vrsi, RSI_OB)
RSIDOWN = ta.crossunder(vrsi, RSI_OS)
rsiMA = ta.sma(rsi, RSI_SMA)
RSIBULL = ta.crossover(rsi, rsiMA)
RSIBEAR = ta.crossunder(rsi, rsiMA)
BULLRSI = rsi <= RSI_OB
BEARRSI = rsi >= RSI_OS
RSIc1 = rsi > rsiMA ? color.new(RSIMA_COL1, RSIMA_TRANS) : color.new(RSIMA_COL2, RSIMA_TRANS)
plotshape(RSI_PLOT ? RSIUP : na, title='RSIUP', text = 'OB', color=color.new(color.yellow, 100), style=shape.circle, location=location.belowbar, size=size.auto) //plot for buy icon
plotshape(RSI_PLOT ? RSIDOWN : na, title='RSIDOWN', text = 'OS', color=color.new(color.red, 100), style=shape.circle, location=location.abovebar, size=size.auto) //plot for buy icon
plot(RSI_PLOT ? rsi : na, title = "RSI", color = color.new(RSI_COL,RSI_TRANS), linewidth = RSI_SIZE, style = plot.style_line)
plot(RSI_PLOT ? rsiMA : na, title = "RSI-based MA", color=RSIc1, linewidth = RSIMA_SIZE, style = plot.style_line)
Disable_Confirm = MACDConfirm_MODE == false and RSIConfirm_MODE == false and MACross_MODE == false and IchiConfirm_MODE == false and AroonConfirm_MODE == false
//////////// INPUT BACKTEST RANGE ////////////////////////////////////////////////////
var string BTR1 = '════════ INPUT BACKTEST TIME RANGE ════════'
i_startTime = input.time(defval = timestamp("01 Jan 1945 00:00 +0000"), title = "Start", inline="timestart", group=BTR1, tooltip = 'Start Backtest YYYY/MM/DD')
i_endTime = input.time(defval = timestamp("01 Jan 2074 23:59 +0000"), title = "End", inline="timeend", group=BTR1, tooltip = 'End Backtest YYYY/MM/DD')
// Define the trading time range
startHour = input.int(defval = 0, title = "⌛⌛ Start Trade , O Clock", group = GRCON, inline = "Start01")
startMinute = input.int(defval = 0, title = "Minute ", group = GRCON, inline = "Start01")
endHour = input.int(defval = 23, title = "⌛⌛ Stop Trade , O Clock", group = GRCON, inline = "Stop01")
endMinute = input.int(defval = 59, title = "Minute ", group = GRCON, inline = "Stop01")
// Convert the trading time range to seconds
startSeconds = (startHour * 60 + startMinute) * 60
endSeconds = (endHour * 60 + endMinute) * 60
// Check if the current time is within the specified range
isTradingTime = time >= timestamp(year, month, dayofmonth, startHour, startMinute) and time <= timestamp(year, month, dayofmonth, endHour, endMinute)
if time >= i_startTime and time <= i_endTime and isTradingTime
// ##### BreakOut Strategy ######
if Spot_MODE == false
if MACDConfirm_MODE == true
if BreakOut_MODE == true
if not na(close[lengthBO]) and MACDBull
strategy.entry("Long", strategy.long, stop=upBound + syminfo.mintick, comment="Break🌙MACD", alert_message = Alert_OpenLong)
if MACDBear
strategy.entry("Short", strategy.short, stop=downBound - syminfo.mintick, comment="Break👻MACD", alert_message = Alert_OpenShort)
// ##### Consecutive Strategy #######
if (Consecutive_MODE ? ups >= consecutiveBarsUp : na) and MACDBull
strategy.entry("Long", strategy.long, comment="Up🌙MACD", alert_message = Alert_OpenLong)
if (Consecutive_MODE ? dns >= consecutiveBarsDown : na) and MACDBear
strategy.entry("Short", strategy.short, comment="Down👻MACD", alert_message = Alert_OpenShort)
// ##### 15m Strategy ######
if (longCondition15) and MACDBull
strategy.entry("Long", strategy.long, alert_message = Alert_OpenLong, comment = "15m🌙MACD")
alert("15m BREAK UP", freq = alert.freq_once_per_bar_close)
if (shortCondition15) and MACDBear
strategy.close_all("15m BREAK DOWN", immediately = true, alert_message = Alert_StopLosslong)
alert("15m BREAK DOWN", freq = alert.freq_once_per_bar_close)
if MAStrategy_MODE == true and MARepeat_Mode == false
if BullMACross and MACDBull
strategy.entry("Long", strategy.long, comment="X🌙MACD", alert_message = Alert_OpenLong)
if BearMACross and MACDBear
strategy.entry("Short", strategy.short, comment="X👻MACD", alert_message = Alert_OpenShort)
if (MAStrategy_MODE == true and MARepeat_Mode == true) or (MAStrategy_MODE == false and MARepeat_Mode == true)
if BullMAPlus and MACDBull
strategy.entry("Long", strategy.long, comment="X-Re🌙MACD", alert_message = Alert_OpenLong)
if BearMAPlus and MACDBear
strategy.entry("Short", strategy.short, comment="X-Re👻MACD", alert_message = Alert_OpenShort)
if MACDStrategy_MODE == true and MACDStrategy_Repeat == false
if macdTPl
strategy.entry("Long", strategy.long, comment="MACD🌙X", alert_message = Alert_OpenLong)
if macdTPs
strategy.entry("Short", strategy.short, comment="MACD👻X", alert_message = Alert_OpenShort)
if (MACDStrategy_MODE == true and MACDStrategy_Repeat == true)
if MACDBull or macdTPl
strategy.entry("Long", strategy.long, comment="MACD🌙X", alert_message = Alert_OpenLong)
if MACDBear or macdTPs
strategy.entry("Short", strategy.short, comment="MACD👻X", alert_message = Alert_OpenShort)
if (MACDStrategy_MODE == false and MACDStrategy_Repeat == true)
if MACDBull
strategy.entry("Long", strategy.long, comment="MACD🌙X", alert_message = Alert_OpenLong)
if MACDBear
strategy.entry("Short", strategy.short, comment="MACD👻X", alert_message = Alert_OpenShort)
if RSIConfirm_MODE == true
if BreakOut_MODE == true
if not na(close[lengthBO]) and BULLRSI
strategy.entry("Long", strategy.long, stop=upBound + syminfo.mintick, comment="Break🌙RSI", alert_message = Alert_OpenLong)
if BEARRSI
strategy.entry("Short", strategy.short, stop=downBound - syminfo.mintick, comment="Break👻RSI", alert_message = Alert_OpenShort)
// ##### Consecutive Strategy #######
if (Consecutive_MODE ? ups >= consecutiveBarsUp : na) and BULLRSI
strategy.entry("Long", strategy.long, comment="Up🌙RSI", alert_message = Alert_OpenLong)
if (Consecutive_MODE ? dns >= consecutiveBarsDown : na) and BEARRSI
strategy.entry("Short", strategy.short, comment="Down👻RSI", alert_message = Alert_OpenShort)
// ##### 15m Strategy ######
if (longCondition15) and BULLRSI
strategy.entry("Long", strategy.long, alert_message = Alert_OpenLong, comment = "15m🌙RSI")
alert("15m BREAK UP", freq = alert.freq_once_per_bar_close)
if (shortCondition15) and BEARRSI
strategy.close_all("15m BREAK DOWN", immediately = true, alert_message = Alert_StopLosslong)
alert("15m BREAK DOWN", freq = alert.freq_once_per_bar_close)
if MAStrategy_MODE == true and MARepeat_Mode == false
if BullMAPlus and BULLRSI
strategy.entry("Long", strategy.long, comment="X🌙RSI", alert_message = Alert_OpenLong)
if BearMAPlus and BEARRSI
strategy.entry("Short", strategy.short, comment="X👻RSI", alert_message = Alert_OpenShort)
if (MAStrategy_MODE == true and MARepeat_Mode == true) or (MAStrategy_MODE == false and MARepeat_Mode == true)
if BullMAPlus and BULLRSI
strategy.entry("Long", strategy.long, comment="X-Re🌙RSI", alert_message = Alert_OpenLong)
if BearMAPlus and BEARRSI
strategy.entry("Short", strategy.short, comment="X-Re👻RSI", alert_message = Alert_OpenShort)
if MACDStrategy_MODE == true and MACDStrategy_Repeat == false
if macdTPl and BULLRSI
strategy.entry("Long", strategy.long, comment="MACD🌙RSI", alert_message = Alert_OpenLong)
if macdTPs and BEARRSI
strategy.entry("Short", strategy.short, comment="MACD👻RSI", alert_message = Alert_OpenShort)
if MACDStrategy_MODE == true and MACDStrategy_Repeat == true
if (MACDBull and BULLRSI) or (macdTPl and BULLRSI)
strategy.entry("Long", strategy.long, comment="MACD🌙RSI", alert_message = Alert_OpenLong)
if (MACDBear and BEARRSI) or (macdTPs and BEARRSI)
strategy.entry("Short", strategy.short, comment="MACD👻RSI", alert_message = Alert_OpenShort)
if MACDStrategy_MODE == false and MACDStrategy_Repeat == true
if MACDBull and BULLRSI
strategy.entry("Long", strategy.long, comment="MACD🌙RSI", alert_message = Alert_OpenLong)
if MACDBear and BEARRSI
strategy.entry("Short", strategy.short, comment="MACD👻RSI", alert_message = Alert_OpenShort)
if MACross_MODE == true
if BreakOut_MODE == true
if not na(close[lengthBO]) and BullMAPlus
strategy.entry("Long", strategy.long, stop=upBound + syminfo.mintick, comment="Break🌙MA", alert_message = Alert_OpenLong)
if BearMAPlus
strategy.entry("Short", strategy.short, stop=downBound - syminfo.mintick, comment="Break👻MA", alert_message = Alert_OpenShort)
// ##### Consecutive Strategy #######
if (Consecutive_MODE ? ups >= consecutiveBarsUp : na) and BullMAPlus
strategy.entry("Long", strategy.long, comment="Up🌙MA", alert_message = Alert_OpenLong)
if (Consecutive_MODE ? dns >= consecutiveBarsDown : na) and BearMAPlus
strategy.entry("Short", strategy.short, comment="Down👻MA", alert_message = Alert_OpenShort)
// ##### 15m Strategy ######
if (longCondition15) and BullMAPlus
strategy.entry("Long", strategy.long, alert_message = Alert_OpenLong, comment = "15m🌙MA")
alert("15m BREAK UP", freq = alert.freq_once_per_bar_close)
if (shortCondition15) and BearMAPlus
strategy.close_all("15m BREAK DOWN", immediately = true, alert_message = Alert_StopLosslong)
alert("15m BREAK DOWN", freq = alert.freq_once_per_bar_close)
if MACDStrategy_MODE == true and MACDStrategy_Repeat == true
if (macdTPl and BullMAPlus) or (MACDBull and BullMAPlus)
strategy.entry("Long", strategy.long, comment="MACD🌙MA", alert_message = Alert_OpenLong)
if (macdTPs and BearMAPlus) or (MACDBear and BearMAPlus)
strategy.entry("Short", strategy.short, comment="MACD👻MA", alert_message = Alert_OpenShort)
if MACDStrategy_MODE == true and MACDStrategy_Repeat == false
if (macdTPl and BullMAPlus)
strategy.entry("Long", strategy.long, comment="MACD🌙MA", alert_message = Alert_OpenLong)
if (macdTPs and BearMAPlus)
strategy.entry("Short", strategy.short, comment="MACD👻MA", alert_message = Alert_OpenShort)
if MACDStrategy_MODE == false and MACDStrategy_Repeat == true
if (MACDBull and BullMAPlus)
strategy.entry("Long", strategy.long, comment="MACD🌙MA", alert_message = Alert_OpenLong)
if (MACDBear and BearMAPlus)
strategy.entry("Short", strategy.short, comment="MACD👻MA", alert_message = Alert_OpenShort)
if MAStrategy_MODE == true and MARepeat_Mode == false
if BullMACross
strategy.entry("Long", strategy.long, comment="X🌙", alert_message = Alert_OpenLong)
if BearMACross
strategy.entry("Short", strategy.short, comment="X👻", alert_message = Alert_OpenShort)
if (MAStrategy_MODE == true and MARepeat_Mode == true) or (MAStrategy_MODE == false and MARepeat_Mode == true)
if BullMAPlus
strategy.entry("Long", strategy.long, comment="X-Re🌙", alert_message = Alert_OpenLong)
if BearMAPlus
strategy.entry("Short", strategy.short, comment="X-Re👻", alert_message = Alert_OpenShort)
if IchiConfirm_MODE == true
if BreakOut_MODE == true
if not na(close[lengthBO]) and ichi_bullplus
strategy.entry("Long", strategy.long, stop=upBound + syminfo.mintick, comment="Break🌙ICHI", alert_message = Alert_OpenLong)
if ichi_bearplus
strategy.entry("Short", strategy.short, stop=downBound - syminfo.mintick, comment="Break👻ICHI", alert_message = Alert_OpenShort)
// ##### Consecutive Strategy #######
if (Consecutive_MODE ? ups >= consecutiveBarsUp : na) and ichi_bullplus
strategy.entry("Long", strategy.long, comment="Up🌙ICHI", alert_message = Alert_OpenLong)
if (Consecutive_MODE ? dns >= consecutiveBarsDown : na) and ichi_bearplus
strategy.entry("Short", strategy.short, comment="Down👻ICHI", alert_message = Alert_OpenShort)
// ##### 15m Strategy ######
if (longCondition15) and ichi_bullplus
strategy.entry("Long", strategy.long, alert_message = Alert_OpenLong, comment = "15m🌙ICHI")
alert("15m BREAK UP", freq = alert.freq_once_per_bar_close)
if (shortCondition15) and ichi_bearplus
strategy.close_all("15m BREAK DOWN", immediately = true, alert_message = Alert_StopLosslong)
alert("15m BREAK DOWN", freq = alert.freq_once_per_bar_close)
if MAStrategy_MODE == true and MARepeat_Mode == false
if BullMACross and ichi_bullplus
strategy.entry("Long", strategy.long, comment="X🌙ICHI", alert_message = Alert_OpenLong)
if BearMACross and ichi_bearplus
strategy.entry("Short", strategy.short, comment="X👻ICHI", alert_message = Alert_OpenShort)
if (MAStrategy_MODE == true and MARepeat_Mode == true) or (MAStrategy_MODE == false and MARepeat_Mode == true)
if BullMAPlus and ichi_bullplus
strategy.entry("Long", strategy.long, comment="X-Re🌙ICHI", alert_message = Alert_OpenLong)
if BearMAPlus and ichi_bearplus
strategy.entry("Short", strategy.short, comment="X-Re👻ICHI", alert_message = Alert_OpenShort)
if MACDStrategy_MODE == true and MACDStrategy_Repeat == true
if (macdTPl and ichi_bullplus) or (MACDBull and ichi_bullplus)
strategy.entry("Long", strategy.long, comment="MACD🌙ICHI", alert_message = Alert_OpenLong)
if (macdTPs and ichi_bearplus) or (MACDBear and ichi_bearplus)
strategy.entry("Short", strategy.short, comment="MACD👻ICHI", alert_message = Alert_OpenShort)
if MACDStrategy_MODE == true and MACDStrategy_Repeat == false
if (macdTPl and ichi_bullplus)
strategy.entry("Long", strategy.long, comment="MACD🌙ICHI", alert_message = Alert_OpenLong)
if (macdTPs and ichi_bearplus)
strategy.entry("Short", strategy.short, comment="MACD👻ICHI", alert_message = Alert_OpenShort)
if MACDStrategy_MODE == false and MACDStrategy_Repeat == true
if (MACDBull and ichi_bullplus)
strategy.entry("Long", strategy.long, comment="MACD🌙ICHI", alert_message = Alert_OpenLong)
if (MACDBear and ichi_bearplus)
strategy.entry("Short", strategy.short, comment="MACD👻ICHI", alert_message = Alert_OpenShort)
if AroonConfirm_MODE == true
if BreakOut_MODE == true
if not na(close[lengthBO]) and AroonHitUp
strategy.entry("Long", strategy.long, stop=upBound + syminfo.mintick, comment="Break🌙AR", alert_message = Alert_OpenLong)
if AroonHitDown
strategy.entry("Short", strategy.short, stop=downBound - syminfo.mintick, comment="Break👻AR", alert_message = Alert_OpenShort)
// ##### Consecutive Strategy #######
if (Consecutive_MODE ? ups >= consecutiveBarsUp : na) and AroonHitUp
strategy.entry("Long", strategy.long, comment="Up🌙AR", alert_message = Alert_OpenLong)
if (Consecutive_MODE ? dns >= consecutiveBarsDown : na) and AroonHitDown
strategy.entry("Short", strategy.short, comment="Down👻AR", alert_message = Alert_OpenShort)
// ##### 15m Strategy ######
if (longCondition15) and AroonHitUp
strategy.entry("Long", strategy.long, alert_message = Alert_OpenLong, comment = "15m🌙AR")
alert("15m BREAK UP", freq = alert.freq_once_per_bar_close)
if (shortCondition15) and AroonHitDown
strategy.close_all("15m BREAK DOWN", immediately = true, alert_message = Alert_StopLosslong)
alert("15m BREAK DOWN", freq = alert.freq_once_per_bar_close)
if MAStrategy_MODE == true and MARepeat_Mode == false
if BullMACross and AroonHitUp
strategy.entry("Long", strategy.long, comment="X🌙AR", alert_message = Alert_OpenLong)
if BearMACross and AroonHitDown
strategy.entry("Short", strategy.short, comment="X👻AR", alert_message = Alert_OpenShort)
if (MAStrategy_MODE == true and MARepeat_Mode == true) or (MAStrategy_MODE == false and MARepeat_Mode == true)
if BullMAPlus and AroonHitUp
strategy.entry("Long", strategy.long, comment="X-Re🌙AR", alert_message = Alert_OpenLong)
if BearMAPlus and AroonHitDown
strategy.entry("Short", strategy.short, comment="X-Re👻AR", alert_message = Alert_OpenShort)
if MACDStrategy_MODE == true and MACDStrategy_Repeat == false
if macdTPl and AroonHitUp
strategy.entry("Long", strategy.long, comment="MACD🌙AR", alert_message = Alert_OpenLong)
if macdTPs and AroonHitDown
strategy.entry("Short", strategy.short, comment="MACD👻AR", alert_message = Alert_OpenShort)
if MACDStrategy_MODE == true and MACDStrategy_Repeat == true
if (macdTPl and AroonHitUp) or (MACDBull and AroonHitUp)
strategy.entry("Long", strategy.long, comment="MACD🌙AR", alert_message = Alert_OpenLong)
if (macdTPs and AroonHitDown) or (MACDBear and AroonHitDown)
strategy.entry("Short", strategy.short, comment="MACD👻AR", alert_message = Alert_OpenShort)
if MACDStrategy_MODE == false and MACDStrategy_Repeat == true
if (MACDBull and AroonHitUp)
strategy.entry("Long", strategy.long, comment="MACD🌙AR", alert_message = Alert_OpenLong)
if (MACDBear and AroonHitDown)
strategy.entry("Short", strategy.short, comment="MACD👻AR", alert_message = Alert_OpenShort)
if MACDConfirm_MODE == false and RSIConfirm_MODE == false and MACross_MODE == false and IchiConfirm_MODE == false and AroonConfirm_MODE == false
if BreakOut_MODE == true
if not na(close[lengthBO])
strategy.entry("Long", strategy.long, stop=upBound + syminfo.mintick, comment="Break🌙", alert_message = Alert_OpenLong)
strategy.entry("Short", strategy.short, stop=downBound - syminfo.mintick, comment="Break👻", alert_message = Alert_OpenShort)
// ##### Consecutive Strategy #######
if (Consecutive_MODE ? ups >= consecutiveBarsUp : na)
strategy.entry("Long", strategy.long, comment="Up🌙", alert_message = Alert_OpenLong)
if (Consecutive_MODE ? dns >= consecutiveBarsDown : na)
strategy.entry("Short", strategy.short, comment="Down👻", alert_message = Alert_OpenShort)
// ##### 15m Strategy ######
if (longCondition15)
strategy.entry("Long", strategy.long, alert_message = Alert_OpenLong)
alert("15m BREAK UP", freq = alert.freq_once_per_bar_close)
if (shortCondition15)
strategy.close_all("15m BREAK DOWN", immediately = true, alert_message = Alert_StopLosslong)
alert("15m BREAK DOWN", freq = alert.freq_once_per_bar_close)
if MAStrategy_MODE == true and MARepeat_Mode == false
if BullMACross
strategy.entry("Long", strategy.long, comment="X🌙", alert_message = Alert_OpenLong)
if BearMACross
strategy.entry("Short", strategy.short, comment="X👻", alert_message = Alert_OpenShort)
if (MAStrategy_MODE == true and MARepeat_Mode == true) or (MAStrategy_MODE == false and MARepeat_Mode == true)
if BullMAPlus
strategy.entry("Long", strategy.long, comment="X-Re🌙", alert_message = Alert_OpenLong)
if BearMAPlus
strategy.entry("Short", strategy.short, comment="X-Re👻", alert_message = Alert_OpenShort)
if MACDStrategy_MODE == true and MACDStrategy_Repeat == false
if macdTPl
strategy.entry("Long", strategy.long, comment="MACD🌙X", alert_message = Alert_OpenLong)
if macdTPs
strategy.entry("Short", strategy.short, comment="MACD👻X", alert_message = Alert_OpenShort)
if MACDStrategy_MODE == true and MACDStrategy_Repeat == true
if macdTPl or MACDBull
strategy.entry("Long", strategy.long, comment="MACD🌙X", alert_message = Alert_OpenLong)
if macdTPs or MACDBear
strategy.entry("Short", strategy.short, comment="MACD👻X", alert_message = Alert_OpenShort)
if MACDStrategy_MODE == false and MACDStrategy_Repeat == true
if MACDBull
strategy.entry("Long", strategy.long, comment="MACD🌙X", alert_message = Alert_OpenLong)
if MACDBear
strategy.entry("Short", strategy.short, comment="MACD👻X", alert_message = Alert_OpenShort)
else if Spot_MODE == true
if MACDConfirm_MODE == true
if BreakOut_MODE == true
if not na(close[lengthBO]) and MACDBull
strategy.entry("Long", strategy.long, stop=upBound + syminfo.mintick, comment="Break🌙MACD", alert_message = Alert_OpenLong)
if MACDBear
strategy.close_all(immediately = true, comment="Break👻MACD", alert_message = Alert_StopLosslong)
// ##### Consecutive Strategy #######
if (Consecutive_MODE ? ups >= consecutiveBarsUp : na) and MACDBull
strategy.entry("Long", strategy.long, comment="Up🌙MACD", alert_message = Alert_OpenLong)
if (Consecutive_MODE ? dns >= consecutiveBarsDown : na) and MACDBear
strategy.close_all(immediately = true, comment="Down👻MACD", alert_message = Alert_StopLosslong)
// ##### 15m Strategy ######
if (longCondition15) and MACDBull
strategy.entry("Long", strategy.long, alert_message = Alert_OpenLong, comment = "15m🌙MACD")
alert("15m BREAK UP", freq = alert.freq_once_per_bar_close)
if (shortCondition15) and MACDBear
strategy.close_all("15m BREAK DOWN", immediately = true, alert_message = Alert_StopLosslong)
alert("15m BREAK DOWN", freq = alert.freq_once_per_bar_close)
if MAStrategy_MODE == true and MARepeat_Mode == false
if BullMACross and MACDBull
strategy.entry("Long", strategy.long, comment="X🌙MACD", alert_message = Alert_OpenLong)
if BearMACross and MACDBear
strategy.close_all(immediately = true, comment="X👻MACD", alert_message = Alert_StopLosslong)
if (MAStrategy_MODE == true and MARepeat_Mode == true) or (MAStrategy_MODE == false and MARepeat_Mode == true)
if BullMAPlus and MACDBull
strategy.entry("Long", strategy.long, comment="X-Re🌙MACD", alert_message = Alert_OpenLong)
if BearMAPlus and MACDBear
strategy.close_all(immediately = true, comment="X👻MACD", alert_message = Alert_StopLosslong)
if MACDStrategy_MODE == true and MACDStrategy_Repeat == false
if macdTPl
strategy.entry("Long", strategy.long, comment="MACD🌙X", alert_message = Alert_OpenLong)
if macdTPs
strategy.close_all(immediately = true, comment="MACD👻X", alert_message = Alert_StopLosslong)
if MACDStrategy_MODE == true and MACDStrategy_Repeat == true
if macdTPl or MACDBull
strategy.entry("Long", strategy.long, comment="MACD🌙X", alert_message = Alert_OpenLong)
if macdTPs or MACDBear
strategy.close_all(immediately = true, comment="MACD👻X", alert_message = Alert_StopLosslong)
if MACDStrategy_MODE == false and MACDStrategy_Repeat == true
if MACDBull
strategy.entry("Long", strategy.long, comment="MACD🌙X", alert_message = Alert_OpenLong)
if MACDBear
strategy.close_all(immediately = true, comment="MACD👻X", alert_message = Alert_StopLosslong)
if RSIConfirm_MODE == true
if BreakOut_MODE == true
if not na(close[lengthBO]) and BULLRSI
strategy.entry("Long", strategy.long, stop=upBound + syminfo.mintick, comment="Break🌙RSI", alert_message = Alert_OpenLong)
if BEARRSI
strategy.close_all(immediately = true, comment="Break👻RSI", alert_message = Alert_StopLosslong)
// ##### Consecutive Strategy #######
if (Consecutive_MODE ? ups >= consecutiveBarsUp : na) and BULLRSI
strategy.entry("Long", strategy.long, comment="Up🌙RSI", alert_message = Alert_OpenLong)
if (Consecutive_MODE ? dns >= consecutiveBarsDown : na) and BEARRSI
strategy.close_all(immediately = true, comment="Down👻RSI", alert_message = Alert_StopLosslong)
// ##### 15m Strategy ######
if (longCondition15) and BULLRSI
strategy.entry("Long", strategy.long, alert_message = Alert_OpenLong, comment = "15m🌙RSI")
alert("15m BREAK UP", freq = alert.freq_once_per_bar_close)
if (shortCondition15) and BEARRSI
strategy.close_all("15m BREAK DOWN", immediately = true, alert_message = Alert_StopLosslong)
alert("15m BREAK DOWN", freq = alert.freq_once_per_bar_close)
if MAStrategy_MODE == true and MARepeat_Mode == false
if BullMACross and BULLRSI
strategy.entry("Long", strategy.long, comment="X🌙RSI", alert_message = Alert_OpenLong)
if BearMACross and BEARRSI
strategy.close_all(immediately = true, comment="X👻RSI", alert_message = Alert_StopLosslong)
if (MAStrategy_MODE == true and MARepeat_Mode == true) or (MAStrategy_MODE == false and MARepeat_Mode == true)
if BullMAPlus and BULLRSI
strategy.entry("Long", strategy.long, comment="X-Re🌙RSI", alert_message = Alert_OpenLong)
if BearMAPlus and BEARRSI
strategy.close_all(immediately = true, comment="X👻RSI", alert_message = Alert_StopLosslong)
if MACDStrategy_MODE == true and MACDStrategy_Repeat == false
if macdTPl and BULLRSI
strategy.entry("Long", strategy.long, comment="MACD🌙RSI", alert_message = Alert_OpenLong)
if macdTPs and BEARRSI
strategy.close_all(immediately = true, comment="MACD👻RSI", alert_message = Alert_StopLosslong)
if MACDStrategy_MODE == true and MACDStrategy_Repeat == true
if (macdTPl and BULLRSI) or (MACDBull and BULLRSI)
strategy.entry("Long", strategy.long, comment="MACD🌙RSI", alert_message = Alert_OpenLong)
if (macdTPs and BEARRSI) or (MACDBear and BEARRSI)
strategy.close_all(immediately = true, comment="MACD👻RSI", alert_message = Alert_StopLosslong)
if MACDStrategy_MODE == false and MACDStrategy_Repeat == true
if (MACDBull and BULLRSI)
strategy.entry("Long", strategy.long, comment="MACD🌙RSI", alert_message = Alert_OpenLong)
if (MACDBear and BEARRSI)
strategy.close_all(immediately = true, comment="MACD👻RSI", alert_message = Alert_StopLosslong)
if MACross_MODE == true
if BreakOut_MODE == true
if not na(close[lengthBO]) and BullMAPlus
strategy.entry("Long", strategy.long, stop=upBound + syminfo.mintick, comment="Break🌙MA", alert_message = Alert_OpenLong)
if BearMAPlus
strategy.close_all(immediately = true, comment="Break👻MA", alert_message = Alert_StopLosslong)
// ##### Consecutive Strategy #######
if (Consecutive_MODE ? ups >= consecutiveBarsUp : na) and BullMAPlus
strategy.entry("Long", strategy.long, comment="Up🌙MA", alert_message = Alert_OpenLong)
if (Consecutive_MODE ? dns >= consecutiveBarsDown : na) and BearMAPlus
strategy.close_all(immediately = true, comment="Down👻MA", alert_message = Alert_StopLosslong)
// ##### 15m Strategy ######
if (longCondition15) and BullMAPlus
strategy.entry("Long", strategy.long, alert_message = Alert_OpenLong, comment = "15m🌙MA")
alert("15m BREAK UP", freq = alert.freq_once_per_bar_close)
if (shortCondition15) and BearMAPlus
strategy.close_all("15m BREAK DOWN", immediately = true, alert_message = Alert_StopLosslong)
alert("15m BREAK DOWN", freq = alert.freq_once_per_bar_close)
if MACDStrategy_MODE == true and MACDStrategy_Repeat == false
if macdTPl and BullMAPlus
strategy.entry("Long", strategy.long, comment="MACD🌙MA", alert_message = Alert_OpenLong)
if macdTPs and BearMAPlus
strategy.close_all(immediately = true, comment="MACD👻MA", alert_message = Alert_StopLosslong)
if MACDStrategy_MODE == true and MACDStrategy_Repeat == true
if (macdTPl and BullMAPlus) or (MACDBull and BullMAPlus)
strategy.entry("Long", strategy.long, comment="MACD🌙MA", alert_message = Alert_OpenLong)
if (macdTPs and BearMAPlus) or (MACDBear and BearMAPlus)
strategy.close_all(immediately = true, comment="MACD👻MA", alert_message = Alert_StopLosslong)
if MACDStrategy_MODE == false and MACDStrategy_Repeat == true
if (MACDBull and BullMAPlus)
strategy.entry("Long", strategy.long, comment="MACD🌙MA", alert_message = Alert_OpenLong)
if (MACDBear and BearMAPlus)
strategy.close_all(immediately = true, comment="MACD👻MA", alert_message = Alert_StopLosslong)
if MAStrategy_MODE == true and MARepeat_Mode == false
if BullMACross
strategy.entry("Long", strategy.long, comment="X🌙MA", alert_message = Alert_OpenLong)
if BearMACross
strategy.close_all(immediately = true, comment="X👻MA", alert_message = Alert_StopLosslong)
if (MAStrategy_MODE == true and MARepeat_Mode == true) or (MAStrategy_MODE == false and MARepeat_Mode == true)
if BullMAPlus
strategy.entry("Long", strategy.long, comment="X-Re🌙MA", alert_message = Alert_OpenLong)
if BearMAPlus
strategy.close_all(immediately = true, comment="X👻MA", alert_message = Alert_StopLosslong)
if IchiConfirm_MODE == true
if BreakOut_MODE == true
if not na(close[lengthBO]) and ichi_bullplus
strategy.entry("Long", strategy.long, stop=upBound + syminfo.mintick, comment="Break🌙ICHI", alert_message = Alert_OpenLong)
if ichi_bearplus
strategy.close_all(immediately = true, comment="Break👻ICHI", alert_message = Alert_StopLosslong)
// ##### Consecutive Strategy #######
if (Consecutive_MODE ? ups >= consecutiveBarsUp : na) and ichi_bullplus
strategy.entry("Long", strategy.long, comment="Up🌙ICHI", alert_message = Alert_OpenLong)
if (Consecutive_MODE ? dns >= consecutiveBarsDown : na) and ichi_bearplus
strategy.close_all(immediately = true, comment="Down👻ICHI", alert_message = Alert_StopLosslong)
// ##### 15m Strategy ######
if (longCondition15) and ichi_bullplus
strategy.entry("Long", strategy.long, alert_message = Alert_OpenLong, comment = "15m🌙ICHI")
alert("15m BREAK UP", freq = alert.freq_once_per_bar_close)
if (shortCondition15) and ichi_bearplus
strategy.close_all("15m BREAK DOWN", immediately = true, alert_message = Alert_StopLosslong)
alert("15m BREAK DOWN", freq = alert.freq_once_per_bar_close)
if MAStrategy_MODE == true and MARepeat_Mode == false
if BullMACross and ichi_bullplus
strategy.entry("Long", strategy.long, comment="X🌙ICHI", alert_message = Alert_OpenLong)
if BearMACross and ichi_bearplus
strategy.close_all(immediately = true, comment="X👻ICHI", alert_message = Alert_StopLosslong)
if (MAStrategy_MODE == true and MARepeat_Mode == true) or (MAStrategy_MODE == false and MARepeat_Mode == true)
if BullMAPlus and ichi_bullplus
strategy.entry("Long", strategy.long, comment="X-Re🌙ICHI", alert_message = Alert_OpenLong)
if BearMAPlus and ichi_bearplus
strategy.close_all(immediately = true, comment="X👻ICHI", alert_message = Alert_StopLosslong)
if MACDStrategy_MODE == true and MACDStrategy_Repeat == false
if macdTPl and ichi_bullplus
strategy.entry("Long", strategy.long, comment="MACD🌙ICHI", alert_message = Alert_OpenLong)
if macdTPs and ichi_bearplus
strategy.close_all(immediately = true, comment="MACD👻ICHI", alert_message = Alert_StopLosslong)
if MACDStrategy_MODE == true and MACDStrategy_Repeat == true
if (macdTPl and ichi_bullplus) or (MACDBull and ichi_bullplus)
strategy.entry("Long", strategy.long, comment="MACD🌙ICHI", alert_message = Alert_OpenLong)
if (macdTPs and ichi_bearplus) or (MACDBear and ichi_bearplus)
strategy.close_all(immediately = true, comment="MACD👻ICHI", alert_message = Alert_StopLosslong)
if MACDStrategy_MODE == false and MACDStrategy_Repeat == true
if (MACDBull and ichi_bullplus)
strategy.entry("Long", strategy.long, comment="MACD🌙ICHI", alert_message = Alert_OpenLong)
if (MACDBear and ichi_bearplus)
strategy.close_all(immediately = true, comment="MACD👻ICHI", alert_message = Alert_StopLosslong)
if AroonConfirm_MODE == true
if BreakOut_MODE == true
if not na(close[lengthBO]) and AroonHitUp
strategy.entry("Long", strategy.long, stop=upBound + syminfo.mintick, comment="Break🌙AR", alert_message = Alert_OpenLong)
if AroonHitDown
strategy.close_all(immediately = true, comment="Break👻AR", alert_message = Alert_StopLosslong)
// ##### Consecutive Strategy #######
if (Consecutive_MODE ? ups >= consecutiveBarsUp : na) and AroonHitUp
strategy.entry("Long", strategy.long, comment="Up🌙AR", alert_message = Alert_OpenLong)
if (Consecutive_MODE ? dns >= consecutiveBarsDown : na) and AroonHitDown
strategy.close_all(immediately = true, comment="Down👻AR", alert_message = Alert_StopLosslong)
// ##### 15m Strategy ######
if (longCondition15) and AroonHitUp
strategy.entry("Long", strategy.long, alert_message = Alert_OpenLong, comment = "15m🌙AR")
alert("15m BREAK UP", freq = alert.freq_once_per_bar_close)
if (shortCondition15) and AroonHitDown
strategy.close_all("15m BREAK DOWN", immediately = true, alert_message = Alert_StopLosslong)
alert("15m BREAK DOWN", freq = alert.freq_once_per_bar_close)
if MAStrategy_MODE == true and MARepeat_Mode == false
if BullMACross and AroonHitUp
strategy.entry("Long", strategy.long, comment="X🌙AR", alert_message = Alert_OpenLong)
if BearMACross and AroonHitDown
strategy.close_all(immediately = true, comment="X👻AR", alert_message = Alert_StopLosslong)
if (MAStrategy_MODE == true and MARepeat_Mode == true) or (MAStrategy_MODE == false and MARepeat_Mode == true)
if BullMAPlus and AroonHitUp
strategy.entry("Long", strategy.long, comment="X-Re🌙AR", alert_message = Alert_OpenLong)
if BearMAPlus and AroonHitDown
strategy.close_all(immediately = true, comment="X👻AR", alert_message = Alert_StopLosslong)
if MACDStrategy_MODE == true and MACDStrategy_Repeat == false
if macdTPl and AroonHitUp
strategy.entry("Long", strategy.long, comment="MACD🌙AR", alert_message = Alert_OpenLong)
if macdTPs and AroonHitDown
strategy.close_all(immediately = true, comment="MACD👻AR", alert_message = Alert_StopLosslong)
if MACDStrategy_MODE == true and MACDStrategy_Repeat == true
if (macdTPl and AroonHitUp) or (MACDBull and AroonHitUp)
strategy.entry("Long", strategy.long, comment="MACD🌙AR", alert_message = Alert_OpenLong)
if (macdTPs and AroonHitDown) or (MACDBear and AroonHitDown)
strategy.close_all(immediately = true, comment="MACD👻AR", alert_message = Alert_StopLosslong)
if MACDStrategy_MODE == false and MACDStrategy_Repeat == true
if (MACDBull and AroonHitUp)
strategy.entry("Long", strategy.long, comment="MACD🌙AR", alert_message = Alert_OpenLong)
if (MACDBear and AroonHitDown)
strategy.close_all(immediately = true, comment="MACD👻AR", alert_message = Alert_StopLosslong)
if MACDConfirm_MODE == false and RSIConfirm_MODE == false and MACross_MODE == false and IchiConfirm_MODE == false and AroonConfirm_MODE == false
if BreakOut_MODE == true
if not na(close[lengthBO])
strategy.entry("Long", strategy.long, stop=upBound + syminfo.mintick, comment="Break🌙", alert_message = Alert_OpenLong)
strategy.exit("Long", qty_percent = 100,stop = downBound - syminfo.mintick,comment="Break👻", alert_message = Alert_StopLosslong)
// ##### Consecutive Strategy #######
if (Consecutive_MODE ? ups >= consecutiveBarsUp : na)
strategy.entry("Long", strategy.long, comment="Up🌙", alert_message = Alert_OpenLong)
if (Consecutive_MODE ? dns >= consecutiveBarsDown : na)
strategy.close_all(immediately = true, comment="Down👻", alert_message = Alert_StopLosslong)
// ##### 15m Strategy ######
if (longCondition15)
strategy.entry("Long", strategy.long, alert_message = Alert_OpenLong)
alert("15m BREAK UP", freq = alert.freq_once_per_bar_close)
if (shortCondition15)
strategy.close_all("15m BREAK DOWN", immediately = true, alert_message = Alert_StopLosslong)
alert("15m BREAK DOWN", freq = alert.freq_once_per_bar_close)
if MAStrategy_MODE == true and MARepeat_Mode == false
if BullMACross
strategy.entry("Long", strategy.long, comment="X🌙", alert_message = Alert_OpenLong)
if BearMACross
strategy.close_all(immediately = true, comment="X👻", alert_message = Alert_StopLosslong)
if (MAStrategy_MODE == true and MARepeat_Mode == true) or (MAStrategy_MODE == false and MARepeat_Mode == true)
if BullMAPlus
strategy.entry("Long", strategy.long, comment="X-Re🌙", alert_message = Alert_OpenLong)
if BearMAPlus
strategy.close_all(immediately = true, comment="X👻", alert_message = Alert_StopLosslong)
if MACDStrategy_MODE == true and MACDStrategy_Repeat == false
if macdTPl
strategy.entry("Long", strategy.long, comment="MACD🌙X", alert_message = Alert_OpenLong)
if macdTPs
strategy.close_all(immediately = true, comment="MACD👻X", alert_message = Alert_StopLosslong)
if MACDStrategy_MODE == true and MACDStrategy_Repeat == true
if macdTPl or MACDBull
strategy.entry("Long", strategy.long, comment="MACD🌙X", alert_message = Alert_OpenLong)
if macdTPs or MACDBear
strategy.close_all(immediately = true, comment="MACD👻X", alert_message = Alert_StopLosslong)
if MACDStrategy_MODE == false and MACDStrategy_Repeat == true
if MACDBull
strategy.entry("Long", strategy.long, comment="MACD🌙X", alert_message = Alert_OpenLong)
if MACDBear
strategy.close_all(immediately = true, comment="MACD👻X", alert_message = Alert_StopLosslong)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if Spot_MODE == false
if (strategy.position_size > 0)
if sl > 0
stoploss := calcStopLossPrice(sl)
stoploss_l := stoploss
else if sl <= 0
stoploss := na
if tp_l > 0
takeprofit := tp_l
takeprofit_ll := close + ((close/100)*tp_l)
//takeprofit_s := na
else if tp_l <= 0
takeprofit := na
if (strategy.position_size < 0)
if sl > 0
stoploss := calcStopLossPrice(sl)
stoploss_s := stoploss
else if sl <= 0
stoploss := na
if tp_s > 0
takeprofit := tp_s
takeprofit_ss := close - ((close/100)*tp_s)
//takeprofit_l := na
else if tp_s <= 0
takeprofit := na
else if strategy.position_size == 0
stoploss := na
takeprofit := na
if Spot_MODE == true
if (strategy.position_size > 0)
if sl > 0
stoploss := calcStopLossPrice(sl)
stoploss_l := stoploss
else if sl <= 0
stoploss := na
if tp_l > 0
takeprofit := tp_l
takeprofit_ll := close + ((close/100)*tp_l)
//takeprofit_s := na
else if tp_l <= 0
takeprofit := na
else if strategy.position_size == 0
stoploss := na
takeprofit := na
if mode == true and BOTrail_MODE == false
if Spot_MODE == false
if strategy.position_size > 0
//strategy.cancel_all()
strategy.exit("Exit",'Long', qty_percent = 100 , profit = takeprofit, stop = stoploss, alert_message = Alert_StopLosslong, comment_profit = "TP💚L", comment_loss = "SL💚L")
else if strategy.position_size < 0
//strategy.cancel_all()
strategy.exit("Exit",'Short', qty_percent = 100, profit = takeprofit, stop = stoploss, alert_message = Alert_StopLossshort, comment_profit = "TP❤️️S", comment_loss = "SL❤️️S")
else if Spot_MODE == true
if strategy.position_size > 0
//strategy.cancel_all()
strategy.exit("Exit",'Long', qty_percent = 100, profit = takeprofit, stop = stoploss, alert_message = Alert_StopLosslong, comment_profit = "TP💚L", comment_loss = "SL💚L")
else if BOTrail_MODE == true and mode == true
if Spot_MODE == false
if strategy.position_size > 0
//strategy.cancel_all()
strategy.exit("Exit",'Long', qty_percent = 100 , profit = takeprofit, loss = stoploss, alert_message = Alert_StopLosslong, comment_profit = "TP💚L", comment_loss = "SL💚L")
//if strategy.position_size > 0
//strategy.close("Long", qty_percent = 100, comment = "❇️CALLBACK❇️", immediately = true)
//if SL_ShortBO and strategy.position_size < 0
//if strategy.position_size < 0
//strategy.close("Short", qty_percent = 100, comment = "❇️CALLBACK❇️", immediately = true)
if strategy.position_size > 0 and SL_LongBO
strategy.close("Long", qty_percent = 100, comment = "❇️CALLBACK❇️", immediately = true)
if strategy.position_size < 0
//strategy.cancel_all()
strategy.exit("Exit",'Short', qty_percent = 100, profit = takeprofit, loss = stoploss, alert_message = Alert_StopLossshort, comment_profit = "TP❤️️S", comment_loss = "SL❤️️S")
if strategy.position_size < 0 and SL_ShortBO
strategy.close("Short", qty_percent = 100, comment = "❇️CALLBACK❇️", immediately = true)
else if Spot_MODE == true
//if SL_LongBO and strategy.position_size > 0
//if strategy.position_size > 0
// strategy.close("Long", qty_percent = 100, comment = "❇️CALLBACK❇️", immediately = true)
if strategy.position_size > 0
//strategy.cancel_all()
strategy.exit("Exit",'Long', qty_percent = 100 , profit = takeprofit, loss = stoploss, alert_message = Alert_StopLosslong, comment_profit = "TP💚L", comment_loss = "SL💚L")
if strategy.position_size > 0 and SL_LongBO
strategy.close("Long", qty_percent = 100, comment = "❇️CALLBACK❇️", immediately = true)
else if BOTrail_MODE == true and mode == false
if Spot_MODE == false
if strategy.position_size > 0 and SL_LongBO
//if strategy.position_size > 0
strategy.cancel_all()
strategy.close("Long", qty_percent = 100, comment = "❇️CALLBACK❇️", immediately = true)
//strategy.exit("Exit",'Long', qty_percent = 100 , profit = SL_LongBOPrice, alert_message = Alert_StopLosslong, comment_profit = "TP💚L")
//if strategy.position_size > 0
//strategy.close("Long", qty_percent = 100, comment = "❇️CALLBACK❇️", immediately = true)
//if SL_ShortBO and strategy.position_size < 0
//if strategy.position_size < 0
//strategy.close("Short", qty_percent = 100, comment = "❇️CALLBACK❇️", immediately = true)
if strategy.position_size < 0 and SL_ShortBO
//if strategy.position_size < 0
strategy.cancel_all()
strategy.close("Short", qty_percent = 100, comment = "❇️CALLBACK❇️", immediately = true)
//strategy.exit("Exit",'Short', qty_percent = 100, profit = SL_ShortBOPrice, alert_message = Alert_StopLossshort, comment_profit = "TP❤️️S")
if Spot_MODE == true
//if SL_LongBO and strategy.position_size > 0
//if strategy.position_size > 0
// strategy.close("Long", qty_percent = 100, comment = "❇️CALLBACK❇️", immediately = true)
if strategy.position_size > 0 and SL_LongBO
strategy.cancel_all()
//strategy.exit("Exit",'Long', qty_percent = 100 , profit = SL_LongBOPrice, alert_message = Alert_StopLosslong, comment_profit = "TP💚L")
strategy.close("Long", qty_percent = 100, comment = "❇️CALLBACK❇️", immediately = true)
if pnl_mode == true
if strategy.position_size > 0 and pnl_tp
strategy.cancel_all()
strategy.close_all(comment = "💵PNL TP💵", alert_message = Alert_StopLosslong)
if strategy.position_size < 0 and pnl_tp
strategy.cancel_all()
strategy.close_all(comment = "💵PNL TP💵", alert_message = Alert_StopLossshort)
if BungToon_Mode == true
if strategy.position_size > 0 and ticker_close_price <= entry_price
strategy.close("Long", qty_percent = 100, comment = "🙏BangToon🙏", immediately = true)
else if strategy.position_size < 0 and ticker_close_price >= entry_price
strategy.close("Short", qty_percent = 100, comment = "🙏BangToon🙏", immediately = true)
//===================== เรียกใช้ library =========================
import X4815162342/X48_LibaryStrategyStatus/2 as fuLi
//แสดงผล Backtest
show_Net = input.bool(true,'Monitor Profit&Loss', inline = 'Lnet', group = '= PNL MONITOR SETTING =')
position_ = input.string('bottom_center','Position', options = ['top_right','middle_right','bottom_right','top_center','middle_center','bottom_center','middle_left','bottom_left'] , inline = 'Lnet')
size_i = input.string('auto','size', options = ['auto','tiny','small','normal'] , inline = 'Lnet')
color_Net = input.color(color.blue,"" , inline = 'Lnet')
fuLi.NetProfit_Show(show_Net , position_ , size_i, color_Net )
|
Investments/swing trading strategy for different assets | https://www.tradingview.com/script/OePmdMFg/ | StrategiesForEveryone | https://www.tradingview.com/u/StrategiesForEveryone/ | 415 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Developed by © StrategiesForEveryone
//@version=5
strategy('Investments/swing trading strategy for different assets', overlay=true, process_orders_on_close=true, initial_capital = 100000, default_qty_type = strategy.cash, pyramiding = 1, precision = 2, calc_on_every_tick = true, commission_value = 0.05)
how_to_use = input.bool(defval=true, title="How to use the strategy ----->", group = "Information", tooltip = "When there is a buy signal at the end of the candle, buy. To close, you must wait for the candle to close, exit in breakeven or, failing that, exit through stop loss. Use the amounts and stop loss based on the values provided in the upper left corner by the indicator (choose the candlestick where the signal was produced to obtain the position information). Do not modify the parameters of the indicators as it is the most optimal setting for different assets from different markets. Use the info boxes to see more information about using the strategy")
// ------ Position amount calculator ------
initial_actual_capital_c = input.float(defval=1000000.0, title = "Initial/Actual Capital", group = "Position amount calculator", tooltip = "Enter the current amount of your capital. This amount will be used to calculate the size of your position that will be reflected in the upper left corner of the indicator. Remember that to change the amount in the back test you must go to properties. >>The amount in currency units is the green value<<")
risk_c = input.float(defval = 2.5, title = '% account risk per trade', step=1, group = "Position amount calculator")
// ------ Date filter ---------
initial_date = input.time(title="Initial date", defval=timestamp("01 Jan 1800 13:30 +0000"), group="Time filter", tooltip="Enter the start date and time of the strategy")
final_date = input.time(title="Final date", defval=timestamp("1 Jan 2030 19:30 +0000"), group="Time filter", tooltip="Enter the end date and time of the strategy")
dateFilter(int st, int et) => time >= st and time <= et
colorDate = input.bool(defval=false, title="Date background", tooltip = "Add color to the period of time of the strategy tester")
bgcolor(colorDate and dateFilter(initial_date, final_date) ? color.new(color.blue, transp=90) : na)
// ------ Session limits -------
timeSession = input.session(title="Time session", defval="0000-2400", group="Time filter", tooltip="Session time to operate. It may be different depending on your time zone, you have to find the correct hours manually.")
colorBG = input.bool(title="Session background", defval=false, tooltip = "Add color to session time background")
inSession(sess) => na(time(timeframe.period, sess + ':1234567')) == false
bgcolor(inSession(timeSession) and colorBG ? color.rgb(0, 38, 255, 84) : na)
// ------------------ Squeeze momentum Lazy Bear -----------------------
length = input(20, title='BB Length', group = "Squeeze Momentum", inline = "c")
mult = input(2.0, title='BB MultFactor', group = "Squeeze Momentum", inline = "c")
source = close
lengthKC = input(20, title='KC Length', group = "Squeeze Momentum", inline = "c")
multKC = input(1.5, title='KC MultFactor', group = "Squeeze Momentum", inline = "c")
useTrueRange = input(true, title='Use TrueRange (KC)', group = "Squeeze Momentum", inline = "c")
ma = ta.sma(source, length)
basis = ma
dev = mult * ta.stdev(source, length)
upperBB = basis + dev
lowerBB = basis - dev
range_1 = useTrueRange ? ta.tr : high - low
rangema = ta.sma(range_1, lengthKC)
upperKC = ma + rangema * multKC
lowerKC = ma - rangema * multKC
sqzOn = lowerBB > lowerKC and upperBB < upperKC
sqzOff = lowerBB < lowerKC and upperBB > upperKC
noSqz = sqzOn == false and sqzOff == false
val = ta.linreg(source - math.avg(math.avg(ta.highest(high, lengthKC), ta.lowest(low, lengthKC)), ta.sma(close, lengthKC)), lengthKC, 0)
iff_1 = val > nz(val[1]) ? #00ff00 : #008000
iff_2 = val < nz(val[1]) ? #FF0000 : #800000
bcolor = val > 0 ? iff_1 : iff_2
green_sqz = val > 0
red_sqz = val < 0
show_sqz = input.bool(defval=false, title = "Show squeeze momentum ?", group = "Appearance")
plot(show_sqz ? val : na, color=bcolor, style=plot.style_columns, linewidth=4, display = display.all-display.price_scale-display.status_line)
// ----------- Ema ----------------------
ema = input.int(200, title='Ema length', minval=1, maxval=500, group = "Trend")
ema200 = ta.ema(close, ema)
bullish = close > ema200
bearish = close < ema200
show_ema = input.bool(defval=true, title="Show Ema ?", group = "Appearance")
plot(show_ema ? ema200 : na, color=color.white, linewidth=2, display = display.all - display.status_line)
// --------------- Custom Rsi ------------------
overbought = input.int(70, title='Over bought line rsi', minval=50, maxval=100, group = "Rsi", inline = "b")
oversold = input.int(30, title='Over sold line rsi', minval=0, maxval=50, group = "Rsi", inline = "b")
periods = input.int(5, title='Rsi Length', minval=1, maxval=200, group = "Rsi", inline = "b")
rsi_filter = ta.rsi(close, periods)
show_rsi = input.bool(defval=false, title="Show Rsi ?", group = "Appearance")
plot(show_rsi ? rsi_filter : na, color=color.white, linewidth=2, display = display.all-display.price_scale-display.status_line-display.data_window)
hline(show_rsi ? overbought : na, color=color.green, linewidth = 1, display = display.all)
// --------- Macd -----------
// Getting inputs
fast_length = input(title="Fast Length", defval=16, group = "Macd")
slow_length = input(title="Slow Length", defval=26, group = "Macd")
src = input(title="Source", defval=close)
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 8, group = "Macd")
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"], group = "Macd")
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"], group = "Macd")
// Plot colors
col_macd = input(#2962FF, "MACD Line ", group="Color Settings", inline="MACD")
col_signal = input(#FF6D00, "Signal Line ", group="Color Settings", inline="Signal")
col_grow_above = input(#26A69A, "Above Grow", group="Histogram", inline="Above")
col_fall_above = input(#B2DFDB, "Fall", group="Histogram", inline="Above")
col_grow_below = input(#FFCDD2, "Below Grow", group="Histogram", inline="Below")
col_fall_below = input(#FF5252, "Fall", group="Histogram", inline="Below")
// Calculating
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal
//hline(0, "Zero Line", color=color.new(#787B86, 50))
show_macd = input.bool(defval=false, title = "Show Macd ?", group = "Appearance")
plot(show_macd ? hist : na, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)), display = display.all-display.price_scale-display.status_line-display.data_window)
//plot(macd, title="MACD", color=col_macd)
//plot(signal, title="Signal", color=col_signal)
// -------------- Atr stop loss by Gatherio -----------------
source_atr = input(close, title='Source', group = "Atr stop loss", inline = "A")
length_atr = input.int(14, minval=1, title='Period', group = "Atr stop loss" , inline = "A")
multiplier = input.float(1.6, minval=0.1, step=0.1, title='Atr multiplier', group = "Atr stop loss", inline = "A", tooltip = "Defines the stop loss distance based in the Atr stop loss indicator")
shortStopLoss = source_atr + ta.atr(length_atr) * multiplier
longStopLoss = source_atr - ta.atr(length_atr) * multiplier
atr_past_candle_buy = close[1] - ta.atr(length_atr)[1] * multiplier[1]
// ------- Money management ---------
strategy_contracts = strategy.equity / close
distance_sl_buy = -1 * (longStopLoss - close) / close
distance_sl_buy_past_candle = -1 * (atr_past_candle_buy - close) / close // distancia stop loss en porcentaje
risk = input.float(2.5, '% Account risk per trade for backtesting', step=1, group = "Risk management", tooltip = "Percentage of total account to risk per trade. >>The price of the stop loss is the red value<<. >>The distance of the stop loss is the orange value<<. It is recommended not to use more than 5%")
amount_1 = strategy_contracts * (risk / 100) / distance_sl_buy
amount_2 = strategy_contracts * (risk / 100) / distance_sl_buy_past_candle
// ------- Risk management ---------
risk_reward_breakeven = input.float(title='Risk reward for break even', defval=1.0, step=0.1, group = "Risk management", tooltip = "Risk/reward level to determine the target price to move the stop loss to the buy price (neither win nor lose). >>It is the light blue value<<")
var float sl = na
var float be_buy = na
var float tp_buy = na
var float stop_loss_distance = na
var float buy_amount = na
var float asset_amount = na
var float be_buy_calculator = na
var float stoploss_distance = na
leverage=input.bool(defval=false, title="Use leverage ?", group = "Risk management", tooltip = "If it is activated, there will be no monetary units or amount of assets limit for each operation (That is, each operation will not be affected by the initial / current capital since it would be using leverage). If it is deactivated, the monetary units or the amount of assets to use for each operation will be limited by the initial/current capital.")
if not leverage and amount_1>strategy_contracts
amount_1:=strategy.equity/close
if not leverage and amount_2>strategy_contracts
amount_2:=strategy.equity/close
// --------- Risk calculator --------------------------
number_of_contracts = initial_actual_capital_c / close
buy_amount_atr_actual_candle = close * (number_of_contracts * (risk_c / 100) / distance_sl_buy)
buy_amount_atr_past_candle = close * (number_of_contracts * (risk_c / 100) / distance_sl_buy_past_candle)
// Plot purchase currency units amount
if close>ema200
buy_amount:=close * (number_of_contracts * (risk / 100) / distance_sl_buy)
if close>ema200 and hist[0] > hist[1] and close[0] > close[1] and hist<0 and red_sqz and open[1]>ema200
buy_amount:= close * (number_of_contracts * (risk / 100) / distance_sl_buy_past_candle)
if close<ema200
buy_amount:=close * (number_of_contracts * (risk / 100) / distance_sl_buy)
if not leverage and buy_amount>initial_actual_capital_c
buy_amount:=initial_actual_capital_c
plot(buy_amount, display = display.all - display.pane, color=color.rgb(0, 255, 55), title="Amount purchase currency units")
// Plot stop loss price
draw_sl_be = input.bool(defval=true, title="Show stop loss and break even ?", group = "Appearance")
if close>ema200
sl:=longStopLoss
if close>ema200 and hist[0] > hist[1] and close[0] > close[1] and hist<0 and red_sqz and open[1]>ema200
sl:=atr_past_candle_buy
if close<ema200
sl:=longStopLoss
// Plot stop loss % distance
if close>ema200
stop_loss_distance:=(-1 * (longStopLoss - close) / close)*100
if close>ema200 and hist[0] > hist[1] and close[0] > close[1] and hist<0 and red_sqz and open[1]>ema200
stop_loss_distance:=(-1 * (atr_past_candle_buy - close) / close)*100
if close<ema200
stop_loss_distance:=(-1 * (longStopLoss - close) / close)*100
plot(stop_loss_distance, title="Stop loss % distance", color=color.rgb(255, 136, 0), display=display.all - display.pane)
// Plot break even
distance_stop_buy_break_even = close - longStopLoss
distance_stop_buy_break_even_past_candle = close - atr_past_candle_buy
be_buy_calculator:= close + distance_stop_buy_break_even * risk_reward_breakeven
if close>ema200
be_buy_calculator:= close + distance_stop_buy_break_even * risk_reward_breakeven
if close>ema200 and hist[0] > hist[1] and close[0] > close[1] and hist<0 and red_sqz and open[1]>ema200
be_buy_calculator:=close + distance_stop_buy_break_even_past_candle * risk_reward_breakeven
if close<ema200
be_buy_calculator:= close + distance_stop_buy_break_even * risk_reward_breakeven
// ------- Conditions for buying -----------
bought = strategy.position_size > 0
sold = strategy.position_size < 0
buy_rsi_signal = ta.crossover(rsi_filter, oversold) and red_sqz and bearish
buy_macd_signal = hist[0] > hist[1] and close[0] > close[1] and hist<0 and red_sqz and open[1]>ema200
sell_rsi_signal = ta.crossunder(rsi_filter, overbought) and green_sqz and bought
trend_sell_signal_sqz = ta.crossunder(val, 0)
trend_buy_signal_sqz = ta.crossover(val, 0) or (val>0 and (val[0] > val[1] and val[1] < val[2]))
positive_close=strategy.openprofit>0
information = input.bool(defval=true, title="Read ------>", group = "Final information", tooltip = "Thank you for using this model, I hope it can be very useful for you when making decisions in the short/medium and long term. Remember that it is not a crystal ball and it is not the Holy Grail of investments, it is just a model that seeks to adapt to different market situations to position yourself in favor of having the chances in your favor and making management much easier. Any questions you have about the model, feel free to ask :). Don't forget to leave your boost!")
againts_trend = input.bool(defval=false, title="Againts trend ?", group ="Risk management", tooltip = "Activate to trade when the price is below the EMA of 200 periods. It can be useful in certain assets or timeframes like weelky and risky in others")
break_even_with_rsi = input.bool(defval=false, title="Break even using rsi ?", group="Risk management", tooltip = "Activate to apply break even when rsi crosses under overbought line. It appears as a blue arrow")
var float sl_1 = na
var float sl_2 = na
var float sl_3 = na
if not bought
sl_1:=na
sl_2:=na
sl_3:=na
// --------- Use of strategy conditions ----------
// ------------------------ Sqz momentum signal ------------------------
// ---------------------- Againts Trend ----------------------
if trend_buy_signal_sqz and dateFilter(initial_date, final_date) and inSession(timeSession) and strategy.opentrades<1 and againts_trend
sl_1:=longStopLoss
stoploss_distance:= close - longStopLoss
be_buy := close + stoploss_distance * risk_reward_breakeven
strategy.entry("Buy", strategy.long, qty=amount_1)
strategy.exit("Cl Buy", "Buy", stop=sl_1)
if high > be_buy or sell_rsi_signal and positive_close and break_even_with_rsi
sl_1:=strategy.position_avg_price
strategy.exit("Cl Buy", "Buy", stop=sl_1)
if (bought and trend_sell_signal_sqz)
strategy.close("Buy", comment="Cl Buy")
//---------------In favor of the trend"---------------------
if trend_buy_signal_sqz and dateFilter(initial_date, final_date) and inSession(timeSession) and strategy.opentrades<1 and bullish and not againts_trend
sl_2:=longStopLoss
stoploss_distance:= close - longStopLoss
be_buy := close + stoploss_distance * risk_reward_breakeven
strategy.entry('Buy', strategy.long, qty=amount_1)
strategy.exit('Cl Buy', 'Buy', stop=sl_2)
if high > be_buy or sell_rsi_signal and positive_close and break_even_with_rsi
sl_2:=strategy.position_avg_price
strategy.exit("Cl Buy", "Buy", stop=sl_2)
if (trend_sell_signal_sqz)
strategy.close("Buy", comment="Cl Buy")
// ---------------------- Macd signal ----------------------------------------
if buy_macd_signal and dateFilter(initial_date, final_date) and inSession(timeSession) and bullish and strategy.opentrades<1
sl_3:=atr_past_candle_buy
stoploss_distance:= close - atr_past_candle_buy
be_buy := close + stoploss_distance * risk_reward_breakeven
strategy.entry('Buy.', strategy.long, qty=amount_2)
strategy.exit('Cl Buy.', 'Buy.', stop=sl_3)
if high > be_buy or sell_rsi_signal and positive_close and break_even_with_rsi
sl_3:=strategy.position_avg_price
strategy.exit("Cl Buy.", "Buy.", stop=sl_3)
if (trend_sell_signal_sqz)
strategy.close("Buy.", comment="Cl Buy.")
// ---------- Draw position on chart -------------
if high > be_buy
be_buy:=na
show_position_on_chart = input.bool(defval=true, title="Draw position on chart ?", group = "Appearance", tooltip = "Activate to graphically display profit, stop loss and break even")
position_price = plot(show_position_on_chart? strategy.position_avg_price : na, style=plot.style_linebr, color = color.new(#ffffff, 20), linewidth = 1, display = display.all - display.status_line)
break_even_price = plot(strategy.position_size>0 and high<be_buy and show_position_on_chart ? be_buy : na , style = plot.style_linebr, color = color.new(#41a3ff, 20), linewidth = 1, display = display.all - display.status_line)
sl1_price = plot(show_position_on_chart and bought and againts_trend ? sl_1 : na, style = plot.style_linebr, color = color.new(color.red, 20), linewidth = 1, display = display.all - display.status_line)
sl2_price = plot(show_position_on_chart and bought ? sl_2 : na, style = plot.style_linebr, color = color.new(color.red, 20), linewidth = 1, display = display.all - display.status_line)
sl3_price = plot(show_position_on_chart and bought ? sl_3 : na, style = plot.style_linebr, color = color.new(color.red, 20), linewidth = 1, display = display.all - display.status_line)
position_profit_price = plot(strategy.position_size>0 and show_position_on_chart and positive_close ? close : na, style = plot.style_linebr, color = color.new(color.green, 20), linewidth = 1, display = display.all - display.status_line)
fill(plot1 = position_price, plot2 = position_profit_price, color = color.new(color.green,90))
fill(plot1 = position_price, plot2 = sl1_price, color = color.new(color.red,90))
fill(plot1 = position_price, plot2 = sl2_price, color = color.new(color.red,90))
fill(plot1 = position_price, plot2 = sl3_price, color = color.new(color.red,90))
// --------- Strategy as indicator -----------
show_signals = input.bool(defval=true, title="Draw signals on chart ?", group = "Appearance")
plot(draw_sl_be and trend_buy_signal_sqz and not bought or draw_sl_be and buy_macd_signal and not bought? sl : na, title="Stop loss price", color=color.rgb(255, 255, 255), linewidth=1, style=plot.style_circles, display=display.all - display.price_scale)
plot(draw_sl_be and trend_buy_signal_sqz and not bought or draw_sl_be and buy_macd_signal and not bought? be_buy_calculator : na, title="Target price for break event", color=color.rgb(72, 210, 245), linewidth=1, style=plot.style_circles, display=display.all - display.price_scale)
plotshape(show_signals and break_even_with_rsi and bought? sell_rsi_signal : na, style = shape.triangledown, color = color.blue, size = size.tiny, display = display.all - display.price_scale - display.status_line)
|
Baseline Cross Qualifier Volatility Strategy with HMA Trend Bias | https://www.tradingview.com/script/QF1wKN1V-Baseline-Cross-Qualifier-Volatility-Strategy-with-HMA-Trend-Bias/ | sevencampbell | https://www.tradingview.com/u/sevencampbell/ | 127 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © sevencampbell
//@version=5
strategy(title="Baseline Cross Qualifier Volatility Strategy with HMA Trend Bias", overlay=true)
// --- User Inputs ---
// Baseline Inputs
baselineLength = input.int(title="Baseline Length", defval=20)
baseline = ta.sma(close, baselineLength)
// PBCQ Inputs
pbcqEnabled = input.bool(title="Post Baseline Cross Qualifier Enabled", defval=true)
pbcqBarsAgo = input.int(title="Post Baseline Cross Qualifier Bars Ago", defval=3)
// Volatility Inputs
atrLength = input.int(title="ATR Length", defval=14)
multiplier = input.float(title="Volatility Multiplier", defval=2.0)
rangeMultiplier = input.float(title="Volatility Range Multiplier", defval=1.0)
qualifierMultiplier = input.float(title="Volatility Qualifier Multiplier", defval=0.5)
// Take Profit Inputs
takeProfitType = input.string(title="Take Profit Type", options=["1 Take Profit", "2 Take Profits", "3 Take Profits"], defval="1 Take Profit")
// HMA Inputs
hmaLength = input.int(title="HMA Length", defval=50)
// --- Calculations ---
// ATR
atr = ta.atr(atrLength)
// Range Calculation
rangeHigh = baseline + rangeMultiplier * atr
rangeLow = baseline - rangeMultiplier * atr
rangeColor = rangeLow <= close and close <= rangeHigh ? color.yellow : na
bgcolor(rangeColor, transp=90)
// Qualifier Calculation
qualifier = qualifierMultiplier * atr
// Dot Calculation
isLong = close > baseline and (close - baseline) >= qualifier and close > ta.hma(close, hmaLength)
isShort = close < baseline and (baseline - close) >= qualifier and close < ta.hma(close, hmaLength)
colorDot = isLong ? color.green : isShort ? color.red : na
plot(isLong or isShort ? baseline : na, color=colorDot, style=plot.style_circles, linewidth=3)
// --- Strategy Logic ---
// PBCQ
pbcqValid = not pbcqEnabled or low[pbcqBarsAgo] > baseline
// Entry Logic
longCondition = isLong and pbcqValid
shortCondition = isShort and pbcqValid
if (longCondition)
strategy.entry("Long", strategy.long)
if (shortCondition)
strategy.entry("Short", strategy.short)
// Exit Logic
if (takeProfitType == "1 Take Profit")
strategy.exit("TP/SL", "Long", limit=rangeHigh, stop=rangeLow)
strategy.exit("TP/SL", "Short", limit=rangeLow, stop=rangeHigh)
else if (takeProfitType == "2 Take Profits")
strategy.exit("TP1", "Long", qty=strategy.position_size * 0.5, limit=rangeHigh / 2)
strategy.exit("TP2", "Long", qty=strategy.position_size * 0.5, limit=rangeHigh)
strategy.exit("TP1", "Short", qty=strategy.position_size * 0.5, limit=rangeLow / 2)
strategy.exit("TP2", "Short", qty=strategy.position_size * 0.5, limit=rangeLow)
else if (takeProfitType == "3 Take Profits")
strategy.exit("TP1", "Long", qty=strategy.position_size * 0.5, limit=rangeHigh / 2)
strategy.exit("TP2", "Long", qty=strategy.position_size * 0.25, limit=rangeHigh * 0.75)
strategy.exit("TP3", "Long", qty=strategy.position_size * 0.25, limit=rangeHigh * 1.5)
|
Divergence for Many [Dimkud - v5] | https://www.tradingview.com/script/C8cpBFWm-Divergence-for-Many-Dimkud-v5/ | dimkud | https://www.tradingview.com/u/dimkud/ | 549 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Strategy based on "Divergence for Many Indicators v4 ST" by CannyTolany01
// which is based on "Divergence for Many Indicator" indicator by LonesomeTheBlue
//@version=5
strategy('Divergence for Many [Dimkud - v5]', overlay=true, calc_on_order_fills=true, commission_type=strategy.commission.percent, commission_value=0.04, default_qty_type=strategy.cash, default_qty_value=200, initial_capital=1000)
// DIMAK Static SL/TP - Begin
GRUPO_statSLTP = 'Static SL/TP'
USEdisplTPSL = input(defval=false, title='Display Visualisation for TP/SL ?', group = GRUPO_statSLTP)
enable_long_strategy = input.bool(false, title='Use Long ?', group=GRUPO_statSLTP, inline='11')
enable_short_strategy = input.bool(true, title='Use Short ?', group=GRUPO_statSLTP, inline='11')
SLsameTP = input.bool(false, 'SL = TP ?', group=GRUPO_statSLTP)
USE_SignSL = input.bool(false, 'Use Opposite Signal SL ?', group=GRUPO_statSLTP)
USEorderOnSL = input(defval=false, title='New Opposite-Order after SL ?', group = GRUPO_statSLTP, tooltip = 'After SL - create new order with with opposite direction')
longProfitPerc = input.float(defval=0.9, title='Take Profit (%)', group=GRUPO_statSLTP, minval=0.0, step=0.1) / 100
longSLPerc = input.float(defval=0.9, title='Stop Loss (%)', group=GRUPO_statSLTP, minval=0.0, step=0.1) / 100
longSLPerc := SLsameTP ? longProfitPerc : longSLPerc
shortProfitPerc = longProfitPerc
shortSLPerc = longSLPerc
longExitPrice = strategy.position_avg_price * (1 + longProfitPerc)
shortExitPrice = strategy.position_avg_price * (1 - shortProfitPerc)
longSLExitPrice = strategy.position_avg_price * (1 - longSLPerc)
shortSLExitPrice = strategy.position_avg_price * (1 + shortSLPerc)
// use such: limit=shortExitPrice, stop=shortSLExitPrice
// DIMAK Static SL/TP - END
// ===================================================================================================
// DIMAK - TimeFrame request.security - Repaint-Non Repaint
f_security(_sym, _res, _src, _rep) =>
request.security(_sym, _res, _src[not _rep and barstate.isrealtime ? 1 : 0])[_rep or barstate.isrealtime ? 0 : 1]
// DIMAK - TimeFrame request.security - Repaint-Non Repaint
// Time filter =================================
grTIMEset = "Testing Period"
testPeriod() =>
// Testing Start dates
testStartYear = input.int(2022, 'Start Year', inline='date1', group=grTIMEset)
testStartMonth = input.int(5, '', inline='date1', group=grTIMEset)
testStartDay = input.int(1, '', inline='date1', group=grTIMEset)
testPeriodStart = timestamp(testStartYear, testStartMonth, testStartDay, 0, 0)
//Stop date if you want to use a specific range of dates
testStopYear = input.int(2030, 'Stop Year', inline='date2', group=grTIMEset)
testStopMonth = input.int(12, '', inline='date2', group=grTIMEset)
testStopDay = input.int(30, '', inline='date2', group=grTIMEset)
testPeriodStop = timestamp(testStopYear, testStopMonth, testStopDay, 0, 0)
time >= testPeriodStart and time < testPeriodStop ? true : false
// pass some date
//testPeriodStop2 = timestamp(2022,6,14,0,0)
//testPeriodStop3 = timestamp(2022,6,16,0,0)
//(time >= testPeriodStart) and (time < testPeriodStop) and ((time < testPeriodStop2) or (time > testPeriodStop3)) ? true : false
// Time filter =================================
grMAINset = "Main Divergence Settings"
prd = input.int(defval=9, title='Pivot Period(9)', minval=1, maxval=50, group = grMAINset)
source = input.string(defval='Close', title='Source for Pivot Points', options=['Close', 'High/Low'], group = grMAINset)
//searchdiv = input.string(defval='Regular', title='Divergence Type', options=['Regular', 'Hidden', 'Regular/Hidden'], group = grMAINset)
// works only Regular
searchdiv = 'Regular'
showindis = input.string(defval='Don\'t Show', title='Show Indicator Names', options=['Full', 'First Letter', 'Don\'t Show'], group = grMAINset)
//showlimit = input.int(1, title='Minimum Number of Divergence', minval=1, maxval=11)
// not good results and not work now
showlimit = 1
maxpp = input.int(defval=10, title='Maximum Pivot Points to Check', minval=10, maxval=20, group = grMAINset)
maxbars = input.int(defval=100, title='Maximum Bars to Check', minval=100, maxval=200, group = grMAINset)
shownum = input(defval=true, title='Show Divergence Number', group = grMAINset)
showlast = input(defval=false, title='Show Only Last Divergence', group = grMAINset)
dontconfirm = input(defval=false, title='Don\'t Wait for Confirmation', group = grMAINset)
showlines = input(defval=false, title='Show Divergence Lines', group = grMAINset)
showpivot = input(defval=false, title='Show Pivot Points', group = grMAINset)
// declaration
macd = 0.0
deltamacd = 0.0
rsi = 0.0
stk = 0.0
cci = 0.0
moment = 0.0
Obv = 0.0
vwmacd = 0.0
cmf = 0.0
Mfi = 0.0
aStDev = 0.0
wvf = 0.0
StochRSIk = 0.0
oscSMIO = 0.0
dmVWMACD_LB = 0.0
BBPower = 0.0
SmootherBOP = 0.0
rviMA = 0.0
// declaration
calcmacd = input(defval=true, title='MACD')
dimmacdFast = input.int(defval=12, title='Fast(12):', minval=1, maxval=70, inline='223')
dimmacdSlow = input.int(defval=26, title='Slow(26):', minval=1, maxval=70, inline='223')
dimmacdSignal = input.int(defval=9, title='Sign(9):', minval=1, maxval=70, inline='223')
calcmacda = input(defval=true, title='MACD Histogram')
if calcmacd or calcmacda
//[macd, signal, deltamacd] = macd(close, 12, 26, 9) // MACD
[macd2, signal, deltamacd2] = ta.macd(close, dimmacdFast, dimmacdSlow, dimmacdSignal) // MACD
macd := macd2
deltamacd := deltamacd2
deltamacd
calcrsi = input(defval=true, title='RSI')
dimRSI = input.int(defval=14, title='RSI period (14):', minval=1, maxval=70)
if calcrsi
//rsi = rsi(close, 14) // RSI
rsi := ta.rsi(close, dimRSI) // RSI
rsi
calcstoc = input(defval=true, title='Stochastic')
dimSTOCHlength = input.int(defval=14, title='STOCH Length(14):', minval=1, maxval=70)
if calcstoc
//stk = sma(stoch(close, high, low, 14), 3) // Stoch
stk := ta.sma(ta.stoch(close, high, low, dimSTOCHlength), 3) // Stoch
stk
calccci = input(defval=true, title='CCI')
dimCCIL = input.int(defval=10, title='CCI Length(10)', minval=1, maxval=70, inline='')
if calccci
//cci = cci(close, 10) // CCI
cci := ta.cci(close, dimCCIL) // CCI
cci
calcmom = input(defval=true, title='Momentum')
dimmomentL = input.int(defval=10, title='Momentum Length(10)', minval=1, maxval=70, inline='')
if calcmom
//moment = mom(close, 10) // Momentum
moment := ta.mom(close, dimmomentL) // Momentum
moment
calcobv = input(defval=true, title='OBV')
if calcobv
Obv := ta.obv // OBV
Obv
calcvwmacd = input(true, title='VWmacd')
dimmaFast = input.int(defval=12, title='Volume Weighted Macd. Fast(12)', minval=1, maxval=70, inline='112')
dimmaSlow = input.int(defval=26, title='Slow(26)', minval=1, maxval=70, inline='112')
if calcvwmacd
//maFast = vwma(close, 12), maSlow = vwma(close, 26), vwmacd = maFast - maSlow // volume weighted macd
maFast = ta.vwma(close, dimmaFast)
maSlow = ta.vwma(close, dimmaSlow)
vwmacd := maFast - maSlow // volume weighted macd
vwmacd
calccmf = input(true, title='Chaikin Money Flow')
dimCMFperiod = input.int(defval=21, title='CMF period(21)', minval=1, maxval=70, inline='')
if calccmf
//Cmfm = ((close-low) - (high-close)) / (high - low), Cmfv = Cmfm * volume, cmf = sma(Cmfv, 21) / sma(volume,21) // Chaikin money flow
Cmfm = (close - low - (high - close)) / (high - low)
Cmfv = Cmfm * volume
cmf := ta.sma(Cmfv, dimCMFperiod) / ta.sma(volume, dimCMFperiod) // Chaikin money flow
cmf
calcmfi = input(true, title='Money Flow Index')
dimMfilength = input.int(defval=14, title='Mfi length(14)', minval=1, maxval=70, inline='')
if calcmfi
//Mfi = mfi(close, 14) // Moneyt Flow Index
Mfi := ta.mfi(close, dimMfilength) // Moneyt Flow Index
Mfi
//==================================================================================
calcWVIX = input(true, title='Williams_Vix_Fix')
pd = input(21, title='Williams_Vix_Fix Period(21)')
if calcWVIX
wvf := (ta.highest(close, pd) - low) / ta.highest(close, pd) * -100
wvf
//==================================================================================
calcStochRSI = input.bool(true, title='Use Stochastic RSI ?', group='Stochastic RSI')
smoothK = input.int(3, 'Stochastic K(3)', minval=1, group='Stochastic RSI')
lengthSTRSI = input.int(14, 'RSI Length(14)', minval=1, group='Stochastic RSI')
lengthStoch = input.int(14, 'Stochastic Length(14)', minval=1, group='Stochastic RSI')
if calcStochRSI
rsi1 = ta.rsi(close, lengthSTRSI)
StochRSIk := ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
StochRSIk
//==================================================================================
calcSMIO = input.bool(true, title='Use SMIO ?', group='SMI Ergodic Oscillator')
longlenSMIO = input.int(20, minval=1, title='Long Length(20)', group='SMI Ergodic Oscillator')
shortlenSMIO = input.int(5, minval=1, title='Short Length(5)', group='SMI Ergodic Oscillator')
siglenSMIO = input.int(5, minval=1, title='Signal Line Length(5)', group='SMI Ergodic Oscillator')
if calcSMIO
ergSMIO = ta.tsi(close, shortlenSMIO, longlenSMIO)
sigSMIO = ta.ema(ergSMIO, siglenSMIO)
oscSMIO := ergSMIO - sigSMIO
oscSMIO
//==================================================================================
calcVWMACD_LB = input.bool(true, title='Use VWMACD_LB ?', group='Volume Weighted MACD [LazyBear]')
slowVWMACD_LB = input.int(12, 'Short period(12)', minval=1)
fastVWMACD_LB = input.int(26, 'Long period(26)', minval=1)
signalVWMACD_LB = input.int(9, 'Smoothing period(9)', minval=1)
if calcVWMACD_LB
maFastVWMACD_LB = ta.ema(volume * close, fastVWMACD_LB) / ta.ema(volume, fastVWMACD_LB)
maSlowVWMACD_LB = ta.ema(volume * close, slowVWMACD_LB) / ta.ema(volume, slowVWMACD_LB)
dVWMACD_LB = maSlowVWMACD_LB - maFastVWMACD_LB
maSignalVWMACD_LB = ta.ema(dVWMACD_LB, signalVWMACD_LB)
dmVWMACD_LB := dVWMACD_LB - maSignalVWMACD_LB
dmVWMACD_LB
//==================================================================================
calcBBP = input.bool(true, title='Use BBP', group='Bull Bear Power')
lengthInputBBP = input.int(13, title='BBP Length(13)', minval=1, group='Bull Bear Power')
if calcBBP
bullPowerBBP = high - ta.ema(close, lengthInputBBP)
bearPowerBBP = low - ta.ema(close, lengthInputBBP)
BBPower := bullPowerBBP + bearPowerBBP
BBPower
//==================================================================================
calcBOP = input.bool(true, title='Use BOP', group='Balance of Power')
EMA = input.int(20, 'BOP Smooth Length(20)', minval=1, group='Balance of Power')
TEMA = input.int(20, 'TRIPLE Smooth Length(20)', minval=1, group='Balance of Power')
if calcBOP
THL = high != low ? high - low : 0.01
BullOpen = (high - open) / THL
BearOpen = (open - low) / THL
BullClose = (close - low) / THL
BearClose = (high - close) / THL
BullOC = close > open ? (close - open) / THL : 0
BearOC = open > close ? (open - close) / THL : 0
BullReward = (BullOpen + BullClose + BullOC) / 3
BearReward = (BearOpen + BearClose + BearOC) / 3
BOP = BullReward - BearReward
SmoothBOP = ta.ema(BOP, EMA)
xEMA1 = ta.ema(SmoothBOP, TEMA)
xEMA2 = ta.ema(xEMA1, TEMA)
xEMA3 = ta.ema(xEMA2, TEMA)
nRes = 3 * xEMA1 - 3 * xEMA2 + xEMA3
SmootherBOP := nRes
SmootherBOP
//==================================================================================
calcRVI = input.bool(true, title='Use RVI', group='Relative Volatility Index')
lengthRVI = input.int(10, title='RVI length(10)', minval=1, group='Relative Volatility Index')
maTypeInput = input.string('WMA', title='MA Type', options=['SMA', 'EMA', 'SMMA (RMA)', 'WMA', 'VWMA'], group='Relative Volatility Index')
maLengthInput = input.int(14, title='MA Length(14)', group='Relative Volatility Index')
if calcRVI
stddevRVI = ta.stdev(close, lengthRVI)
upperRVI = ta.ema(ta.change(close) <= 0 ? 0 : stddevRVI, 14)
lowerRVI = ta.ema(ta.change(close) > 0 ? 0 : stddevRVI, 14)
rviRVI = upperRVI / (upperRVI + lowerRVI) * 100
rviMA := maTypeInput == 'SMA' ? ta.sma(rviRVI, maLengthInput) : maTypeInput == 'EMA' ? ta.ema(rviRVI, maLengthInput) : maTypeInput == 'SMMA (RMA)' ? ta.rma(rviRVI, maLengthInput) : maTypeInput == 'WMA' ? ta.wma(rviRVI, maLengthInput) : maTypeInput == 'VWMA' ? ta.vwma(rviRVI, maLengthInput) : ta.wma(rviRVI, maLengthInput)
rviMA
//==================================================================================
// Logistic Dominance
calcLD = input.bool(true, title='Logistic Dominance', group='Logistic Settings')
source2 = close
length = input.int(13, 'Map Length(13)', minval=1, inline='LOG', group='Logistic Settings')
lenLD = input.int(5, 'Dominance(5)', minval=1, inline='LOG', group='Logistic Settings')
f_logmap(_s, _r, _l) =>
_r * _s / ta.highest(_l) * (1 - _s / ta.highest(_l))
f_map(_s, _r, _v) =>
mapeq = f_logmap(_s, _r, length)
lmap = mapeq
for i = 0 to 29 by 1
array.push(_v, lmap)
lmap := _r * math.abs(mapeq[i]) * (1 - mapeq[i])
lmap
lmap
if calcLD
r = -f_logmap(-source2, ta.change(source2, lenLD) / source2[lenLD], lenLD) - f_logmap(source2, ta.change(source2, lenLD) / source2[lenLD], lenLD)
var v = array.new_float(0)
val = f_map(source2, r, v)
array.remove(v, 0)
aStDev := math.sign(array.avg(v)) * array.stdev(v)
array.clear(v)
// Logistic Dominance
//==================================================================================
calcext = input(false, title='Check External Indicator')
externalindi = input(defval=close, title='External Indicator')
pos_reg_div_col = input(defval=color.yellow, title='Positive Regular Divergence')
neg_reg_div_col = input(defval=color.navy, title='Negative Regular Divergence')
pos_hid_div_col = input(defval=color.lime, title='Positive Hidden Divergence')
neg_hid_div_col = input(defval=color.red, title='Negative Hidden Divergence')
pos_div_text_col = input(defval=color.black, title='Positive Divergence Text Color')
neg_div_text_col = input(defval=color.white, title='Negative Divergence Text Color')
reg_div_l_style_ = input.string(defval='Solid', title='Regular Divergence Line Style', options=['Solid', 'Dashed', 'Dotted'])
hid_div_l_style_ = input.string(defval='Dashed', title='Hdden Divergence Line Style', options=['Solid', 'Dashed', 'Dotted'])
reg_div_l_width = input.int(defval=2, title='Regular Divergence Line Width', minval=1, maxval=5)
hid_div_l_width = input.int(defval=1, title='Hidden Divergence Line Width', minval=1, maxval=5)
showmas = input.bool(defval=false, title='Show MAs 50 & 200', inline='ma12')
cma1col = input.color(defval=color.lime, title='', inline='ma12')
cma2col = input.color(defval=color.red, title='', inline='ma12')
plot(showmas ? ta.sma(close, 50) : na, color=showmas ? cma1col : na)
plot(showmas ? ta.sma(close, 200) : na, color=showmas ? cma2col : na)
// set line styles
var reg_div_l_style = reg_div_l_style_ == 'Solid' ? line.style_solid : reg_div_l_style_ == 'Dashed' ? line.style_dashed : line.style_dotted
var hid_div_l_style = hid_div_l_style_ == 'Solid' ? line.style_solid : hid_div_l_style_ == 'Dashed' ? line.style_dashed : line.style_dotted
// keep indicators names and colors in arrays
// !!!!!!!! DIMAK - add num of Indicators +1
var indicators_name = array.new_string(19)
var div_colors = array.new_color(4)
if barstate.isfirst
// names
array.set(indicators_name, 0, showindis == 'Full' ? 'MACD' : 'M')
array.set(indicators_name, 1, showindis == 'Full' ? 'Hist' : 'H')
array.set(indicators_name, 2, showindis == 'Full' ? 'RSI' : 'E')
array.set(indicators_name, 3, showindis == 'Full' ? 'Stoch' : 'S')
array.set(indicators_name, 4, showindis == 'Full' ? 'CCI' : 'C')
array.set(indicators_name, 5, showindis == 'Full' ? 'MOM' : 'M')
array.set(indicators_name, 6, showindis == 'Full' ? 'OBV' : 'O')
array.set(indicators_name, 7, showindis == 'Full' ? 'VWMACD' : 'V')
array.set(indicators_name, 8, showindis == 'Full' ? 'CMF' : 'C')
array.set(indicators_name, 9, showindis == 'Full' ? 'MFI' : 'M')
array.set(indicators_name, 10, showindis == 'Full' ? 'Extrn' : 'X')
array.set(indicators_name, 11, showindis == 'Full' ? 'Logist' : 'L')
array.set(indicators_name, 12, showindis == 'Full' ? 'WVIX' : 'VIX')
array.set(indicators_name, 13, showindis == 'Full' ? 'StochRSI' : 'SR')
array.set(indicators_name, 14, showindis == 'Full' ? 'calcSMIO' : 'SM')
array.set(indicators_name, 15, showindis == 'Full' ? 'VWMACD_LB' : 'VWM')
array.set(indicators_name, 16, showindis == 'Full' ? 'BBP' : 'BBP')
array.set(indicators_name, 17, showindis == 'Full' ? 'BOP' : 'BOP')
array.set(indicators_name, 18, showindis == 'Full' ? 'RVI' : 'RVI')
// !!!!!!!!!!! DIMAK - num of Ind +1
//colors
array.set(div_colors, 0, pos_reg_div_col)
array.set(div_colors, 1, neg_reg_div_col)
array.set(div_colors, 2, pos_hid_div_col)
array.set(div_colors, 3, neg_hid_div_col)
// Check if we get new Pivot High Or Pivot Low
float ph = ta.pivothigh(source == 'Close' ? close : high, prd, prd)
float pl = ta.pivotlow(source == 'Close' ? close : low, prd, prd)
plotshape(ph and showpivot, text='H', style=shape.labeldown, color=color.new(color.white, 100), textcolor=color.new(color.red, 0), location=location.abovebar, offset=-prd)
plotshape(pl and showpivot, text='L', style=shape.labelup, color=color.new(color.white, 100), textcolor=color.new(color.lime, 0), location=location.belowbar, offset=-prd)
// keep values and positions of Pivot Highs/Lows in the arrays
var int maxarraysize = 20
var ph_positions = array.new_int(maxarraysize, 0)
var pl_positions = array.new_int(maxarraysize, 0)
var ph_vals = array.new_float(maxarraysize, 0.)
var pl_vals = array.new_float(maxarraysize, 0.)
// add PHs to the array
if ph
array.unshift(ph_positions, bar_index)
array.unshift(ph_vals, ph)
if array.size(ph_positions) > maxarraysize
array.pop(ph_positions)
array.pop(ph_vals)
// add PLs to the array
if pl
array.unshift(pl_positions, bar_index)
array.unshift(pl_vals, pl)
if array.size(pl_positions) > maxarraysize
array.pop(pl_positions)
array.pop(pl_vals)
// functions to check Regular Divergences and Hidden Divergences
// function to check positive regular or negative hidden divergence
// cond == 1 => positive_regular, cond == 2=> negative_hidden
positive_regular_positive_hidden_divergence(src, cond) =>
divlen = 0
prsc = source == 'Close' ? close : low
// if indicators higher than last value and close price is higher than las close
if dontconfirm or src > src[1] or close > close[1]
startpoint = dontconfirm ? 0 : 1 // don't check last candle
// we search last 15 PPs
for x = 0 to maxpp - 1 by 1
len = bar_index - array.get(pl_positions, x) + prd
// if we reach non valued array element or arrived 101. or previous bars then we don't search more
if array.get(pl_positions, x) == 0 or len > maxbars
break
if len > 5 and (cond == 1 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(pl_vals, x)) or cond == 2 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(pl_vals, x)))
slope1 = (src[startpoint] - src[len]) / (len - startpoint)
virtual_line1 = src[startpoint] - slope1
slope2 = (close[startpoint] - close[len]) / (len - startpoint)
virtual_line2 = close[startpoint] - slope2
arrived = true
for y = 1 + startpoint to len - 1 by 1
if src[y] < virtual_line1 or nz(close[y]) < virtual_line2
arrived := false
break
virtual_line1 -= slope1
virtual_line2 -= slope2
virtual_line2
if arrived
divlen := len
break
divlen
// function to check negative regular or positive hidden divergence
// cond == 1 => negative_regular, cond == 2=> positive_hidden
negative_regular_negative_hidden_divergence(src, cond) =>
divlen = 0
prsc = source == 'Close' ? close : high
// if indicators higher than last value and close price is higher than las close
if dontconfirm or src < src[1] or close < close[1]
startpoint = dontconfirm ? 0 : 1 // don't check last candle
// we search last 15 PPs
for x = 0 to maxpp - 1 by 1
len = bar_index - array.get(ph_positions, x) + prd
// if we reach non valued array element or arrived 101. or previous bars then we don't search more
if array.get(ph_positions, x) == 0 or len > maxbars
break
if len > 5 and (cond == 1 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(ph_vals, x)) or cond == 2 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(ph_vals, x)))
slope1 = (src[startpoint] - src[len]) / (len - startpoint)
virtual_line1 = src[startpoint] - slope1
slope2 = (close[startpoint] - nz(close[len])) / (len - startpoint)
virtual_line2 = close[startpoint] - slope2
arrived = true
for y = 1 + startpoint to len - 1 by 1
if src[y] > virtual_line1 or nz(close[y]) > virtual_line2
arrived := false
break
virtual_line1 -= slope1
virtual_line2 -= slope2
virtual_line2
if arrived
divlen := len
break
divlen
// calculate 4 types of divergence if enabled in the options and return divergences in an array
calculate_divs(cond, indicator_1) =>
divs = array.new_int(4, 0)
array.set(divs, 0, cond and (searchdiv == 'Regular' or searchdiv == 'Regular/Hidden') ? positive_regular_positive_hidden_divergence(indicator_1, 1) : 0)
array.set(divs, 1, cond and (searchdiv == 'Regular' or searchdiv == 'Regular/Hidden') ? negative_regular_negative_hidden_divergence(indicator_1, 1) : 0)
array.set(divs, 2, cond and (searchdiv == 'Hidden' or searchdiv == 'Regular/Hidden') ? positive_regular_positive_hidden_divergence(indicator_1, 2) : 0)
array.set(divs, 3, cond and (searchdiv == 'Hidden' or searchdiv == 'Regular/Hidden') ? negative_regular_negative_hidden_divergence(indicator_1, 2) : 0)
divs
// array to keep all divergences
// !!!!!!!!!! DIMAK - add num of Indicators *4
var all_divergences = array.new_int(76) // 11 indicators * 4 divergence = 44 elements
// set related array elements
array_set_divs(div_pointer, index) =>
for x = 0 to 3 by 1
array.set(all_divergences, index * 4 + x, array.get(div_pointer, x))
// set divergences array
if calcmacd
array_set_divs(calculate_divs(calcmacd, macd), 0)
if calcmacda
array_set_divs(calculate_divs(calcmacda, deltamacd), 1)
if calcrsi
array_set_divs(calculate_divs(calcrsi, rsi), 2)
if calcstoc
array_set_divs(calculate_divs(calcstoc, stk), 3)
if calccci
array_set_divs(calculate_divs(calccci, cci), 4)
if calcmom
array_set_divs(calculate_divs(calcmom, moment), 5)
if calcobv
array_set_divs(calculate_divs(calcobv, Obv), 6)
if calcvwmacd
array_set_divs(calculate_divs(calcvwmacd, vwmacd), 7)
if calccmf
array_set_divs(calculate_divs(calccmf, cmf), 8)
if calcmfi
array_set_divs(calculate_divs(calcmfi, Mfi), 9)
if calcext
array_set_divs(calculate_divs(calcext, externalindi), 10)
if calcLD
array_set_divs(calculate_divs(calcLD, aStDev), 11)
if calcWVIX
array_set_divs(calculate_divs(calcWVIX, wvf), 12)
if calcStochRSI
array_set_divs(calculate_divs(calcStochRSI, StochRSIk), 13)
if calcSMIO
array_set_divs(calculate_divs(calcSMIO, oscSMIO), 14)
if calcVWMACD_LB
array_set_divs(calculate_divs(calcVWMACD_LB, dmVWMACD_LB), 15)
if calcBBP
array_set_divs(calculate_divs(calcBBP, BBPower), 16)
if calcBOP
array_set_divs(calculate_divs(calcBOP, SmootherBOP), 17)
if calcRVI
array_set_divs(calculate_divs(calcRVI, rviMA), 18)
// !!!!!!! DIMAK - add num of Indicators
// check minimum number of divergence, if less than showlimit then delete all divergence
total_div = 0
for x = 0 to array.size(all_divergences) - 1 by 1
total_div += math.round(math.sign(array.get(all_divergences, x)))
if total_div < showlimit
array.fill(all_divergences, 0)
// keep line in an array
var pos_div_lines = array.new_line(0)
var neg_div_lines = array.new_line(0)
var pos_div_labels = array.new_label(0)
var neg_div_labels = array.new_label(0)
// remove old lines and labels if showlast option is enabled
delete_old_pos_div_lines() =>
if array.size(pos_div_lines) > 0
for j = 0 to array.size(pos_div_lines) - 1 by 1
line.delete(array.get(pos_div_lines, j))
1
array.clear(pos_div_lines)
delete_old_neg_div_lines() =>
if array.size(neg_div_lines) > 0
for j = 0 to array.size(neg_div_lines) - 1 by 1
line.delete(array.get(neg_div_lines, j))
1
array.clear(neg_div_lines)
delete_old_pos_div_labels() =>
if array.size(pos_div_labels) > 0
for j = 0 to array.size(pos_div_labels) - 1 by 1
label.delete(array.get(pos_div_labels, j))
array.clear(pos_div_labels)
delete_old_neg_div_labels() =>
if array.size(neg_div_labels) > 0
for j = 0 to array.size(neg_div_labels) - 1 by 1
label.delete(array.get(neg_div_labels, j))
array.clear(neg_div_labels)
// delete last creted lines and labels until we met new PH/PV
delete_last_pos_div_lines_label(n) =>
if n > 0 and array.size(pos_div_lines) >= n
asz = array.size(pos_div_lines)
for j = 1 to n by 1
line.delete(array.get(pos_div_lines, asz - j))
array.pop(pos_div_lines)
if array.size(pos_div_labels) > 0
label.delete(array.get(pos_div_labels, array.size(pos_div_labels) - 1))
array.pop(pos_div_labels)
delete_last_neg_div_lines_label(n) =>
if n > 0 and array.size(neg_div_lines) >= n
asz = array.size(neg_div_lines)
for j = 1 to n by 1
line.delete(array.get(neg_div_lines, asz - j))
array.pop(neg_div_lines)
if array.size(neg_div_labels) > 0
label.delete(array.get(neg_div_labels, array.size(neg_div_labels) - 1))
array.pop(neg_div_labels)
// variables for Alerts
pos_reg_div_detected = false
neg_reg_div_detected = false
pos_hid_div_detected = false
neg_hid_div_detected = false
// to remove lines/labels until we met new // PH/PL
var last_pos_div_lines = 0
var last_neg_div_lines = 0
var remove_last_pos_divs = false
var remove_last_neg_divs = false
if pl
remove_last_pos_divs := false
last_pos_div_lines := 0
last_pos_div_lines
if ph
remove_last_neg_divs := false
last_neg_div_lines := 0
last_neg_div_lines
// draw divergences lines and labels
divergence_text_top = ''
divergence_text_bottom = ''
distances = array.new_int(0)
dnumdiv_top = 0
dnumdiv_bottom = 0
top_label_col = color.white
bottom_label_col = color.white
old_pos_divs_can_be_removed = true
old_neg_divs_can_be_removed = true
startpoint = dontconfirm ? 0 : 1 // used for don't confirm option
// !!!!!!!!!!!! DIMAK - add num of Indicators
for x = 0 to 18 by 1
div_type = -1
for y = 0 to 3 by 1
if array.get(all_divergences, x * 4 + y) > 0 // any divergence?
div_type := y
if y % 2 == 1
dnumdiv_top += 1
top_label_col := array.get(div_colors, y)
top_label_col
if y % 2 == 0
dnumdiv_bottom += 1
bottom_label_col := array.get(div_colors, y)
bottom_label_col
if not array.includes(distances, array.get(all_divergences, x * 4 + y)) // line not exist ?
array.push(distances, array.get(all_divergences, x * 4 + y))
new_line = showlines ? line.new(x1=bar_index - array.get(all_divergences, x * 4 + y), y1=source == 'Close' ? close[array.get(all_divergences, x * 4 + y)] : y % 2 == 0 ? low[array.get(all_divergences, x * 4 + y)] : high[array.get(all_divergences, x * 4 + y)], x2=bar_index - startpoint, y2=source == 'Close' ? close[startpoint] : y % 2 == 0 ? low[startpoint] : high[startpoint], color=array.get(div_colors, y), style=y < 2 ? reg_div_l_style : hid_div_l_style, width=y < 2 ? reg_div_l_width : hid_div_l_width) : na
if y % 2 == 0
if old_pos_divs_can_be_removed
old_pos_divs_can_be_removed := false
if not showlast and remove_last_pos_divs
delete_last_pos_div_lines_label(last_pos_div_lines)
last_pos_div_lines := 0
last_pos_div_lines
if showlast
delete_old_pos_div_lines()
array.push(pos_div_lines, new_line)
last_pos_div_lines += 1
remove_last_pos_divs := true
remove_last_pos_divs
if y % 2 == 1
if old_neg_divs_can_be_removed
old_neg_divs_can_be_removed := false
if not showlast and remove_last_neg_divs
delete_last_neg_div_lines_label(last_neg_div_lines)
last_neg_div_lines := 0
last_neg_div_lines
if showlast
delete_old_neg_div_lines()
array.push(neg_div_lines, new_line)
last_neg_div_lines += 1
remove_last_neg_divs := true
remove_last_neg_divs
// set variables for alerts
if y == 0
pos_reg_div_detected := true
pos_reg_div_detected
if y == 1
neg_reg_div_detected := true
neg_reg_div_detected
if y == 2
pos_hid_div_detected := true
pos_hid_div_detected
if y == 3
neg_hid_div_detected := true
neg_hid_div_detected
// get text for labels
if div_type >= 0
divergence_text_top += (div_type % 2 == 1 ? showindis != 'Don\'t Show' ? array.get(indicators_name, x) + '\n' : '' : '')
divergence_text_bottom += (div_type % 2 == 0 ? showindis != 'Don\'t Show' ? array.get(indicators_name, x) + '\n' : '' : '')
divergence_text_bottom
// draw labels
if showindis != 'Don\'t Show' or shownum
if shownum and dnumdiv_top > 0
divergence_text_top += str.tostring(dnumdiv_top)
divergence_text_top
if shownum and dnumdiv_bottom > 0
divergence_text_bottom += str.tostring(dnumdiv_bottom)
divergence_text_bottom
if divergence_text_top != ''
if showlast
delete_old_neg_div_labels()
array.push(neg_div_labels, label.new(x=bar_index, y=math.max(high, high[1]), text=divergence_text_top, color=top_label_col, textcolor=neg_div_text_col, style=label.style_label_down))
if divergence_text_bottom != ''
if showlast
delete_old_pos_div_labels()
array.push(pos_div_labels, label.new(x=bar_index, y=math.min(low, low[1]), text=divergence_text_bottom, color=bottom_label_col, textcolor=pos_div_text_col, style=label.style_label_up))
//alertcondition(pos_reg_div_detected, title='Positive Regular Divergence Detected', message='Positive Regular Divergence Detected')
//alertcondition(neg_reg_div_detected, title='Negative Regular Divergence Detected', message='Negative Regular Divergence Detected')
//alertcondition(pos_hid_div_detected, title='Positive Hidden Divergence Detected', message='Positive Hidden Divergence Detected')
//alertcondition(neg_hid_div_detected, title='Negative Hidden Divergence Detected', message='Negative Hidden Divergence Detected')
//alertcondition(pos_reg_div_detected or pos_hid_div_detected, title='Positive Divergence Detected', message='Positive Divergence Detected')
//alertcondition(neg_reg_div_detected or neg_hid_div_detected, title='Negative Divergence Detected', message='Negative Divergence Detected')
// ===================================================================================================
GRUPO_KC = 'Keltner Channel'
use_KC = input.bool(false, 'Use Channel ?', group=GRUPO_KC)
P_indicador = input.string('Keltner Channel', 'Channel to Use:', options=['Keltner Channel', 'Bollinger Bands'], group=GRUPO_KC)
P_cond_entrada = input.string('Wick out of band', 'Enter Conditions', options=['Wick out of band', 'Wick out of the band then close in', 'Out-of-band closure', 'Close out of the band then close in'], group=GRUPO_KC)
KC_length = input.int(title='Keltner Long.', group=GRUPO_KC, defval=14, minval=1, inline='kc')
KC_mult = input.float(title='Keltner Mult.', group=GRUPO_KC, defval=1.5, minval=0.01, step=0.05, inline='kc')
[KC_mid, KC_upper, KC_lower] = ta.kc(close, KC_length, KC_mult)
GRUPO_BB = 'Bollinger Bands Filter'
BB_length = input.int(title='BB Long. ', group=GRUPO_KC, defval=20, minval=1, inline='bb')
BB_dev = input.float(title='BB Deviation (Desv.)', group=GRUPO_KC, defval=2.0, minval=0.01, step=0.1, inline='bb')
[BB_mid, BB_upper, BB_lower] = ta.bb(close, BB_length, BB_dev)
Kanal_upper = KC_upper
Kanal_mid = KC_mid
Kanal_lower = KC_lower
if P_indicador == 'Bollinger Bands'
Kanal_upper := BB_upper
Kanal_mid := BB_mid
Kanal_lower := BB_lower
//Kanal_lower
//displ= display.none
displ = use_KC ? display.all : display.none
plot(Kanal_upper, 'UP', color.new(color.aqua, 0), display = displ)
plot(Kanal_mid, 'Mid', color.new(color.orange, 0), display = displ)
plot(Kanal_lower, 'DOWN', color.new(color.aqua, 0), display = displ)
longCondition2 = true
shortCondition2 = true
if use_KC
longCondition2 := false
shortCondition2 := false
if P_cond_entrada == 'Wick out of band'
longCondition2 := low < Kanal_lower
shortCondition2 := high > Kanal_upper
shortCondition2
else if P_cond_entrada == 'Wick out of the band then close in'
longCondition2 := low[1] < Kanal_lower and close > Kanal_lower
shortCondition2 := high[1] > Kanal_upper and close < Kanal_upper
shortCondition2
else if P_cond_entrada == 'Out-of-band closure'
longCondition2 := close < Kanal_lower
shortCondition2 := close > Kanal_upper
shortCondition2
else
// Close out of the band then close in
longCondition2 := close[1] < Kanal_lower and close > Kanal_lower
shortCondition2 := close[1] > Kanal_upper and close < Kanal_upper
shortCondition2
else
longCondition2 := true
shortCondition2 := true
shortCondition2
// ===================================================================================================
// ======================= dimak RSI timeframe Begin 1111111 ====================
GRUPO_RSI_TF = "========== RSI FILTER ============"
lengthRSI = input.int(title="RSI TF Long(14):", group=GRUPO_RSI_TF, defval=14, minval=1)
tf_rsi_indicator = input.timeframe("",title="RSI TimeFrame:", group=GRUPO_RSI_TF)
useRSITFoverSold = input.bool(false, 'Use RSI LONG Range', group=GRUPO_RSI_TF)
overSoldRSITF = input.int(title='(LONG) RSI is More', group=GRUPO_RSI_TF, defval=30, step=5, minval=1, inline='22')
overSold2RSITF = input.int(title='& RSI Less', group=GRUPO_RSI_TF, defval=70, minval=1, maxval = 100, step=5, inline='22')
useRSITFFoverBought = input.bool(false, 'Use RSI SHORT Range', group=GRUPO_RSI_TF)
overBoughtRSITF = input.int(title='(SHORT) RSI is Less', group=GRUPO_RSI_TF, defval=70, step=5, minval=1, maxval = 100, inline='33')
overBought2RSITF = input.int(title='& RSI More', group=GRUPO_RSI_TF, defval=30, minval=1, step=5, inline='33')
//rsi_tf1 = request.security(syminfo.tickerid, tf_rsi_indicator, ta.rsi(close, lengthRSI), barmerge.gaps_off)
rsi_tf1 = f_security(syminfo.tickerid, tf_rsi_indicator, ta.rsi(close, lengthRSI), false) // Repaint = false
//=====================================================
longCondition8 = true
shortCondition8 = true
if useRSITFoverSold or useRSITFFoverBought
longCondition8 := false
shortCondition8 := false
if useRSITFoverSold and (rsi_tf1 >= overSoldRSITF) and (rsi_tf1 <= overSold2RSITF)
longCondition8 := true
if useRSITFFoverBought and (rsi_tf1 <= overBoughtRSITF) and (rsi_tf1 >= overBought2RSITF)
shortCondition8 := true
else
longCondition8 := true
shortCondition8 := true
//dimak RSI timeframe END
//=====================================================
// ======================= dimak RSI timeframe Begin 22222222 ====================
GRUPO_RSI_TF2 = "======= RSI FILTER - Multi TimeFrame [2] ======="
lengthRSI2 = input.int(title="RSI TF Long(14):[2]", group=GRUPO_RSI_TF2, defval=14, minval=1)
tf_rsi_indicator2 = input.timeframe("",title="RSI TimeFrame:[2]", group=GRUPO_RSI_TF2)
useRSITFoverSold2 = input.bool(false, 'Use RSI LONG Range[2]', group=GRUPO_RSI_TF2)
overSoldRSITF2 = input.int(title='(LONG) RSI is More[2]', group=GRUPO_RSI_TF2, defval=30, step=5, minval=1, inline='22')
overSold2RSITF2 = input.int(title='& RSI Less[2]', group=GRUPO_RSI_TF2, defval=70, minval=1, maxval = 100, step=5, inline='22')
useRSITFFoverBought2 = input.bool(false, 'Use RSI SHORT Range[2]', group=GRUPO_RSI_TF2)
overBoughtRSITF2 = input.int(title='(SHORT) RSI is Less[2]', group=GRUPO_RSI_TF2, defval=70, maxval = 100, step=5, minval=1, inline='33')
overBought2RSITF2 = input.int(title='& RSI More[2]', group=GRUPO_RSI_TF2, defval=30, minval=1, step=5, inline='33')
//rsi_tf2 = request.security(syminfo.tickerid, tf_rsi_indicator2, ta.rsi(close, lengthRSI2), barmerge.gaps_off)
rsi_tf2 = f_security(syminfo.tickerid, tf_rsi_indicator2, ta.rsi(close, lengthRSI2), false) // Repaint = false
//=====================================================
longCondition10 = true
shortCondition10 = true
if useRSITFoverSold2 or useRSITFFoverBought2 and not na(rsi_tf2)
longCondition10 := false
shortCondition10 := false
if useRSITFoverSold2 and (rsi_tf2 >= overSoldRSITF2) and (rsi_tf2 <= overSold2RSITF2)
longCondition10 := true
if useRSITFFoverBought2 and (rsi_tf2 <= overBoughtRSITF2) and (rsi_tf2 >= overBought2RSITF2)
shortCondition10 := true
else
longCondition10 := true
shortCondition10 := true
//dimak RSI timeframe END
//=====================================================
// ============ dimak "Money Flow Index" Filter Timeframe [111] =============
GRUPO_MFI_TF = '=========== MFI FILTER ==========='
lengthMFI = input.int(title='MFI TF Long:', group=GRUPO_MFI_TF, defval=14, minval=1)
tf_mfi_indicator = input.timeframe('', title='MFI TimeFrame:', group=GRUPO_MFI_TF)
useMFITFoverSold = input.bool(false, 'Use MFI LONG Range', group=GRUPO_MFI_TF)
overSold = input.int(title='(LONG) MFI is More', group=GRUPO_MFI_TF, defval=10, step=5, minval=1, inline='22')
overSold2 = input.int(title='& MFI Less', group=GRUPO_MFI_TF, defval=60, maxval = 100, step=5, minval=1, inline='22')
useMFITFoverBought = input.bool(false, 'Use MFI SHORT Range', group=GRUPO_MFI_TF)
overBought = input.int(title='(SHORT) MFI is Less', group=GRUPO_MFI_TF, defval=95, maxval = 100, step=5, minval=1, inline='33')
overBought2 = input.int(title='& MFI More', group=GRUPO_MFI_TF, defval=50, maxval = 100, step=5, minval=1, inline='33')
mfi_tf1 = f_security(syminfo.tickerid, tf_mfi_indicator, ta.mfi(hlc3, lengthMFI), true) // Repaint = false
//mfi_tf1 = request.security(syminfo.tickerid, tf_mfi_indicator, ta.mfi(hlc3, lengthMFI), barmerge.gaps_off)
// =====================================================
longCondition4 = true
shortCondition4 = true
if useMFITFoverSold or useMFITFoverBought
longCondition4 := false
shortCondition4 := false
if useMFITFoverSold and (mfi_tf1 > overSold) and (mfi_tf1 < overSold2)
longCondition4 := true
if useMFITFoverBought and (mfi_tf1 < overBought) and (mfi_tf1 > overBought2)
shortCondition4 := true
else
longCondition4 := true
shortCondition4 := true
// dimak MFI timeframe [111] END
// =====================================================
use_mfi_tf1_rising = input.bool(false, 'Use MFI TF Rising ?', group=GRUPO_MFI_TF)
mfi_tf1_rising_len = input.int(3, title='MFI TF Rising Lengh:', group=GRUPO_MFI_TF, minval=0, maxval=20)
use_mfi_tf1_falling = input.bool(false, 'Use MFI TF Falling ?', group=GRUPO_MFI_TF)
mfi_tf1_falling_len = input.int(3, title='MFI TF Falling Lengh:', group=GRUPO_MFI_TF, minval=0, maxval=20)
mfi_tf1_falling = ta.falling(mfi_tf1, mfi_tf1_falling_len)
mfi_tf1_rising = ta.rising(mfi_tf1, mfi_tf1_rising_len)
//mfi_tf1_falling_tf = request.security(syminfo.tickerid, tf_mfi_indicator, mfi_tf1_falling, barmerge.gaps_off)
//mfi_tf1_rising_tf = request.security(syminfo.tickerid, tf_mfi_indicator, mfi_tf1_rising, barmerge.gaps_off)
mfi_tf1_falling_tf = f_security(syminfo.tickerid, tf_mfi_indicator, mfi_tf1_falling, true) // Repaint = false
mfi_tf1_rising_tf = f_security(syminfo.tickerid, tf_mfi_indicator, mfi_tf1_rising, true) // Repaint = false
longCondition12 = true
shortCondition12 = true
if use_mfi_tf1_falling or use_mfi_tf1_rising
longCondition12 := false
shortCondition12 := false
if (use_mfi_tf1_falling and mfi_tf1_falling_tf) or (use_mfi_tf1_rising and mfi_tf1_rising_tf)
shortCondition12 := true
longCondition12 := true
else
longCondition12 := true
shortCondition12 := true
// dimak MFI timeframe END
// =====================================================
// =====================================================
// Two ATR (Volatility Check)
grDATR="=======Two ATR (Volatility Check) Base Settings========="
//useDATR = input(defval=false, title='Use Two ATR (Volatility Check) ?', group = grDATR)
lengthDATR = input.int(title='ATR length1 (20)(5)', defval=20, minval=1, group = grDATR)
length2DATR = input.int(title='ATR length2 (100)(20)', defval=100, minval=1, group = grDATR)
smoothingDATR = input.string(title='ATR Smoothing', defval='WMA', options=['RMA', 'SMA', 'EMA', 'WMA'], group = grDATR)
DATR_ma_function(sourceDATR, lengthDATR1) =>
if smoothingDATR == 'RMA'
ta.rma(sourceDATR, lengthDATR1)
else
if smoothingDATR == 'SMA'
ta.sma(sourceDATR, lengthDATR1)
else
if smoothingDATR == 'EMA'
ta.ema(sourceDATR, lengthDATR1)
else // WMA
ta.wma(sourceDATR, lengthDATR1)
datr1 = DATR_ma_function(ta.tr(true), lengthDATR)
datr2 = DATR_ma_function(ta.tr(true), length2DATR)
// ATR Histograme
datr_hist = datr1-datr2
//plot(datr1+0.4, title='ATR', color=color.new(#77C5E1, 0))
//plot(datr2+0.4, title='ATR', color=color.new(#FF5252, 0))
//plot(datr_hist, color=color.red, style=plot.style_histogram)
// block for filters "ATR1 < ATR2" BEGIN
// "ATR1 < ATR2 - Volatility is Small in last bars, ATR1 > ATR2 - Volatility is High in last bars"
//grATR1ATR2 = "=============== Two ATR (ATR1 <> ATR2)=============="
use_atr1toart2_more_less = input(defval=false, title='Use ATR1 <> ATR2 ? ', group = grDATR)
atr1toart2_more_less = input.string(title='ATR1 to ATR2', defval='ATR1 < ATR2', options=['ATR1 < ATR2', 'ATR1 > ATR2'], group = grDATR, tooltip = "ATR1 < ATR2 - Volatility is Small in last bars, ATR1 > ATR2 - Volatility is High in last bars")
datr1todatr3 = use_atr1toart2_more_less and (atr1toart2_more_less == "ATR1 < ATR2") and (datr1 < datr2) ? true : use_atr1toart2_more_less and (atr1toart2_more_less == "ATR1 > ATR2") and (datr1 > datr2) ? true : false
longCondition1 = true
shortCondition1 = true
if use_atr1toart2_more_less
longCondition1 := false
shortCondition1 := false
longCondition1 := datr1todatr3
shortCondition1 := longCondition1
else
longCondition1 := true
shortCondition1 := true
// shortCondition1 and longCondition1 is if Fast ATR Must be higher (or Lower) than Slow ATR !!!
// block for filters "ATR1 < ATR2" END
// ==========================================================================
// NOTE "ATR1 < ATR2" and ( Barssince_Highest/Lowest + falling/rising ) are working separately. But Same ATR settings
// ==========================================================================
// ========== Two Average True Range ===============================
// ==================== Volume Filter =================== Begin
grVOL="=======Volume Filter========="
use_VOL_more_less = input(defval=false, title='Use VOL1 <> VOL2 ? ', group = grVOL)
VOL_more_less = input.string(title='VOL1 to VOL2', defval='VOL1 < VOL2', options=['VOL1 < VOL2', 'VOL1 > VOL2'], group = grVOL, tooltip = "VOL1 < VOL2 - Volume is Small in last bars, VOL1 > VOL2 - Volume is High in last bars")
lengthVOL = input.int(title='VOL length1 (20)(5)', defval=20, minval=1, group = grVOL)
length2VOL = input.int(title='VOL length2 (100)(20)', defval=100, minval=1, step = 5, group = grVOL)
smoothingVOL = input.string(title='VOL Smoothing', defval='WMA', options=['RMA', 'SMA', 'EMA', 'WMA'], group = grVOL)
VOL_ma_function(sourceVOL, XlengthVOL) =>
if smoothingVOL == 'RMA'
ta.rma(sourceVOL, XlengthVOL)
else
if smoothingVOL == 'SMA'
ta.sma(sourceVOL, XlengthVOL)
else
if smoothingVOL == 'EMA'
ta.ema(sourceVOL, XlengthVOL)
else // WMA
ta.wma(sourceVOL, XlengthVOL)
vol1 = VOL_ma_function(volume, lengthVOL)
vol2 = VOL_ma_function(volume, length2VOL)
longCondition11 = true
shortCondition11 = true
if use_VOL_more_less
longCondition11 := false
shortCondition11 := false
longCondition11 := use_VOL_more_less and (VOL_more_less == "VOL1 < VOL2") and (vol1 < vol2) ? true : use_VOL_more_less and (VOL_more_less == "VOL1 > VOL2") and (vol1 > vol2) ? true : false
shortCondition11 := longCondition11
else
longCondition11 := true
shortCondition11 := true
// ==================== Volume Filter =================== END
// ======================= dimak CCI timeframe Begin 1111111 ====================
GRUPO_CCI_TF = "========== CCI FILTER ============"
lengthCCI = input.int(title="CCI TF Long(14):", group=GRUPO_CCI_TF, defval=14, minval=1)
tf_CCI_indicator = input.timeframe("",title="CCI TimeFrame:", group=GRUPO_CCI_TF)
useCCITFoverSold = input.bool(false, 'Use CCI LONG Range', group=GRUPO_CCI_TF)
overSoldCCITF = input.int(title='(LONG) CCI is More', group=GRUPO_CCI_TF, defval=-400, step=5, minval=-400, inline='22')
overSold2CCITF = input.int(title='& CCI Less', group=GRUPO_CCI_TF, defval=400, minval=-401, maxval = 400, step=5, inline='22')
useCCITFFoverBought = input.bool(false, 'Use CCI SHORT Range', group=GRUPO_CCI_TF)
overBoughtCCITF = input.int(title='(SHORT) CCI is Less', group=GRUPO_CCI_TF, defval=400, step=5, minval=-401, maxval = 400, inline='33')
overBought2CCITF = input.int(title='& CCI More', group=GRUPO_CCI_TF, defval=10, minval=-401, step=5, inline='33')
//CCI_tf1 = request.security(syminfo.tickerid, tf_CCI_indicator, ta.cci(close, lengthCCI), barmerge.gaps_off)
CCI_tf1 = f_security(syminfo.tickerid, tf_CCI_indicator, ta.cci(close, lengthCCI), false) // Repaint = false
//=====================================================
longCondition9 = true
shortCondition9 = true
if useCCITFoverSold or useCCITFFoverBought
longCondition9 := false
shortCondition9 := false
if useCCITFoverSold and (CCI_tf1 >= overSoldCCITF) and (CCI_tf1 <= overSold2CCITF)
longCondition9 := true
if useCCITFFoverBought and (CCI_tf1 <= overBoughtCCITF) and (CCI_tf1 >= overBought2CCITF)
shortCondition9 := true
else
longCondition9 := true
shortCondition9 := true
//dimak CCI timeframe END
//=====================================================
// ======================= dimak Momentum timeframe Begin 1111111 ====================
GRUPO_MOM_TF = "==========Momentum FILTER ============"
lengthMOM = input.int(title="Momentum TF Long(14):", group=GRUPO_MOM_TF, defval=14, minval=1)
tf_MOM_indicator = input.timeframe("",title="Momentum TimeFrame:", group=GRUPO_MOM_TF)
useMOMTFoverSold = input.bool(false, 'Use Momentum LONG Range (-100:100)', group=GRUPO_MOM_TF)
overSoldMOMTF = input.int(title='(LONG) Momentum is More', group=GRUPO_MOM_TF, defval=-100, step=5, minval=-100, maxval = 100, inline='22')
overSold2MOMTF = input.int(title='& Mom Less', group=GRUPO_MOM_TF, defval=10, minval=-100, maxval = 100, step=5, inline='22')
useMOMTFFoverBought = input.bool(false, 'Use Momentum SHORT Range (100:-100)', group=GRUPO_MOM_TF)
overBoughtMOMTF = input.int(title='(SHORT) Momentum is Less', group=GRUPO_MOM_TF, defval=95, step=5, minval=-100, maxval = 100, inline='33')
overBought2MOMTF = input.int(title='& Mom More', group=GRUPO_MOM_TF, defval=-30, minval=-100, maxval = 100, step=5, inline='33')
srcMOM = input(close, "Momentum Source", group=GRUPO_MOM_TF)
momm = ta.change(srcMOM)
f1(m) => m >= 0.0 ? m : 0.0
f2(m) => m >= 0.0 ? 0.0 : -m
m1 = f1(momm)
m2 = f2(momm)
sm1 = math.sum(m1, lengthMOM)
sm2 = math.sum(m2, lengthMOM)
percent(nom, div) => 100 * nom / div
chandeMO = percent(sm1-sm2, sm1+sm2)
//MOM_tf2 = request.security(syminfo.tickerid, tf_MOM_indicator, chandeMO, barmerge.gaps_off)
MOM_tf2 = f_security(syminfo.tickerid, tf_MOM_indicator, chandeMO, false) // Repaint = false
//=====================================================
longCondition3 = true
shortCondition3 = true
if useMOMTFoverSold or useMOMTFFoverBought
longCondition3 := false
shortCondition3 := false
if useMOMTFoverSold and (MOM_tf2 >= overSoldMOMTF) and (MOM_tf2 <= overSold2MOMTF)
longCondition3 := true
if useMOMTFFoverBought and (MOM_tf2 <= overBoughtMOMTF) and (MOM_tf2 >= overBought2MOMTF)
shortCondition3 := true
else
longCondition3 := true
shortCondition3 := true
//dimak MOM timeframe END
//=====================================================
// ========== Super Trend =============================== Begin
grSUPTREND = "=============SUPER TREND FILTER============="
useSUPTREND = input(defval=false, title='Use SuperTrend ?', group = grSUPTREND)
opposite_SUPTREND = input(defval=false, title='Opposite SP Signal? (Sell on UPtrend..)', group = grSUPTREND)
PeriodsST = input.int(title='SuperTrend ATR Period', defval=10, minval=1, group=grSUPTREND)
MultiplierST = input.float(title='SuperTrend ATR Multiplier', step=0.1, defval=3.0, group=grSUPTREND)
//srcST = input(hl2, title='SuperTrend Source', group=grSUPTREND)
srcST = hl2
//changeATR = input(title='Set ATR Smoothing to SMA ?', defval=true, group=grSUPTREND)
changeATR = true
highlightingST = input(title='Show SuperTrend ?', defval=false, group=grSUPTREND)
atr2ST = ta.sma(ta.tr, PeriodsST)
atrST = changeATR ? ta.atr(PeriodsST) : atr2ST
upST = srcST - MultiplierST * atrST
up1ST = nz(upST[1], upST)
upST := close[1] > up1ST ? math.max(upST, up1ST) : upST
dnST = srcST + MultiplierST * atrST
dn1ST = nz(dnST[1], dnST)
dnST := close[1] < dn1ST ? math.min(dnST, dn1ST) : dnST
trendST = 1
trendST := nz(trendST[1], trendST)
trendST := trendST == -1 and close > dn1ST ? 1 : trendST == 1 and close < up1ST ? -1 : trendST
// check if Trend Changed. Not used now. Commented below.
buySignalST = trendST == 1 and trendST[1] == -1
sellSignalST = trendST == -1 and trendST[1] == 1
// check if Trend Changed. Not used now. Commented below.
// visual
displST = highlightingST ? display.all : display.none
upPlot = plot(trendST == 1 ? upST : na, title='Up Trend', style=plot.style_linebr, linewidth=2, color=color.new(color.green, 0), display = displST)
dnPlot = plot(trendST == 1 ? na : dnST, title='Down Trend', style=plot.style_linebr, linewidth=2, color=color.new(color.red, 0), display = displST)
mPlot = plot(ohlc4, title='', style=plot.style_circles, linewidth=0)
fill(mPlot, upPlot, title='UpTrend Highligter', color=color.rgb(76, 144, 175, 90), display = displST)
fill(mPlot, dnPlot, title='DownTrend Highligter', color=color.rgb(255, 82, 255, 90), display = displST)
// visual
longCondition5 = true
shortCondition5 = true
if useSUPTREND
longCondition5 := false
shortCondition5 := false
longCondition5 := trendST == 1 and not opposite_SUPTREND ? true : trendST == -1 and opposite_SUPTREND ? true : false
shortCondition5 := trendST == -1 and not opposite_SUPTREND ? true : trendST == 1 and opposite_SUPTREND ? true : false
// signals by change trend
//longCondition5 := not opposite_SUPTREND ? buySignalST : sellSignalST
//shortCondition5 := not opposite_SUPTREND ? sellSignalST : buySignalST
else
longCondition5 := true
shortCondition5 := true
// ========== Super Trend =============================== End
// ===================================================================================================
if USE_SignSL
//if pos_reg_div_detected and not enable_long_strategy
if pos_reg_div_detected and longCondition1 and longCondition2 and longCondition3 and longCondition4 and longCondition5 and longCondition8 and longCondition9 and longCondition10 and longCondition11 and longCondition12
strategy.close('sell', comment='Close Short L-Sign', alert_message='stoploss')
//if neg_reg_div_detected and not enable_short_strategy
if neg_reg_div_detected and shortCondition1 and shortCondition2 and shortCondition3 and shortCondition4 and shortCondition5 and shortCondition8 and shortCondition9 and shortCondition10 and shortCondition11 and shortCondition12
strategy.close('buy', comment='Close Long S-Sign', alert_message='stoploss')
// ===================================================================================================
// == TEST CODE by =================================================================================================
//reverseCond = strategy.closedtrades.exit_comment(strategy.closedtrades - 1)
//exitPrice = strategy.closedtrades.exit_price(strategy.closedtrades - 1)
//if strategy.position_size == 0 and reverseCond == 'LSL'
// strategy.entry('sell', strategy.short, alert_message='enter_cycle')
//if strategy.position_size == 0 and reverseCond == 'SSL'
// strategy.entry('buy', strategy.long, alert_message='enter_cycle')
// ===== TEST CODE by ==============================================================================================
NotMultiOrders = ((strategy.closedtrades == 0) or ((bar_index != strategy.closedtrades.entry_bar_index(strategy.closedtrades - 1))))
//NotMultiOrders = true
// ============ New order after SL =======================================================================================
var wasLong = false
var wasShort = false
if USEorderOnSL and strategy.closedtrades.exit_bar_index(strategy.closedtrades-1) == bar_index and NotMultiOrders
if wasLong
wasLong := false
strategy.entry('sell222', strategy.short, alert_message='enter_cycle')
if wasShort
wasShort := false
strategy.entry('buy222', strategy.long, alert_message='enter_cycle')
// ============= New order after SL ===================================================================
// ===================================================================================================
if pos_reg_div_detected and enable_long_strategy and testPeriod() and NotMultiOrders and longCondition1 and longCondition2 and longCondition3 and longCondition4 and longCondition5 and longCondition8 and longCondition9 and longCondition10 and longCondition11 and longCondition12
strategy.entry('buy', strategy.long, alert_message='enter_cycle')
//strategy.order('sell333',strategy.short,stop = longSLExitPrice, limit = longSLExitPrice, alert_message ='reverse_position')
wasLong := true
wasShort := false
if neg_reg_div_detected and enable_short_strategy and testPeriod() and NotMultiOrders and shortCondition1 and shortCondition2 and shortCondition3 and shortCondition4 and shortCondition5 and shortCondition8 and shortCondition9 and shortCondition10 and shortCondition11 and shortCondition12
strategy.entry('sell', strategy.short, alert_message='enter_cycle')
//strategy.order('buy333',strategy.long,stop = shortSLExitPrice, limit = shortSLExitPrice, alert_message ='reverse_position')
wasShort := true
wasLong := false
// ===================================================================================================
// ===================================================================================================
if strategy.position_size > 0
strategy.exit(id='Close Long %', from_entry='buy', stop=longSLExitPrice, limit=longExitPrice, alert_message='stoploss')
if strategy.position_size < 0
strategy.exit(id='Close Short %', from_entry='sell', stop=shortSLExitPrice, limit=shortExitPrice, alert_message='stoploss')
// ===================================================================================================
displTPSL = not USEdisplTPSL ? display.none : display.all
// visual TP SL
avg_position_price_plot = plot(series=strategy.position_size != 0 ? strategy.position_avg_price : na, color=color.new(#c2bfbf, 25), style=plot.style_linebr, linewidth=2, title="Precio Entrada", display = displTPSL)
LONG_tp_plot = plot(strategy.position_size > 0 and longExitPrice > 0.0 ? longExitPrice : na, color=color.new(color.lime, 60), style=plot.style_linebr, linewidth=2, title="LONG Take Profit", display = displTPSL)
LONG_sl_plot = plot(strategy.position_size > 0 and longSLExitPrice > 0.0? longSLExitPrice : na, color=color.new(color.red, 60), style=plot.style_linebr, linewidth=2, title="Long Stop Loss", display = displTPSL)
fill(avg_position_price_plot, LONG_tp_plot, color=color.new(color.olive, 90), display = displTPSL)
fill(avg_position_price_plot, LONG_sl_plot, color=color.new(color.maroon, 90), display = displTPSL)
SHORT_tp_plot = plot(strategy.position_size < 0 and shortExitPrice > 0.0 ? shortExitPrice : na, color=color.new(color.lime, 60), style=plot.style_linebr, linewidth=2, title="SHORT Take Profit", display = displTPSL)
SHORT_sl_plot = plot(strategy.position_size < 0 and shortSLExitPrice > 0.0 ? shortSLExitPrice : na, color=color.new(color.red, 60), style=plot.style_linebr, linewidth=2, title="Short Stop Loss", display = displTPSL)
fill(avg_position_price_plot, SHORT_tp_plot, color=color.new(color.olive, 90), display = displTPSL)
fill(avg_position_price_plot, SHORT_sl_plot, color=color.new(color.maroon, 90), display = displTPSL) |
MVRV Z Score and MVRV Free Float Z-Score | https://www.tradingview.com/script/v3TqVthK-MVRV-Z-Score-and-MVRV-Free-Float-Z-Score/ | Powerscooter | https://www.tradingview.com/u/Powerscooter/ | 353 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Powerscooter
//@version=5
strategy("MVRV Z Score and MVRV Free Float Z-Score",shorttitle = "MVRV Z Score",precision=2,default_qty_type = strategy.cash, default_qty_value = 100, initial_capital = 100)
//Inputs
Strategymode = input.bool(false,"Strategy Mode","Switches between indicator and strategy mode.")
Calculation = input.string("Standard", "Calculation Method",options = ["Standard","Free Float"], tooltip = "The standard calculation uses the market cap while the free float version uses the free float market cap.")
Source = input.string("Glassnode", "Market Cap Source",options = ["Glassnode","Coinmetrics"])
Upper = input.float(7.0,"Upper Line",tooltip="Z-Score value above which a sell signal is given, standard is 7.")
Lower = input.float(0.1,"Lower Line",tooltip="Z-Score value below which a buy signal is given, standard is 0.1.")
//Query
MC1 = request.security("GLASSNODE:BTC_MARKETCAP","D",close)
MC2 = request.security("CRYPTOCAP:BTC","D",close)
MCF = request.security("COINMETRICS:BTC_MARKETCAPFF","D",close)
MCR = request.security("COINMETRICS:BTC_MARKETCAPREAL","D",close)
//Initialize var
var float MC = 0
var MCA = array.new<float>()
var float MVRV = 0
var float Zscore = 0
//Calculations
if Source=="Glassnode"
MC := MC1
else
MC := MC2
array.push(MCA,MC)
StdDevA = array.stdev(MCA)
if Calculation=="Standard"
MVRV := MC/MCR
if Calculation=="Free Float"
MVRV := MCF/MCR
if Calculation=="Standard"
Zscore := (MC-MCR)/StdDevA
if Calculation=="Free Float"
Zscore := (MCF-MCR)/StdDevA
//Plotting
MVRVplot = plot(MVRV, "MVRV", color=color.blue,transp=40)
Zplot = plot(Zscore, "Z-score",color=color.yellow,linewidth = 2)
UpperLine = Zscore>=Upper?Upper:na
LowerLine = Zscore<=Lower?Lower:na
//Lower and UpperLine are undefined when Zscore isn't close to them so they don't affect panel scaling.
UpperPlot = plot(UpperLine, transp=100, trackprice = true, color=color.red, display=display.all-display.status_line)
LowerPlot = plot(LowerLine, transp=100, trackprice = true, color=color.green, display=display.all-display.status_line)
fill(plot1=Zplot,plot2=UpperPlot,color=color.red, transp=30)
fill(plot1=Zplot,plot2=LowerPlot,color=color.green, transp=30)
//Order Conditions
Long = ta.crossunder(Zscore,Lower)
TakeProfit = ta.crossover(Zscore,Upper)
//Execution
if Long and Strategymode
strategy.entry("Long",strategy.long)
if TakeProfit and Strategymode
strategy.close("Long") |
Strategy for UT Bot Alerts indicator | https://www.tradingview.com/script/R9nsvSZR/ | StrategiesForEveryone | https://www.tradingview.com/u/StrategiesForEveryone/ | 1,150 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
//Developed by StrategiesForEveryone
strategy("UT Bot alerts strategy", overlay=true, process_orders_on_close = true, initial_capital = 1000000, default_qty_type=strategy.cash, precision = 2, calc_on_every_tick = true, commission_value = 0.03)
// ------ Inputs for calculating position --------
initial_actual_capital = input.float(defval=10000, title = "Enter initial/current capital", group = "============ Calculate amount position ============")
risk_c = input.float(2.5, '% account risk per trade', step=1, group = "============ Calculate amount position ============", tooltip = "Percentage of total account to risk per trade. The USD value that should be used to risk the inserted percentage of the account. Appears green in the upper left corner")
// ------ Date filter (obtained from ZenAndTheArtOfTrading) ---------
initial_date = input.time(title="Initial date", defval=timestamp("10 Feb 2014 13:30 +0000"), group="============ Time filter ============ ", tooltip="Enter the start date and time of the strategy")
final_date = input.time(title="Final date", defval=timestamp("01 Jan 2030 19:30 +0000"), group="============ Time filter ============ ", tooltip="Enter the end date and time of the strategy")
dateFilter(int st, int et) => time >= st and time <= et
colorDate = input.bool(defval=false, title="Date background", tooltip = "Add color to the period of time of the strategy tester")
bgcolor(colorDate and dateFilter(initial_date, final_date) ? color.new(color.blue, transp=90) : na)
// ------ Session limits (obtained from ZenAndTheArtOfTrading) -------
timeSession = input.session(title="Time session", defval="0000-2400", group="============ Time filter ============ ", tooltip="Session time to operate. It may be different depending on your time zone, you have to find the correct hours manually.")
colorBG = input.bool(title="Session background", defval=false, tooltip = "Add color to session time background")
inSession(sess) => na(time(timeframe.period, sess + ':1234567')) == false
bgcolor(inSession(timeSession) and colorBG ? color.rgb(0, 38, 255, 84) : na)
// ----------- Ema ----------------------
ema = input.int(200, title='Ema length', minval=1, maxval=500, group = "============ Trend ============")
ema200 = ta.ema(close, ema)
bullish = close > ema200
bearish = close < ema200
show_ema = input.bool(defval=false, title="Show ema ?", group = "============ Appearance ============")
plot(show_ema ? ema200 : na, title = "Ema", color=color.white, linewidth=2, display = display.all - display.status_line - display.price_scale)
// -------------- UT BOT ALERTS INDICATOR by @QuantNomad -------------------------
// Inputs
a = input(3, title='Key Vaule', group = "============ UT BOT ALERTS ============", tooltip = "Higher amount, less trades. Changing this could be useful in some assets or time frames")
c = input(1, title='ATR Period', group = "============ UT BOT ALERTS ============", tooltip = "Higher amount, less trades. Changing this could be useful in some assets or time frames")
h = input(false, title='Signals from Heikin Ashi Candles', group = "============ UT BOT ALERTS ============")
xATR = ta.atr(c)
nLoss = a * xATR
src = h ? request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close, lookahead=barmerge.lookahead_off) : close
xATRTrailingStop = 0.0
iff_1 = src > nz(xATRTrailingStop[1], 0) ? src - nLoss : src + nLoss
iff_2 = src < nz(xATRTrailingStop[1], 0) and src[1] < nz(xATRTrailingStop[1], 0) ? math.min(nz(xATRTrailingStop[1]), src + nLoss) : iff_1
xATRTrailingStop := src > nz(xATRTrailingStop[1], 0) and src[1] > nz(xATRTrailingStop[1], 0) ? math.max(nz(xATRTrailingStop[1]), src - nLoss) : iff_2
show_atr_ut = input.bool(defval=false, title="Show atr from ut bot alerts ?", group = "============ Appearance ============")
plot(show_atr_ut ? xATRTrailingStop : na, color = color.orange, linewidth = 2, display = display.all - display.price_scale - display.status_line)
pos = 0
iff_3 = src[1] > nz(xATRTrailingStop[1], 0) and src < nz(xATRTrailingStop[1], 0) ? -1 : nz(pos[1], 0)
pos := src[1] < nz(xATRTrailingStop[1], 0) and src > nz(xATRTrailingStop[1], 0) ? 1 : iff_3
xcolor = pos == -1 ? color.red : pos == 1 ? color.green : color.blue
ema_ut = ta.ema(src, 1)
show_ema_ut = input.bool(defval=false, title="Show ema from ut bot alerts ?", group = "============ Appearance ============")
plot(show_ema_ut ? ema_ut : na, color = color.white, linewidth = 2, display = display.all - display.price_scale - display.status_line)
above = ta.crossover(ema_ut, xATRTrailingStop)
below = ta.crossover(xATRTrailingStop, ema_ut)
buy = src > xATRTrailingStop and above
sell = src < xATRTrailingStop and below
close_buy = src < xATRTrailingStop and below
close_sell = src > xATRTrailingStop and above
barbuy = src > xATRTrailingStop
barsell = src < xATRTrailingStop
show_signals = input.bool(true, title = "Show signals ?", group = "============ Appearance ============")
paint_candles = input.bool(false, title = "Paint candles ?", group = "============ Appearance ============")
plotshape(bullish and show_signals ? buy : na, title='Buy', text='Buy', style=shape.labelup, location=location.belowbar, color=color.new(color.green, 0), textcolor=color.new(color.white, 0), size=size.tiny , display = display.all - display.price_scale - display.status_line)
plotshape(bearish and show_signals ? sell : na, title='Sell', text='Sell', style=shape.labeldown, location=location.abovebar, color=color.new(color.red, 0), textcolor=color.new(color.white, 0), size=size.tiny, display = display.all - display.price_scale - display.status_line)
plotshape(bullish and show_signals ? close_buy : na, title='Close Buy', text='Cl Buy', style=shape.labelup, location=location.belowbar, color=color.new(color.green, 80), textcolor=color.new(color.white, 0), size=size.tiny, display = display.all - display.price_scale - display.status_line)
plotshape(bearish and show_signals ? close_sell : na, title='Close Sell', text='Cl Sell', style=shape.labeldown, location=location.abovebar, color=color.new(color.red, 80), textcolor=color.new(color.white, 0), size=size.tiny, display = display.all - display.price_scale - display.status_line)
barcolor(barbuy and paint_candles ? color.green : na)
barcolor(barsell and paint_candles ? color.red : na)
// -------------- Atr stop loss by garethyeo (modified) -----------------
long_condition_atr = src > xATRTrailingStop and above
short_condition_atr = src < xATRTrailingStop and below
source_atr = input(close, title='Source', group = "============ Atr stop loss ============", inline = "A")
length_atr = input.int(14, minval=1, title='Period', group = "============ Atr stop loss ============" , inline = "A")
multiplier = input.float(1.5, minval=0.1, step=0.1, title='Atr multiplier', group = "============ Atr stop loss ============", inline = "A", tooltip = "Defines the stop loss distance based on the Atr stop loss indicator")
show_stoploss = input.bool(defval = true, title = "Show stop loss ?", group = "============ Appearance ============")
var float shortStopLoss = na
var float longStopLoss = na
var float atr_past_candle_long = na
var float atr_past_candle_short = na
//shortStopLoss = source_atr + ta.atr(length_atr) * multiplier
//longStopLoss = source_atr - ta.atr(length_atr) * multiplier
//atr_past_candle_short = close[1] + ta.atr(length_atr)[1] * multiplier[1]
//atr_past_candle_long = close[1] - ta.atr(length_atr)[1] * multiplier[1]
candle_of_stoploss = input.string(defval = "Current candle", title = "Stop loss source for atr stoploss", group = "============ Risk management for trades ============", options = ["Current candle","Past candle"])
if candle_of_stoploss == "Current candle"
shortStopLoss := source_atr + ta.atr(length_atr) * multiplier
longStopLoss := source_atr - ta.atr(length_atr) * multiplier
if candle_of_stoploss == "Past candle"
shortStopLoss := close[1] + ta.atr(length_atr)[1] * multiplier[1]
longStopLoss := close[1] - ta.atr(length_atr)[1] * multiplier[1]
// --------- Stop loss based in last swing high/low --------
high_bars = input.int(defval = 10, title = "Highest price bars: ", group = "============ Swing highs/lows stop losses ============")
low_bars = input.int(defval = 10, title = "Lowest price bars: ", group = "============ Swing highs/lows stop losses ============")
stop_high = ta.highest(high, high_bars)
stop_low = ta.lowest(low, low_bars)
// --------- Stop loss source selection ---------------
stoploss_type = input.string(defval = "Atr stop loss", title = "General stop loss source", group = "============ Risk management for trades ============", options = ["Atr stop loss","Swing high/low"])
if stoploss_type == "Atr stop loss"
shortStopLoss := source_atr + ta.atr(length_atr) * multiplier
longStopLoss := source_atr - ta.atr(length_atr) * multiplier
if candle_of_stoploss == "Past candle" and stoploss_type == "Atr stop loss"
shortStopLoss := close[1] + ta.atr(length_atr)[1] * multiplier[1]
longStopLoss := close[1] - ta.atr(length_atr)[1] * multiplier[1]
if stoploss_type == "Swing high/low"
shortStopLoss := stop_high
longStopLoss := stop_low
// Ploting stop losses
plot(show_stoploss and long_condition_atr and bullish ? longStopLoss : na, color = color.white, style = plot.style_circles, linewidth = 2)
plot(show_stoploss and short_condition_atr and bearish ? shortStopLoss : na, color = color.white, style = plot.style_circles, linewidth = 2)
// ------------- Money management --------------
strategy_contracts = strategy.equity / close
distance_sl_atr_long = -1 * (longStopLoss - close) / close
distance_sl_atr_short = (shortStopLoss - close) / close
risk = input.float(2.5, '% Account risk per trade for backtesting', step=1, group = "============ Risk management for trades ============", tooltip = "Percentage of total account to risk per trade")
long_amount = strategy_contracts * (risk / 100) / distance_sl_atr_long
short_amount = strategy_contracts * (risk / 100) / distance_sl_atr_short
// ---- Fixed amounts ----
//fixed_amounts = input.bool(defval = false, title = "Fixed amounts ?", group = "============ Risk management for trades ============")
//fixed_amount_input = input.float(defval = 1000, title = "Fixed amount in usd", group = "============ Risk management for trades ============")
//if fixed_amounts
// long_amount := fixed_amount_input / close
//if fixed_amounts
// short_amount := fixed_amount_input / close
//
leverage=input.bool(defval=true, title="Use leverage for backtesting ?", group = "============ Risk management for trades ============", tooltip = "If it is activated, there will be no monetary units or amount of assets limit for each operation (That is, each operation will not be affected by the initial / current capital since it would be using leverage). If it is deactivated, the monetary units or the amount of assets to use for each operation will be limited by the initial/current capital.")
if not leverage and long_amount>strategy_contracts
long_amount:=strategy.equity/close
if not leverage and short_amount>strategy_contracts
short_amount:=strategy.equity/close
// ---------- Risk management ---------------
risk_reward_breakeven_long= input.float(title="Risk/reward for breakeven long", defval=0.75, step=0.1, group = "============ Risk management for trades ============")
risk_reward_take_profit_long= input.float(title="Risk/reward for take profit long", defval=3.0, step=0.1, group = "============ Risk management for trades ============")
risk_reward_breakeven_short= input.float(title="Risk/reward for break even short", defval=0.75, step=0.1, group = "============ Risk management for trades ============")
risk_reward_take_profit_short= input.float(title="Risk/reward for take profit short", defval=3.0, step=0.1, group = "============ Risk management for trades ============")
tp_percent=input.float(title="% of trade for first take profit", defval=50, step=5, group = "============ Risk management for trades ============", tooltip = "Closing percentage of the current position when the first take profit is reached.")
// ------------ Trade conditions ---------------
bullish := close > ema200
bearish := close < ema200
bought = strategy.position_size > 0
sold = strategy.position_size < 0
buy := src > xATRTrailingStop and above
sell := src < xATRTrailingStop and below
var float sl_long = na
var float sl_short = na
var float be_long = na
var float be_short = na
var float tp_long = na
var float tp_short = na
if not bought
be_long:=na
sl_long:=na
tp_long:=na
if not sold
be_short:=na
sl_short:=na
tp_short:=na
long_positions = input.bool(defval = true, title = "Long positions ?", group = "============ Positions management ============")
short_positions = input.bool(defval = true, title = "Short positions ?", group = "============ Positions management ============")
use_takeprofit = input.bool(defval = true, title = "Use take profit ?", group = "============ Risk management for trades ============")
// ======================= Strategy ===================================================================================================================
// Long position with take profit
if not bought and buy and dateFilter(initial_date, final_date) and long_positions and bullish and inSession(timeSession) and use_takeprofit
sl_long:=longStopLoss
long_stoploss_distance = close - longStopLoss
be_long := close + long_stoploss_distance * risk_reward_breakeven_long
tp_long:=close+(long_stoploss_distance*risk_reward_take_profit_long)
strategy.entry('L', strategy.long, long_amount, alert_message = "Long")
strategy.exit("Tp", "L", stop=sl_long, limit=tp_long, qty_percent=tp_percent)
strategy.exit('Exit', 'L', stop=sl_long)
if bought and high > be_long
sl_long := strategy.position_avg_price
strategy.exit("Tp", "L", stop=sl_long, limit=tp_long, qty_percent=tp_percent)
strategy.exit('Exit', 'L', stop=sl_long)
if bought and sell and strategy.openprofit>0
strategy.close("L", comment="CL")
// Long position without take profit
if not bought and buy and dateFilter(initial_date, final_date) and long_positions and bullish and inSession(timeSession)
sl_long:=longStopLoss
long_stoploss_distance = close - longStopLoss
be_long := close + long_stoploss_distance * risk_reward_breakeven_long
strategy.entry('L', strategy.long, long_amount, alert_message = "Long")
strategy.exit("Tp", "L", stop=sl_long, qty_percent=tp_percent)
strategy.exit('Exit', 'L', stop=sl_long)
if bought and high > be_long
sl_long := strategy.position_avg_price
strategy.exit("Tp", "L", stop=sl_long, qty_percent=tp_percent)
strategy.exit('Exit', 'L', stop=sl_long)
if bought and sell and strategy.openprofit>0
strategy.close("L", comment="CL")
// Short position with take profit
if not sold and sell and dateFilter(initial_date, final_date) and short_positions and bearish and inSession(timeSession) and use_takeprofit
sl_short:=shortStopLoss
short_stoploss_distance=shortStopLoss - close
be_short:=((short_stoploss_distance*risk_reward_breakeven_short)-close)*-1
tp_short:=((short_stoploss_distance*risk_reward_take_profit_short)-close)*-1
strategy.entry("S", strategy.short, short_amount, alert_message = "Short")
strategy.exit("Tp", "S", stop=sl_short, limit=tp_short, qty_percent=tp_percent)
strategy.exit("Exit", "S", stop=sl_short)
if sold and low < be_short
sl_short:=strategy.position_avg_price
strategy.exit("Tp", "S", stop=sl_short, limit=tp_short, qty_percent=tp_percent)
strategy.exit("Exit", "S", stop=sl_short)
if sold and buy and strategy.openprofit>0
strategy.close("S", comment="CS")
// Short position without take profit
if not sold and sell and dateFilter(initial_date, final_date) and short_positions and bearish and inSession(timeSession)
sl_short:=shortStopLoss
short_stoploss_distance=shortStopLoss - close
be_short:=((short_stoploss_distance*risk_reward_breakeven_short)-close)*-1
strategy.entry("S", strategy.short, short_amount, alert_message = "Short")
strategy.exit("Tp", "S", stop=sl_short, qty_percent=tp_percent)
strategy.exit("Exit", "S", stop=sl_short)
if sold and low < be_short
sl_short:=strategy.position_avg_price
strategy.exit("Tp", "S", stop=sl_short, qty_percent=tp_percent)
strategy.exit("Exit", "S", stop=sl_short)
if sold and buy and strategy.openprofit>0
strategy.close("S", comment="CS")
// ===============================================================================================================================================
// ---------- Draw positions and signals on chart (strategy as an indicator) -------------
if high>tp_long
tp_long:=na
if low<tp_short
tp_short:=na
if high>be_long
be_long:=na
if low<be_short
be_short:=na
show_position_on_chart = input.bool(defval=true, title="Draw position on chart ?", group = "============ Appearance ============", tooltip = "Activate to graphically display profit, stop loss and break even")
position_price = plot(show_position_on_chart? strategy.position_avg_price : na, style=plot.style_linebr, color = color.new(#ffffff, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)
sl_long_price = plot(show_position_on_chart and bought ? sl_long : na, style = plot.style_linebr, color = color.new(color.red, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)
sl_short_price = plot(show_position_on_chart and sold ? sl_short : na, style = plot.style_linebr, color = color.new(color.red, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)
tp_long_price = plot(strategy.position_size>0 and show_position_on_chart and use_takeprofit? tp_long : na, style = plot.style_linebr, color = color.new(#4cd350, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)
tp_short_price = plot(strategy.position_size<0 and show_position_on_chart and use_takeprofit? tp_short : na, style = plot.style_linebr, color = color.new(#4cd350, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)
breakeven_long = plot(strategy.position_size>0 and high<be_long and show_position_on_chart ? be_long : na , style = plot.style_linebr, color = color.new(#1fc9fd, 60), linewidth = 1, display = display.all - display.status_line - display.price_scale)
breakeven_short = plot(strategy.position_size<0 and low>be_short and show_position_on_chart ? be_short : na , style = plot.style_linebr, color = color.new(#1fc9fd, 60), linewidth = 1, display = display.all - display.status_line - display.price_scale)
show_break_even_on_chart = input.bool(defval=true, title="Draw first take profit/breakeven price on chart ?", group = "============ Appearance ============", tooltip = "Activate to display take profit and breakeven price. It appears as a green point in the chart")
long_stoploss_distance = close - longStopLoss
short_stoploss_distance=shortStopLoss - close
be_long_plot = close + long_stoploss_distance * risk_reward_breakeven_long
be_short_plot =((short_stoploss_distance*risk_reward_breakeven_short)-close)*-1
plot(show_break_even_on_chart and buy and bullish? be_long_plot : na, color=color.new(#1fc9fd, 10), style = plot.style_circles, linewidth = 2, display = display.all - display.price_scale)
plot(show_break_even_on_chart and sell and bearish? be_short_plot : na, color=color.new(#1fc9fd, 10), style = plot.style_circles, linewidth = 2, display = display.all - display.price_scale)
position_profit_long = plot(bought and show_position_on_chart and strategy.openprofit>0 ? close : na, style = plot.style_linebr, color = color.new(#4cd350, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)
position_profit_short = plot(sold and show_position_on_chart and strategy.openprofit>0 ? close : na, style = plot.style_linebr, color = color.new(#4cd350, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)
fill(plot1 = position_price, plot2 = position_profit_long, color = color.new(#4cd350, 90))
fill(plot1 = position_price, plot2 = position_profit_short, color = color.new(#4cd350, 90))
fill(plot1 = position_price, plot2 = sl_long_price, color = color.new(color.red,90))
fill(plot1 = position_price, plot2 = sl_short_price, color = color.new(color.red,90))
fill(plot1 = position_price, plot2 = tp_long_price, color = color.new(color.green,90))
fill(plot1 = position_price, plot2 = tp_short_price, color = color.new(color.green,90))
// --------------- Positions amount calculator -------------
contracts_amount_c = initial_actual_capital / close
distance_sl_long_c = -1 * (longStopLoss - close) / close
distance_sl_short_c = (shortStopLoss - close) / close
long_amount_c = close * (contracts_amount_c * (risk_c / 100) / distance_sl_long_c)
short_amount_c = close * (contracts_amount_c * (risk_c / 100) / distance_sl_short_c)
long_amount_lev = close * (contracts_amount_c * (risk_c / 100) / distance_sl_long_c)
short_amount_lev = close * (contracts_amount_c * (risk_c / 100) / distance_sl_short_c)
leverage_for_calculator=input.bool(defval=true, title="Use leverage ?", group = "============ Calculate amount position ============", tooltip = "If it is activated, there will be no monetary units or amount of assets limit for each operation (That is, each operation will not be affected by the initial / current capital since it would be using leverage). If it is deactivated, the monetary units or the amount of assets to use for each operation will be limited by the initial/current capital.")
if not leverage_for_calculator and long_amount_lev>initial_actual_capital
long_amount_lev:=initial_actual_capital
if not leverage_for_calculator and short_amount_lev>initial_actual_capital
short_amount_lev:=initial_actual_capital
plot(buy and leverage_for_calculator ? long_amount_c : na, color = color.rgb(136, 255, 0), display = display.all - display.pane - display.price_scale)
plot(sell and leverage_for_calculator ? short_amount_c : na, color = color.rgb(136, 255, 0), display = display.all - display.pane - display.price_scale)
plot(buy and not leverage_for_calculator ? long_amount_lev : na, color = color.rgb(136, 255, 0), display = display.all - display.pane - display.price_scale)
plot(sell and not leverage_for_calculator ? short_amount_lev : na, color = color.rgb(136, 255, 0), display = display.all - display.pane - display.price_scale)
|
8 Day Run - Momentum Strategy | https://www.tradingview.com/script/fXvKVs5J-8-Day-Run-Momentum-Strategy/ | Marcn5_ | https://www.tradingview.com/u/Marcn5_/ | 133 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Marcuscor
//@version=5
// Inpsired by Linda Bradford Raschke: a strategy for trading momentum in futures markets
strategy("8D Run", initial_capital = 50000, commission_value = 0.0004)
SMA = ta.sma(close,5)
TrendUp = close >= SMA
TrendDown = close <= SMA
//logic to long
TriggerBuy = ta.barssince(close < SMA) >= 8
Buy = TriggerBuy[1] and TrendDown
strategy.entry("EL", strategy.long, when = Buy)
strategy.close(id = "EL", when = close > SMA)
// 1) color background when "run" begins and 2) change color when buy signal occurs
bgcolor(TriggerBuy? color.green : na, transp = 90)
bgcolor(Buy ? color.green : na, transp = 70)
// logic to short
TriggerSell = ta.barssince(close > SMA) >= 8
Sell = TriggerSell[1] and TrendUp
strategy.entry("ES", strategy.short, when = Sell)
strategy.close(id = "ES", when = close < SMA)
// 1) color background when "run" begins and 2) change color when sell signal occurs
bgcolor(TriggerSell ? color.red : na, transp = 90)
bgcolor(Sell ? color.red : na, transp = 70)
|
Zazzamira 50-25-25 Trend System | https://www.tradingview.com/script/QuXIq7UK-Zazzamira-50-25-25-Trend-System/ | philipbianchi | https://www.tradingview.com/u/philipbianchi/ | 156 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Hiubris_Indicators
//@version=5
strategy(title = "Zazzamira 50-25-25 Trend System", overlay = true, default_qty_value = 4, initial_capital=100000,default_qty_type=strategy.fixed, pyramiding=0, process_orders_on_close=true, max_lines_count=500)
// Open Session
tz0 = input.string('UTC-5', title="Timezone", inline='tz', group='Time-Range Settings')
auto_tz = input(true, title="Exchange Timezone", inline='tz', group='Time-Range Settings')
tz = auto_tz? syminfo.timezone : tz0
timeinput = input.session('0830-0915', title="Opening Range", group='Time-Range Settings') + ':1234567'
tses_time = time(timeframe.period, timeinput, tz)
tses = na(tses_time) ? 0 : 1
end_t = tses[1] and not tses
start_t = tses and not tses[1]
// Trading Session
session = input.session("0915-1300", title="Trading Time")+":1234567"
t = time(timeframe.period, session, tz)
trading_session_filter = na(t) ? 0 : 1
t_exit = time(timeframe.period, "1500-0000:1234567", tz)
trading_session_exit = na(t_exit) ? 0 : 1
// Highs Lows - Open sesssion
h = 0.0
l = 0.0
h := start_t ? high : tses and high > h[1] ? high : h[1]
l := start_t ? low : tses and low < l[1] ? low : l[1]
r = h-l
last_start_n = ta.valuewhen(start_t, bar_index, 0)
//col = input.color(color.orange, title="Levels Color")
draw_level(txt, x, col)=>
if start_t
line.new (bar_index-4, x, last_start_n[1], x, color=col)
label.new(bar_index-10, x, style=label.style_none, text=txt, color=col, textcolor=col)
l1 = h+r*0.216
l2 = h+r*0.618
l3 = h+r*1
l4 = h+r*1.618
s1 = l-r*0.216
s2 = l-r*0.618
s3 = l-r*1
s4 = l-r*1.618
plot(tses? na : h, style=plot.style_linebr, title="H", color=color.green)
plot(tses? na : l, style=plot.style_linebr, title="L", color=color.green)
plot(tses? na : l1, style=plot.style_linebr, title="Fib 1", color=color.orange)
plot(tses? na : l2, style=plot.style_linebr, title="Fib 2", color=color.orange)
plot(tses? na : l3, style=plot.style_linebr, title="Fib 3", color=color.orange)
plot(tses? na : l4, style=plot.style_linebr, title="Fib 4", color=color.orange)
plot(tses? na : s1, style=plot.style_linebr, title="Fib 1", color=color.orange)
plot(tses? na : s2, style=plot.style_linebr, title="Fib 2", color=color.orange)
plot(tses? na : s3, style=plot.style_linebr, title="Fib 3", color=color.orange)
plot(tses? na : s4, style=plot.style_linebr, title="Fib 4", color=color.orange)
//draw_level('H' , h[1], color.gray )
//draw_level('Fib 23.6% ' , l1, color.yellow)
//draw_level('Fib 61.8% ' , l2, color.orange)
//draw_level('Fib 100% ' , l3, color.orange)
//draw_level('Fib 161.8% ', l4, color.orange)
//draw_level('H' , l[1], color.gray )
//draw_level('Fib 23.6% ' , s1, color.yellow)
//draw_level('Fib 61.8% ' , s2, color.orange)
//draw_level('Fib 100% ' , s3, color.orange)
//draw_level('Fib 161.8% ', s4, color.orange)
bgcolor(tses?color.new(color.orange , 80):na)
plotshape(ta.crossover (close, h) and not tses and trading_session_filter, textcolor=color.lime, color=color.lime, style=shape.triangleup , title="Cross", text="" , location=location.belowbar, offset=0, size=size.tiny)
plotshape(ta.crossunder(close, l) and not tses and trading_session_filter, textcolor=color.red, color=color.red, style=shape.triangledown, title="Cross", text="", location=location.abovebar, offset=0, size=size.tiny)
// ————— MA
ribbon_grp = "MA SETTINGS"
ma(source, length, type) =>
type == "SMA" ? ta.sma(source, length) :
type == "EMA" ? ta.ema(source, length) :
type == "SMMA (RMA)" ? ta.rma(source, length) :
type == "WMA" ? ta.wma(source, length) :
type == "VWMA" ? ta.vwma(source, length) :
na
ma1_type = input.string("EMA" , "" , inline="MA #1", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group=ribbon_grp)
ma1_source = input.source(close , "" , inline="MA #1", group=ribbon_grp)
ma1_length = input.int (5 , "" , inline="MA #1", minval=1, group=ribbon_grp)
ma1 = ma(ma1_source, ma1_length, ma1_type)
plot(ma1, color = color.green, title="MA №1")
ma2_type = input.string("EMA" , "" , inline="MA #2", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group=ribbon_grp)
ma2_source = input.source(close , "" , inline="MA #2", group=ribbon_grp)
ma2_length = input.int (13 , "" , inline="MA #2", minval=1, group=ribbon_grp)
ma2 = ma(ma2_source, ma2_length, ma2_type)
plot(ma2, color = color.orange, title="MA №2")
use_3 = input(true, title='Use 3rd MA as Entry Condition')
ma3_type = input.string("EMA" , "" , inline="MA #3", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group=ribbon_grp)
ma3_source = input.source(close , "" , inline="MA #3", group=ribbon_grp)
ma3_length = input.int (34 , "" , inline="MA #3", minval=1, group=ribbon_grp)
ma3 = ma(ma3_source, ma3_length, ma3_type)
plot(ma3, color = color.blue, title="MA №3")
ma4_type = input.string("EMA" , "" , inline="MA #4", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group=ribbon_grp)
ma4_source = input.source(close , "" , inline="MA #4", group=ribbon_grp)
ma4_length = input.int (50 , "" , inline="MA #4", minval=1, group=ribbon_grp)
ma4 = ma(ma4_source, ma4_length, ma4_type)
plot(ma4, color = color.red, title="MA #4")
ma_long = ma1>ma2 and ma2>ma3 and ma3>ma4
ma_short= ma1<ma2 and ma2<ma3 and ma3<ma4
long0 = ma_long and trading_session_filter and high<l1 and ta.crossover (close, h)
short0= ma_short and trading_session_filter and low >s1 and ta.crossunder(close, l)
long_setup = 0
long_setup:= high>l1? 0 : long0? 1 : long_setup[1]
long = low<h and long_setup[1]==1
if long
long_setup := 0
short_setup = 0
short_setup:= low<s1? 0 : short0? 1 : short_setup[1]
short = high>l and short_setup[1]==1
if short
short_setup := 0
retest = input(true, title='Use RETEST')
longf = retest? long : long0
shortf= retest? short : short0
// Position Management Tools
pos = 0.0
pos:= longf? 1 : shortf? -1 : pos[1]
longCond = longf and (pos[1]!= 1 or na(pos[1]))
shortCond = shortf and (pos[1]!=-1 or na(pos[1]))
// EXIT FUNCTIONS //
atr = ta.atr(14)
sl = input.float(1.0, title="Initial Stop Loss ATR", minval=0, step=0.1)
atr_long = ta.valuewhen(longCond , atr, 0)
atr_short = ta.valuewhen(shortCond, atr, 0)
tp_long = l3
tp_short = s3
// Inprofit
inprofit_long = 0
inprofit_short = 0
inprofit_long := pos==0 or longCond ? 0 : high>l1[1]? 1 : inprofit_long [1]
inprofit_short := pos==0 or shortCond? 0 : low <s1[1]? 1 : inprofit_short[1]
inprofit_long2 = 0
inprofit_short2 = 0
inprofit_long2 := pos==0 or longCond ? 0 : high>l2[1]? 1 : inprofit_long2 [1]
inprofit_short2 := pos==0 or shortCond? 0 : low <s2[1]? 1 : inprofit_short2[1]
// Trailing Stop Loss
trail_long = 0.0, trail_short = 0.0
trail_long := long0 ? h : longCond ? high : high>trail_long[1]? high : pos<1 ? 0 : trail_long[1]
trail_short := short0? l : shortCond? low : low<trail_short[1]? low : pos>-1 ? 99999 : trail_short[1]
trail_long_final1 = trail_long - sl * atr_long
trail_short_final1 = trail_short + sl * atr_short
trail_long_final2 = trail_long - r * 0.236
trail_short_final2 = trail_short + r * 0.236
trail_long_final3 = trail_long - r * 0.382
trail_short_final3 = trail_short + r * 0.382
sl_long = inprofit_long2 ? trail_long_final3 : inprofit_long ? trail_long_final2 : trail_long_final1
sl_short = inprofit_short2? trail_short_final3 : inprofit_short? trail_short_final2 : trail_short_final1
// Position Adjustment
long_sl = low <sl_long[1] and pos[1]== 1
short_sl = high>sl_short[1] and pos[1]==-1
final_long_tp = high>tp_long[1] and pos[1]== 1
final_short_tp = low <tp_short[1] and pos[1]==-1
if ((long_sl or final_long_tp) and not shortCond) or ((short_sl or final_short_tp) and not longCond)
pos:=0
// Strategy Backtest Limiting Algorithm
i_startTime = input.time(defval = timestamp("01 Sep 2002 13:30 +0000"), title = "Backtesting Start Time")
i_endTime = input.time(defval = timestamp("30 Sep 2099 19:30 +0000"), title = "Backtesting End Time" )
timeCond = (time > i_startTime) and (time < i_endTime)
equity = strategy.initial_capital + strategy.netprofit
if equity>0 and timeCond
if long0
strategy.entry("long" , strategy.long , limit=h)
if short0
strategy.entry("short", strategy.short, limit=l)
strategy.exit("SL/TP1", from_entry = "long" , stop=sl_long , limit=l1 , comment_profit ='TP1', comment_loss='SL', qty_percent=50)
strategy.exit("SL/TP2", from_entry = "long" , stop=sl_long , limit=l2 , comment_profit ='TP2', comment_loss='SL', qty_percent=25)
strategy.exit("SL/TP3", from_entry = "long" , stop=sl_long , limit=l3 , comment_profit ='TP3', comment_loss='SL')
strategy.exit("SL/TP1", from_entry = "short", stop=sl_short, limit=s1, comment_profit ='TP1', comment_loss='SL', qty_percent=50)
strategy.exit("SL/TP2", from_entry = "short", stop=sl_short, limit=s2, comment_profit ='TP2', comment_loss='SL', qty_percent=25)
strategy.exit("SL/TP3", from_entry = "short", stop=sl_short, limit=s3, comment_profit ='TP3', comment_loss='SL')
if high>l1 or not trading_session_filter
strategy.cancel('long')
if low<s1 or not trading_session_filter
strategy.cancel('short')
long_exit = trading_session_exit and pos[1]== 1
short_exit= trading_session_exit and pos[1]==-1
if (long_exit and not shortCond) or (short_exit and not longCond)
pos:=0
strategy.close("long" , when=long_exit and timeCond, comment="Exit")
strategy.close("short", when=short_exit and timeCond, comment="Exit")
// DEBUGGING
bgcolor(long ?color.new(color.green , 80):na)
bgcolor(short?color.new(color.red , 80):na)
bgcolor(false?color.new(color.white , 80):na)
bgcolor(false?color.new(color.orange , 80):na) |
Reinforced RSI - The Quant Science | https://www.tradingview.com/script/mjIwVkql-Reinforced-RSI-The-Quant-Science/ | thequantscience | https://www.tradingview.com/u/thequantscience/ | 81 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © thequantscience
//@version=5
strategy("Reinforced RSI - The Quant Science",
overlay = true,
default_qty_type = strategy.percent_of_equity,
default_qty_value = 100,
pyramiding = 1,
currency = currency.EUR,
initial_capital = 1000,
commission_type = strategy.commission.percent,
commission_value = 0.07)
lenght_rsi = input.int(defval = 14, minval = 1, title = "RSI lenght: ")
rsi = ta.rsi(close, length = lenght_rsi)
rsi_value_check_entry = input.int(defval = 35, minval = 1, title = "Oversold: ")
rsi_value_check_exit = input.int(defval = 75, minval = 1, title = "Overbought: ")
trigger = ta.crossunder(rsi, rsi_value_check_entry)
exit = ta.crossover(rsi, rsi_value_check_exit)
entry_condition = trigger
TPcondition_exit = exit
look = input.int(defval = 30, minval = 0, maxval = 500, title = "Lookback period: ")
Probabilities(lookback) =>
isActiveLong = false
isActiveLong := nz(isActiveLong[1], false)
isSellLong = false
isSellLong := nz(isSellLong[1], false)
int positive_results = 0
int negative_results = 0
float positive_percentage_probabilities = 0
float negative_percentage_probabilities = 0
LONG = not isActiveLong and entry_condition == true
CLOSE_LONG_TP = not isSellLong and TPcondition_exit == true
p = ta.valuewhen(LONG, close, 0)
p2 = ta.valuewhen(CLOSE_LONG_TP, close, 0)
for i = 1 to lookback
if (LONG[i])
isActiveLong := true
isSellLong := false
if (CLOSE_LONG_TP[i])
isActiveLong := false
isSellLong := true
if p[i] > p2[i]
positive_results += 1
else
negative_results += 1
positive_relative_probabilities = positive_results / lookback
negative_relative_probabilities = negative_results / lookback
positive_percentage_probabilities := positive_relative_probabilities * 100
negative_percentage_probabilities := negative_relative_probabilities * 100
positive_percentage_probabilities
probabilities = Probabilities(look)
lots = strategy.equity/close
var float e = 0
var float c = 0
tp = input.float(defval = 1.00, minval = 0, title = "Take profit: ")
sl = input.float(defval = 1.00, minval = 0, title = "Stop loss: ")
if trigger==true and strategy.opentrades==0 and probabilities >= 51
e := close
strategy.entry(id = "e", direction = strategy.long, qty = lots, limit = e)
takeprofit = e + ((e * tp)/100)
stoploss = e - ((e * sl)/100)
if exit==true
c := close
strategy.exit(id = "c", from_entry = "e", limit = c)
if takeprofit and stoploss
strategy.exit(id = "c", from_entry = "e", stop = stoploss, limit = takeprofit) |
Ema Scalp | https://www.tradingview.com/script/kUncyS8L-Ema-Scalp/ | Shauryam_or | https://www.tradingview.com/u/Shauryam_or/ | 542 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Shauryam_or
//@version=5
strategy('Ema Scalp', overlay=true)
// Moving Averages to get some example trades generated
eg1 = ta.ema(close, 100)
plot(eg1,color=color.aqua)
long = close>eg1
short = close<eg1
var countbuy=0
if long
countbuy:=countbuy+1
if strategy.position_size<0
countbuy:=0
var countsell=0
if short
countsell:=countsell+1
if strategy.position_size>0
countsell:=0
////////////////////////////////
// stratgey started
if long and strategy.opentrades==0 and countbuy==1 // open first long when close>ema
strategy.entry("enter long", strategy.long)
if short and strategy.opentrades==0 and countsell==1 // open first short when close<ema
strategy.entry("enter short", strategy.short)
// checking last trade is long or short
is_pos_closed = (strategy.position_size[1] != 0 and strategy.position_size == 0) or ((strategy.position_size[1] * strategy.position_size) < 0)
is_long = strategy.position_size > 0
is_short = strategy.position_size < 0
ptrade_islong=is_pos_closed and is_long[1]
ptrade_isshort=is_pos_closed and is_short[1]
// checking is last trade is profit
var lastTradeWasprofit = false
if (strategy.wintrades[0] > strategy.wintrades[1])
// last trade was a profit
lastTradeWasprofit := true
if (strategy.losstrades[0] > strategy.losstrades[1])
// unsuccessful trade, reset
lastTradeWasprofit := false
// if last trade is a long trade and loss and close>ema open 2nd trade long side
new_counnb=0
new_couns=0
if lastTradeWasprofit and ptrade_islong
new_counnb:=new_counnb+1
if lastTradeWasprofit and ptrade_isshort
new_couns:=new_couns+1
if lastTradeWasprofit and ptrade_islong
strategy.entry("El2",strategy.long,comment ="long")
if lastTradeWasprofit and ptrade_isshort
strategy.entry("Es2",strategy.short,comment ="short")
//exit in percentage
// User Options to Change Inputs (%)
stopPer = input.float(0.8,step=0.1, title='Stop Loss %') / 100
takePer = input.float(1.0,step=0.1, title='Take Profit %') / 100
// Determine where you've entered and in what direction
longStop =strategy.position_avg_price * (1 - stopPer)
shortStop =strategy.position_avg_price * (1 + stopPer)
shortTake =strategy.position_avg_price * (1 - takePer)
longTake =strategy.position_avg_price * (1 + takePer)
if strategy.position_size > 0
strategy.exit(id='Close Long',from_entry = "enter long", stop=longStop, limit=longTake)
if strategy.position_size < 0
strategy.exit(id='Close Short',from_entry = "enter short", stop=shortStop, limit=shortTake)
if strategy.position_size > 0
strategy.exit(id='Close Long2',from_entry = "El2", stop=longStop, limit=longTake)
if strategy.position_size < 0
strategy.exit(id='Close Short2',from_entry = "Es2", stop=shortStop, limit=shortTake)
//PLOT FIXED SLTP LINE
plot(strategy.position_size > 0 ? longStop : na, style=plot.style_linebr, color=color.new(color.red, 0), linewidth=1, title='Long Fixed SL')
plot(strategy.position_size < 0 ? shortStop : na, style=plot.style_linebr, color=color.new(color.red, 0), linewidth=1, title='Short Fixed SL')
plot(strategy.position_size > 0 ? longTake : na, style=plot.style_linebr, color=color.new(color.green, 0), linewidth=1, title='Long Take Profit')
plot(strategy.position_size < 0 ? shortTake : na, style=plot.style_linebr, color=color.new(color.green, 0), linewidth=1, title='Short Take Profit')
|
Strategy Myth-Busting #9 - HullSuite+LSMA - [MYN] | https://www.tradingview.com/script/SypjeOFx-Strategy-Myth-Busting-9-HullSuite-LSMA-MYN/ | myncrypto | https://www.tradingview.com/u/myncrypto/ | 190 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © myn
//@version=5
strategy('Strategy Myth-Busting #9 - HullSuite+LSMA - [MYN]', max_bars_back=5000, overlay=true, pyramiding=0, initial_capital=1000, currency='USD', default_qty_type=strategy.percent_of_equity, default_qty_value=1.0, commission_value=0.075, use_bar_magnifier = false)
// Hull Suite by InSilico
// Least Squares Moving Average
// Long
// Hull Suite is red and LSMA crosses above HUll Suite while red
// Stop loss latest swing low
//Short
// Hull Suite is green and LSMA crosses under HUll Suite while green
// Stop loss latest swing high
//1:4 Risk ratio
// 1 minute timeframe
/////////////////////////////////////
//* Put your strategy logic below *//
/////////////////////////////////////
//72iE0gCVjvM
// LSMA
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
//@version=5
//indicator(title = "Least Squares Moving Average", shorttitle="LSMA", overlay=true, timeframe="", timeframe_gaps=true)
length1 = input(title="Length", defval=25, group="Least Squares Moving Average (LSMA)")
offset1 = input(title="Offset", defval=0)
src1 = input(close, title="Source")
lsma = ta.linreg(src1, length1, offset1)
plot(lsma, color=color.white)
// Hull Suite by InSilico
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
//@version=5
//Basic Hull Ma Pack tinkered by InSilico
//indicator('Hull Suite by InSilico', overlay=true)
//INPUT
src = input(close, title='Source', group="Hull Suite")
modeSwitch = input.string('Hma', title='Hull Variation', options=['Hma', 'Thma', 'Ehma'])
length = input(55, title='Length(180-200 for floating S/R , 55 for swing entry)')
lengthMult = input(1.0, title='Length multiplier (Used to view higher timeframes with straight band)')
useHtf = input(false, title='Show Hull MA from X timeframe? (good for scalping)')
htf = input.timeframe('240', title='Higher timeframe')
switchColor = input(true, 'Color Hull according to trend?')
candleCol = input(false, title='Color candles based on Hull\'s Trend?')
visualSwitch = input(false, title='Show as a Band?')
thicknesSwitch = input(1, title='Line Thickness')
transpSwitch = input.int(40, title='Band Transparency', step=5)
//FUNCTIONS
//HMA
HMA(_src, _length) =>
ta.wma(2 * ta.wma(_src, _length / 2) - ta.wma(_src, _length), math.round(math.sqrt(_length)))
//EHMA
EHMA(_src, _length) =>
ta.ema(2 * ta.ema(_src, _length / 2) - ta.ema(_src, _length), math.round(math.sqrt(_length)))
//THMA
THMA(_src, _length) =>
ta.wma(ta.wma(_src, _length / 3) * 3 - ta.wma(_src, _length / 2) - ta.wma(_src, _length), _length)
//SWITCH
Mode(modeSwitch, src, len) =>
modeSwitch == 'Hma' ? HMA(src, len) : modeSwitch == 'Ehma' ? EHMA(src, len) : modeSwitch == 'Thma' ? THMA(src, len / 2) : na
//OUT
_hull = Mode(modeSwitch, src, int(length * lengthMult))
HULL = useHtf ? request.security(syminfo.ticker, htf, _hull) : _hull
MHULL = HULL[0]
SHULL = HULL[2]
//COLOR
hullColor = switchColor ? HULL > HULL[2] ? #00ff00 : #ff0000 : #ff9800
//PLOT
///< Frame
Fi1 = plot(MHULL, title='MHULL', color=hullColor, linewidth=thicknesSwitch, transp=50)
Fi2 = plot(visualSwitch ? SHULL : na, title='SHULL', color=hullColor, linewidth=thicknesSwitch, transp=50)
alertcondition(ta.crossover(MHULL, SHULL), title='Hull trending up.', message='Hull trending up.')
alertcondition(ta.crossover(SHULL, MHULL), title='Hull trending down.', message='Hull trending down.')
///< Ending Filler
fill(Fi1, Fi2, title='Band Filler', color=hullColor, transp=transpSwitch)
///BARCOLOR
barcolor(color=candleCol ? switchColor ? hullColor : na : na)
// Long
// Hull Suite is red and LSMA crosses above HUll Suite while red
// Stop loss latest swing low
//Short
// Hull Suite is green and LSMA crosses under HUll Suite while green
// Stop loss latest swing high
//1:4 Risk ratio
longEntry = hullColor == #ff0000 and ta.crossover(lsma, MHULL )
shortEntry = hullColor == #00ff00 and ta.crossunder(lsma, MHULL)
//////////////////////////////////////
//* Put your strategy rules below *//
/////////////////////////////////////
longCondition = longEntry
shortCondition = shortEntry
//define as 0 if do not want to use
closeLongCondition = 0
closeShortCondition = 0
// ADX
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
adxEnabled = input.bool(defval = false , title = "Average Directional Index (ADX)", tooltip = "", group ="ADX" )
adxlen = input(14, title="ADX Smoothing", group="ADX")
adxdilen = input(14, title="DI Length", group="ADX")
adxabove = input(25, title="ADX Threshold", group="ADX")
adxdirmov(len) =>
adxup = ta.change(high)
adxdown = -ta.change(low)
adxplusDM = na(adxup) ? na : (adxup > adxdown and adxup > 0 ? adxup : 0)
adxminusDM = na(adxdown) ? na : (adxdown > adxup and adxdown > 0 ? adxdown : 0)
adxtruerange = ta.rma(ta.tr, len)
adxplus = fixnan(100 * ta.rma(adxplusDM, len) / adxtruerange)
adxminus = fixnan(100 * ta.rma(adxminusDM, len) / adxtruerange)
[adxplus, adxminus]
adx(adxdilen, adxlen) =>
[adxplus, adxminus] = adxdirmov(adxdilen)
adxsum = adxplus + adxminus
adx = 100 * ta.rma(math.abs(adxplus - adxminus) / (adxsum == 0 ? 1 : adxsum), adxlen)
adxsig = adxEnabled ? adx(adxdilen, adxlen) : na
isADXEnabledAndAboveThreshold = adxEnabled ? (adxsig > adxabove) : true
//Backtesting Time Period (Input.time not working as expected as of 03/30/2021. Giving odd start/end dates
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
useStartPeriodTime = input.bool(true, 'Start', group='Date Range', inline='Start Period')
startPeriodTime = input.time(timestamp('1 Jan 2019'), '', group='Date Range', inline='Start Period')
useEndPeriodTime = input.bool(true, 'End', group='Date Range', inline='End Period')
endPeriodTime = input.time(timestamp('31 Dec 2030'), '', group='Date Range', inline='End Period')
start = useStartPeriodTime ? startPeriodTime >= time : false
end = useEndPeriodTime ? endPeriodTime <= time : false
calcPeriod = not start and not end
// Trade Direction
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tradeDirection = input.string('Long and Short', title='Trade Direction', options=['Long and Short', 'Long Only', 'Short Only'], group='Trade Direction')
// Percent as Points
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
per(pcnt) =>
strategy.position_size != 0 ? math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na)
// Take profit 1
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp1 = input.float(title='Take Profit 1 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 1')
q1 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 1')
// Take profit 2
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp2 = input.float(title='Take Profit 2 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 2')
q2 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 2')
// Take profit 3
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp3 = input.float(title='Take Profit 3 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 3')
q3 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 3')
// Take profit 4
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp4 = input.float(title='Take Profit 4 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit')
/// Stop Loss
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
stoplossPercent = input.float(title='Stop Loss (%)', defval=999, minval=0.01, group='Stop Loss') * 0.01
slLongClose = close < strategy.position_avg_price * (1 - stoplossPercent)
slShortClose = close > strategy.position_avg_price * (1 + stoplossPercent)
/// Leverage
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
leverage = input.float(1, 'Leverage', step=.5, group='Leverage')
contracts = math.min(math.max(.000001, strategy.equity / close * leverage), 1000000000)
/// Trade State Management
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
isInLongPosition = strategy.position_size > 0
isInShortPosition = strategy.position_size < 0
/// ProfitView Alert Syntax String Generation
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
alertSyntaxPrefix = input.string(defval='CRYPTANEX_99FTX_Strategy-Name-Here', title='Alert Syntax Prefix', group='ProfitView Alert Syntax')
alertSyntaxBase = alertSyntaxPrefix + '\n#' + str.tostring(open) + ',' + str.tostring(high) + ',' + str.tostring(low) + ',' + str.tostring(close) + ',' + str.tostring(volume) + ','
/// Trade Execution
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
longConditionCalc = (longCondition and isADXEnabledAndAboveThreshold)
shortConditionCalc = (shortCondition and isADXEnabledAndAboveThreshold)
if calcPeriod
if longConditionCalc and tradeDirection != 'Short Only' and isInLongPosition == false
strategy.entry('Long', strategy.long, qty=contracts)
alert(message=alertSyntaxBase + 'side:long', freq=alert.freq_once_per_bar_close)
if shortConditionCalc and tradeDirection != 'Long Only' and isInShortPosition == false
strategy.entry('Short', strategy.short, qty=contracts)
alert(message=alertSyntaxBase + 'side:short', freq=alert.freq_once_per_bar_close)
//Inspired from Multiple %% profit exits example by adolgo https://www.tradingview.com/script/kHhCik9f-Multiple-profit-exits-example/
strategy.exit('TP1', qty_percent=q1, profit=per(tp1))
strategy.exit('TP2', qty_percent=q2, profit=per(tp2))
strategy.exit('TP3', qty_percent=q3, profit=per(tp3))
strategy.exit('TP4', profit=per(tp4))
strategy.close('Long', qty_percent=100, comment='SL Long', when=slLongClose)
strategy.close('Short', qty_percent=100, comment='SL Short', when=slShortClose)
strategy.close_all(when=closeLongCondition or closeShortCondition, comment='Close Postion')
/// Dashboard
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Inspired by https://www.tradingview.com/script/uWqKX6A2/ - Thanks VertMT
showDashboard = input.bool(group="Dashboard", title="Show Dashboard", defval=true)
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
_cellText = _title + "\n" + _value
table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=size.auto)
// Draw dashboard table
if showDashboard
var bgcolor = color.new(color.black,0)
// Keep track of Wins/Losses streaks
newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
varip int winRow = 0
varip int lossRow = 0
varip int maxWinRow = 0
varip int maxLossRow = 0
if newWin
lossRow := 0
winRow := winRow + 1
if winRow > maxWinRow
maxWinRow := winRow
if newLoss
winRow := 0
lossRow := lossRow + 1
if lossRow > maxLossRow
maxLossRow := lossRow
// Prepare stats table
var table dashTable = table.new(position.bottom_right, 1, 15, border_width=1)
if barstate.islastconfirmedhistory
// Update table
dollarReturn = strategy.netprofit
f_fillCell(dashTable, 0, 0, "Start:", str.format("{0,date,long}", strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.closedtrades.entry_time(0))
f_fillCell(dashTable, 0, 1, "End:", str.format("{0,date,long}", strategy.opentrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.opentrades.entry_time(0))
_profit = (strategy.netprofit / strategy.initial_capital) * 100
f_fillCell(dashTable, 0, 2, "Net Profit:", str.tostring(_profit, '##.##') + "%", _profit > 0 ? color.green : color.red, color.white)
_numOfDaysInStrategy = (strategy.opentrades.entry_time(0) - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24)
f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit / _numOfDaysInStrategy, '#########################.#####')+"%", _profit > 0 ? color.green : color.red, color.white)
_winRate = ( strategy.wintrades / strategy.closedtrades ) * 100
f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? color.red : _winRate < 75 ? #999900 : color.green, color.white)
f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? color.green : color.red, color.white)
f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white)
f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white)
f_fillCell(dashTable, 0, 9, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white) |
Trading Day and Time Session | https://www.tradingview.com/script/CEpWWHDi-Trading-Day-and-Time-Session/ | Dannnnnnny | https://www.tradingview.com/u/Dannnnnnny/ | 40 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Dannnnnnny
//@version=5
strategy(title="Trade Day-Time Session", overlay = true)
//Session=====================================================================
fromDay = input.int(defval = 1, title = "From", minval = 1, maxval = 31, inline="1", group='Trade Session')
fromMonth = input.int(defval = 1, title = "", minval = 1, maxval = 12,inline="1", group='Trade Session')
fromYear = input.int(defval = 2010, title = "", minval = 1970, inline="1", group='Trade Session')
toDay = input.int(defval = 31, title = "To", minval = 1, maxval = 31, inline="2", group='Trade Session')
toMonth = input.int(defval = 12, title = "", minval = 1, maxval = 12, inline="2",group='Trade Session')
toYear = input.int(defval = 2099, title = "", minval = 1970, inline="2",group='Trade Session')
startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
date_cond = time >= startDate and time <= finishDate
i_sess = input.session("0400-1900", "Trade time", group='Trade Session')
UTC_offset = input.int(3, title='UTC Offset', minval=-10, maxval=13, group='Trade Session')
UTC_string = 'UTC' + (UTC_offset > 0 ? '+' : '') + (UTC_offset != 0 ? str.tostring(UTC_offset) : '')
time_cond = time(timeframe.period, i_sess, UTC_string)
is_trade_mon = input(true, title="Trade Monday?", group='Trade Session')
is_trade_tue = input(true, title="Trade Tuesday?", group='Trade Session')
is_trade_wed = input(true, title="Trade Wednesday?", group='Trade Session')
is_trade_thu = input(true, title="Trade Thursday?", group='Trade Session')
is_trade_fri = input(true, title="Trade Friday?", group='Trade Session')
is_trade_sat = input(false, title="Trade Saturday?", group='Trade Session')
is_trade_sun = input(false, title="Trade Sunday?", group='Trade Session')
day_cond = false
if(dayofweek(time_cond, UTC_string) == dayofweek.monday and is_trade_mon)
day_cond := true
else if(dayofweek(time_cond, UTC_string) == dayofweek.tuesday and is_trade_tue)
day_cond := true
else if(dayofweek(time_cond, UTC_string) == dayofweek.wednesday and is_trade_wed)
day_cond := true
else if(dayofweek(time_cond, UTC_string) == dayofweek.thursday and is_trade_thu)
day_cond := true
else if(dayofweek(time_cond, UTC_string) == dayofweek.friday and is_trade_fri)
day_cond := true
else if(dayofweek(time_cond, UTC_string) == dayofweek.saturday and is_trade_sat)
day_cond := true
else if(dayofweek(time_cond, UTC_string) == dayofweek.sunday and is_trade_sun)
day_cond := true
bgcolor(time == time_cond and day_cond ? color.new(color.gray,90) : na)
final_time_cond = time == time_cond and day_cond and date_cond
//=====================================================================
maLength= 400
wma= ta.vwma(hl2,maLength)
uptrend= ta.rising(wma, 5)
downtrend= ta.falling(wma,5)
plot(wma)
if(final_time_cond)
if uptrend
strategy.entry("Buy", strategy.long)
else
strategy.close("Buy")
|
Strategy Myth-Busting #11 - TrendMagic+SqzMom+CDV - [MYN] | https://www.tradingview.com/script/GyTR3NKT-Strategy-Myth-Busting-11-TrendMagic-SqzMom-CDV-MYN/ | myncrypto | https://www.tradingview.com/u/myncrypto/ | 230 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © myn
//@version=5
strategy('Strategy Myth-Busting #11 - TrendMagic+SqzMom+CDV - [MYN]', max_bars_back=5000, overlay=true, pyramiding=0, initial_capital=1000, currency='USD', default_qty_type=strategy.percent_of_equity, default_qty_value=1, commission_value=0.075, use_bar_magnifier = false)
// HA to Regular Candlestick resolover
useHA = input.bool(true, "Use Heiken Ashi")
CLOSE = close
OPEN = open
HIGH = high
LOW = low
CLOSE := useHA ? (OPEN + CLOSE + HIGH + LOW) / 4 : CLOSE
OPEN := useHA ? na(OPEN[1]) ? (OPEN + CLOSE) / 2: (OPEN[1] + CLOSE[1]) / 2 : OPEN
HIGH := useHA ? math.max(HIGH, math.max(OPEN, CLOSE)) : HIGH
LOW := useHA ? math.min(LOW, math.min(OPEN, CLOSE)) : LOW
isCrypto = input.bool(true, "Is Crypto?")
// Functions
f_priorBarsSatisfied(_objectToEval, _numOfBarsToLookBack) =>
returnVal = false
for i = 0 to _numOfBarsToLookBack
if (_objectToEval[i] == true)
returnVal = true
/////////////////////////////////////
//* Put your strategy logic below *//
/////////////////////////////////////
// Trend Magic by KivancOzbilgic
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
period = input(20, 'CCI period')
coeff = input(2, 'ATR Multiplier')
AP = input(5, 'ATR Period')
ATR = ta.sma(ta.tr, AP)
src = CLOSE
upT = LOW - ATR * coeff
downT = HIGH + ATR * coeff
MagicTrend = 0.0
MagicTrend := ta.cci(src, period) >= 0 ? upT < nz(MagicTrend[1]) ? nz(MagicTrend[1]) : upT : downT > nz(MagicTrend[1]) ? nz(MagicTrend[1]) : downT
color1 = ta.cci(src, period) >= 0 ? #0022FC : #FC0400
plot(MagicTrend, color=color1, linewidth=3)
alertcondition(ta.cross(CLOSE, MagicTrend), title='Cross Alert', message='Price - MagicTrend Crossing!')
alertcondition(ta.crossover(LOW, MagicTrend), title='CrossOver Alarm', message='BUY SIGNAL!')
alertcondition(ta.crossunder(HIGH, MagicTrend), title='CrossUnder Alarm', message='SELL SIGNAL!')
i_numLookbackBarsTM = input(17,title="Number of bars to look back to validate Trend Magic trend")
//trendMagicEntryLong = trendMagicEntryConditionLong and f_priorBarsSatisfied(trendMagicEntryConditionLong,i_numLookbackBarsTM)
//trendMagicEntryShort = trendMagicEntryConditionShort and f_priorBarsSatisfied(trendMagicEntryConditionShort,i_numLookbackBarsTM)
trendMagicEntryConditionLong = ta.cci(src, period) >= 0 and src > MagicTrend + (isCrypto ? 5 : 0 )
trendMagicEntryConditionShort = ta.cci(src, period) < 0 and src < MagicTrend - (isCrypto ? 5 : 0)
trendMagicEntryLong = trendMagicEntryConditionLong and ta.barssince(trendMagicEntryConditionShort) > i_numLookbackBarsTM
trendMagicEntryShort = trendMagicEntryConditionShort and ta.barssince(trendMagicEntryConditionLong) > i_numLookbackBarsTM
// Squeeze Momentum by LazyBear
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
length = input(10, title='BB Length', group="Squeeze Momentum")
mult = input(2.0, title='BB MultFactor')
lengthKC = input(10, title='KC Length')
multKC = input(1.5, title='KC MultFactor')
useTrueRange = input(true, title='Use TrueRange (KC)')
// Calculate BB
source = CLOSE
basis = ta.sma(source, length)
dev = multKC * ta.stdev(source, length)
upperBB = basis + dev
lowerBB = basis - dev
// Calculate KC
ma = ta.sma(source, lengthKC)
range_1 = useTrueRange ? ta.tr : HIGH - LOW
rangema = ta.sma(range_1, lengthKC)
upperKC = ma + rangema * multKC
lowerKC = ma - rangema * multKC
sqzOn = lowerBB > lowerKC and upperBB < upperKC
sqzOff = lowerBB < lowerKC and upperBB > upperKC
noSqz = sqzOn == false and sqzOff == false
val = ta.linreg(source - math.avg(math.avg(ta.highest(HIGH, lengthKC), ta.lowest(LOW, lengthKC)), ta.sma(CLOSE, lengthKC)), lengthKC, 0)
iff_1 = val > nz(val[1]) ? color.lime : color.green
iff_2 = val < nz(val[1]) ? color.red : color.maroon
bcolor = val > 0 ? iff_1 : iff_2
scolor = noSqz ? color.blue : sqzOn ? color.black : color.gray
//plot(val, color=bcolor, style=plot.style_histogram, linewidth=4)
//plot(0, color=scolor, style=plot.style_cross, linewidth=2)
i_numLookbackBarsSM = input(14,title="Number of bars to look back to validate Sqz Mom trend")
//sqzmomEntryLong = val > 0 and f_priorBarsSatisfied(val > 0,i_numLookbackBarsSM)
//sqzmomEntryShort = val < 0 and f_priorBarsSatisfied(val < 0,i_numLookbackBarsSM)
sqzmomEntryConditionLong = val > 0
sqzmomEntryConditionShort = val < 0
sqzmomEntryLong = sqzmomEntryConditionLong and ta.barssince(sqzmomEntryConditionShort) > i_numLookbackBarsSM
sqzmomEntryShort = sqzmomEntryConditionShort and ta.barssince(sqzmomEntryConditionLong) > i_numLookbackBarsSM
// Cumulative Delta Volume by LonesomeTheBlue
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
linestyle = input.string(defval='Candle', title='Style', options=['Candle', 'Line'], group="Cumlative Delta Volume")
hacandle = input(defval=true, title='Heikin Ashi Candles?')
showma1 = input.bool(defval=false, title='SMA 1', inline='ma1')
ma1len = input.int(defval=50, title='', minval=1, inline='ma1')
ma1col = input.color(defval=color.lime, title='', inline='ma1')
showma2 = input.bool(defval=false, title='SMA 2', inline='ma2')
ma2len = input.int(defval=200, title='', minval=1, inline='ma2')
ma2col = input.color(defval=color.red, title='', inline='ma2')
showema1 = input.bool(defval=false, title='EMA 1', inline='ema1')
ema1len = input.int(defval=50, title='', minval=1, inline='ema1')
ema1col = input.color(defval=color.lime, title='', inline='ema1')
showema2 = input.bool(defval=false, title='EMA 2', inline='ema2')
ema2len = input.int(defval=200, title='', minval=1, inline='ema2')
ema2col = input.color(defval=color.red, title='', inline='ema2')
colorup = input.color(defval=color.lime, title='Body', inline='bcol')
colordown = input.color(defval=color.red, title='', inline='bcol')
bcolup = input.color(defval=#74e05e, title='Border', inline='bocol')
bcoldown = input.color(defval=#ffad7d, title='', inline='bocol')
wcolup = input.color(defval=#b5b5b8, title='Wicks', inline='wcol')
wcoldown = input.color(defval=#b5b5b8, title='', inline='wcol')
tw = HIGH - math.max(OPEN, CLOSE)
bw = math.min(OPEN, CLOSE) - LOW
body = math.abs(CLOSE - OPEN)
_rate(cond) =>
ret = 0.5 * (tw + bw + (cond ? 2 * body : 0)) / (tw + bw + body)
ret := nz(ret) == 0 ? 0.5 : ret
ret
deltaup = volume * _rate(OPEN <= CLOSE)
deltadown = volume * _rate(OPEN > CLOSE)
delta = CLOSE >= OPEN ? deltaup : -deltadown
cumdelta = ta.cum(delta)
float ctl = na
float o = na
float h = na
float l = na
float c = na
if linestyle == 'Candle'
o := cumdelta[1]
h := math.max(cumdelta, cumdelta[1])
l := math.min(cumdelta, cumdelta[1])
c := cumdelta
ctl
else
ctl := cumdelta
ctl
plot(ctl, title='CDV Line', color=color.new(color.blue, 0), linewidth=2)
float haclose = na
float haopen = na
float hahigh = na
float halow = na
haclose := (o + h + l + c) / 4
haopen := na(haopen[1]) ? (o + c) / 2 : (haopen[1] + haclose[1]) / 2
hahigh := math.max(h, math.max(haopen, haclose))
halow := math.min(l, math.min(haopen, haclose))
c_ = hacandle ? haclose : c
o_ = hacandle ? haopen : o
h_ = hacandle ? hahigh : h
l_ = hacandle ? halow : l
//plotcandle(o_, h_, l_, c_, title='CDV Candles', color=o_ <= c_ ? colorup : colordown, bordercolor=o_ <= c_ ? bcolup : bcoldown, wickcolor=o_ <= c_ ? bcolup : bcoldown)
//plot(showma1 and linestyle == 'Candle' ? ta.sma(c_, ma1len) : na, title='SMA 1', color=ma1col)
//plot(showma2 and linestyle == 'Candle' ? ta.sma(c_, ma2len) : na, title='SMA 2', color=ma2col)
//plot(showema1 and linestyle == 'Candle' ? ta.ema(c_, ema1len) : na, title='EMA 1', color=ema1col)
//plot(showema2 and linestyle == 'Candle' ? ta.ema(c_, ema2len) : na, title='EMA 2', color=ema2col)
i_numLookbackBarsCDV = input(14,title="Number of bars to look back to validate CDV trend")
//cdvEntryLong = o_ < c_ and f_priorBarsSatisfied(o_ < c_,i_numLookbackBarsCDV)
//cdvEntryShort = o_ > c_ and f_priorBarsSatisfied(o_ > c_,i_numLookbackBarsCDV)
cdvEntryConditionLong = o_ <= c_
cdvEntryConditionShort = o_ > c_
cdvEntryLong = cdvEntryConditionLong and ta.barssince(cdvEntryConditionShort) > i_numLookbackBarsCDV
cdvEntryShort = cdvEntryConditionShort and ta.barssince(cdvEntryConditionLong) > i_numLookbackBarsCDV
//////////////////////////////////////
//* Put your strategy rules below *//
/////////////////////////////////////
longCondition = trendMagicEntryLong and sqzmomEntryLong and cdvEntryLong
shortCondition = trendMagicEntryShort and sqzmomEntryShort and cdvEntryShort
//define as 0 if do not want to use
closeLongCondition = 0
closeShortCondition = 0
// ADX
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
adxEnabled = input.bool(defval = false , title = "Average Directional Index (ADX)", tooltip = "", group ="ADX" )
adxlen = input(14, title="ADX Smoothing", group="ADX")
adxdilen = input(14, title="DI Length", group="ADX")
adxabove = input(25, title="ADX Threshold", group="ADX")
adxdirmov(len) =>
adxup = ta.change(HIGH)
adxdown = -ta.change(LOW)
adxplusDM = na(adxup) ? na : (adxup > adxdown and adxup > 0 ? adxup : 0)
adxminusDM = na(adxdown) ? na : (adxdown > adxup and adxdown > 0 ? adxdown : 0)
adxtruerange = ta.rma(ta.tr, len)
adxplus = fixnan(100 * ta.rma(adxplusDM, len) / adxtruerange)
adxminus = fixnan(100 * ta.rma(adxminusDM, len) / adxtruerange)
[adxplus, adxminus]
adx(adxdilen, adxlen) =>
[adxplus, adxminus] = adxdirmov(adxdilen)
adxsum = adxplus + adxminus
adx = 100 * ta.rma(math.abs(adxplus - adxminus) / (adxsum == 0 ? 1 : adxsum), adxlen)
adxsig = adxEnabled ? adx(adxdilen, adxlen) : na
isADXEnabledAndAboveThreshold = adxEnabled ? (adxsig > adxabove) : true
//Backtesting Time Period (Input.time not working as expected as of 03/30/2021. Giving odd start/end dates
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
useStartPeriodTime = input.bool(true, 'Start', group='Date Range', inline='Start Period')
startPeriodTime = input.time(timestamp('1 Jan 2019'), '', group='Date Range', inline='Start Period')
useEndPeriodTime = input.bool(true, 'End', group='Date Range', inline='End Period')
endPeriodTime = input.time(timestamp('31 Dec 2030'), '', group='Date Range', inline='End Period')
start = useStartPeriodTime ? startPeriodTime >= time : false
end = useEndPeriodTime ? endPeriodTime <= time : false
calcPeriod = not start and not end
// Trade Direction
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tradeDirection = input.string('Long and Short', title='Trade Direction', options=['Long and Short', 'Long Only', 'Short Only'], group='Trade Direction')
// Percent as Points
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
per(pcnt) =>
strategy.position_size != 0 ? math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na)
// Take profit 1
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp1 = input.float(title='Take Profit 1 - Target %', defval=2, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 1')
q1 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 1')
// Take profit 2
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp2 = input.float(title='Take Profit 2 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 2')
q2 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 2')
// Take profit 3
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp3 = input.float(title='Take Profit 3 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 3')
q3 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 3')
// Take profit 4
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp4 = input.float(title='Take Profit 4 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit')
/// Stop Loss
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
stoplossPercent = input.float(title='Stop Loss (%)', defval=6, minval=0.01, group='Stop Loss') * 0.01
slLongClose = CLOSE < strategy.position_avg_price * (1 - stoplossPercent)
slShortClose = CLOSE > strategy.position_avg_price * (1 + stoplossPercent)
/// Leverage
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
leverage = input.float(1, 'Leverage', step=.5, group='Leverage')
contracts = math.min(math.max(.000001, strategy.equity / CLOSE * leverage), 1000000000)
/// Trade State Management
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
isInLongPosition = strategy.position_size > 0
isInShortPosition = strategy.position_size < 0
/// ProfitView Alert Syntax String Generation
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
alertSyntaxPrefix = input.string(defval='CRYPTANEX_99FTX_Strategy-Name-Here', title='Alert Syntax Prefix', group='ProfitView Alert Syntax')
alertSyntaxBase = alertSyntaxPrefix + '\n#' + str.tostring(OPEN) + ',' + str.tostring(HIGH) + ',' + str.tostring(LOW) + ',' + str.tostring(CLOSE) + ',' + str.tostring(volume) + ','
/// Trade Execution
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
longConditionCalc = (longCondition and isADXEnabledAndAboveThreshold)
shortConditionCalc = (shortCondition and isADXEnabledAndAboveThreshold)
if calcPeriod
if longConditionCalc and tradeDirection != 'Short Only' and isInLongPosition == false
strategy.entry('Long', strategy.long, qty=contracts)
alert(message=alertSyntaxBase + 'side:long', freq=alert.freq_once_per_bar_close)
if shortConditionCalc and tradeDirection != 'Long Only' and isInShortPosition == false
strategy.entry('Short', strategy.short, qty=contracts)
alert(message=alertSyntaxBase + 'side:short', freq=alert.freq_once_per_bar_close)
//Inspired from Multiple %% profit exits example by adolgo https://www.tradingview.com/script/kHhCik9f-Multiple-profit-exits-example/
strategy.exit('TP1', qty_percent=q1, profit=per(tp1))
strategy.exit('TP2', qty_percent=q2, profit=per(tp2))
strategy.exit('TP3', qty_percent=q3, profit=per(tp3))
strategy.exit('TP4', profit=per(tp4))
strategy.close('Long', qty_percent=100, comment='SL Long', when=slLongClose)
strategy.close('Short', qty_percent=100, comment='SL Short', when=slShortClose)
strategy.close_all(when=closeLongCondition or closeShortCondition, comment='Close Postion')
/// Dashboard
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Inspired by https://www.tradingview.com/script/uWqKX6A2/ - Thanks VertMT
showDashboard = input.bool(group="Dashboard", title="Show Dashboard", defval=true)
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
_cellText = _title + "\n" + _value
table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=size.auto)
// Draw dashboard table
if showDashboard
var bgcolor = color.new(color.black,0)
// Keep track of Wins/Losses streaks
newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
varip int winRow = 0
varip int lossRow = 0
varip int maxWinRow = 0
varip int maxLossRow = 0
if newWin
lossRow := 0
winRow := winRow + 1
if winRow > maxWinRow
maxWinRow := winRow
if newLoss
winRow := 0
lossRow := lossRow + 1
if lossRow > maxLossRow
maxLossRow := lossRow
// Prepare stats table
var table dashTable = table.new(position.bottom_right, 1, 15, border_width=1)
if barstate.islastconfirmedhistory
// Update table
dollarReturn = strategy.netprofit
f_fillCell(dashTable, 0, 0, "Start:", str.format("{0,date,long}", strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.closedtrades.entry_time(0))
f_fillCell(dashTable, 0, 1, "End:", str.format("{0,date,long}", strategy.opentrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.opentrades.entry_time(0))
_profit = (strategy.netprofit / strategy.initial_capital) * 100
f_fillCell(dashTable, 0, 2, "Net Profit:", str.tostring(_profit, '##.##') + "%", _profit > 0 ? color.green : color.red, color.white)
_numOfDaysInStrategy = (strategy.opentrades.entry_time(0) - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24)
f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit / _numOfDaysInStrategy, '#########################.#####')+"%", _profit > 0 ? color.green : color.red, color.white)
_winRate = ( strategy.wintrades / strategy.closedtrades ) * 100
f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? color.red : _winRate < 75 ? #999900 : color.green, color.white)
f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? color.green : color.red, color.white)
f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white)
f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white)
f_fillCell(dashTable, 0, 9, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white) |
ATR Mean Reversion Strategy V1 | https://www.tradingview.com/script/O4t4zTd3-ATR-Mean-Reversion-Strategy-V1/ | Bcullen175 | https://www.tradingview.com/u/Bcullen175/ | 225 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Bcullen175
//@version=5
strategy("ATR Mean Reversion", overlay=true, initial_capital=100000,default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=6E-5) // Brokers rate (ICmarkets = 6E-5)
SLx = input(1.5, "SL Multiplier", tooltip = "Multiplies ATR to widen stop on volatile assests, Higher values reduce risk:reward but increase winrate, Values below 1.2 are not reccomended")
src = input(close, title="Source")
period = input.int(10, "ATR & MA PERIOD")
plot(open+ta.atr(period))
plot(open-ta.atr(period))
plot((ta.ema(src, period)), title = "Mean", color=color.white)
i_startTime = input.time(title="Start Filter", defval=timestamp("01 Jan 1995 13:30 +0000"), group="Time Filter", tooltip="Start date & time to begin searching for setups")
i_endTime = input.time(title="End Filter", defval=timestamp("1 Jan 2099 19:30 +0000"), group="Time Filter", tooltip="End date & time to stop searching for setups")
// Check filter(s)
f_dateFilter = time >= i_startTime and time <= i_endTime
atr = ta.atr(period)
// Check buy/sell conditions
var float buyPrice = 0
buyCondition = low < (open-ta.atr(period)) and strategy.position_size == 0 and f_dateFilter
sellCondition = (high > (ta.ema(close, period)) and strategy.position_size > 0 and close < low[1]) or high > (open+ta.atr(period))
stopDistance = strategy.position_size > 0 ? ((buyPrice - atr)/buyPrice) : na
stopPrice = strategy.position_size > 0 ? (buyPrice - SLx*atr): na
stopCondition = strategy.position_size > 0 and low < stopPrice
// Enter positions
if buyCondition
strategy.entry(id="Long", direction=strategy.long)
if buyCondition[1]
buyPrice := open
// Exit positions
if sellCondition or stopCondition
strategy.close(id="Long", comment="Exit" + (stopCondition ? "SL=true" : ""))
buyPrice := na
// Draw pretty colors
plot(buyPrice, color=color.lime, style=plot.style_linebr)
plot(stopPrice, color=color.red, style=plot.style_linebr, offset=-1)
|
MTF Diagonally Layered RSI - 1 minute Bitcoin Bot [wbburgin] | https://www.tradingview.com/script/z1fsrtce-MTF-Diagonally-Layered-RSI-1-minute-Bitcoin-Bot-wbburgin/ | wbburgin | https://www.tradingview.com/u/wbburgin/ | 554 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © wbburgin
//@version=5
strategy("MTF Layered RSI - Bitcoin Bot [wbburgin]",overlay=false, initial_capital=10000, pyramiding=2)
length = input.int(7,"RSI Length",group="Config")
tf2 = input.timeframe("3",title="HT 1",group="Config")
tf3 = input.timeframe("5",title="HT 2",group="Config")
ob = input.int(80,"Overbought Level",group="Config")
os = input.int(20,"Oversold Level",group="Config")
calcType = input.string("Manual Calculation",options=["Security Function","Manual Calculation"],title="Calc Type",
tooltip="Manual calculation is a way to stop repaint without using request.security().")
use200ma = input.bool(false,"Use EMA Filter",group="Risk Management")
emaLen = input.int(200,"EMA Length",group="Risk Management")
stoploss = input.bool(false,"Use % Stop Loss",group="Risk Management")
stoplosspercent = input.float(0.5,title="Stop Loss (%)",group="Risk Management")
tradeType = input.string("Long-only",options=["Long-only","Long and Short"],title="Allow Shorts?")
rsi = ta.rsi(close,length)
// Security RSI Calculation ____________________________________________________________________________________________
indexHighTF = barstate.isrealtime ? 1 : 0
indexCurrTF = barstate.isrealtime ? 0 : 1
rsi2_sec = request.security(syminfo.tickerid, tf2, rsi[indexHighTF])[indexCurrTF]
rsi3_sec = request.security(syminfo.tickerid, tf3, rsi[indexHighTF])[indexCurrTF]
//Aligns with Tradingview's method of non-repainting: https://www.tradingview.com/pine-script-docs/en/v5/concepts/Repainting.html
// Manual RSI Calculation ______________________________________________________________________________________________
currentTF = timeframe.period
tf_to_int(timeframe)=>
switch
timeframe == "1S" => 1
timeframe == "5S" => 5
timeframe == "10S"=> 10
timeframe == "15S"=> 15
timeframe == "30S"=> 30
timeframe == "1" => 60
timeframe == "3" => 180
timeframe == "5" => 300
timeframe == "15" => 900
timeframe == "30" => 1800
timeframe == "45" => 2700
timeframe == "60" => 3600 // 1 hour
timeframe == "120"=> 7200 // 2 hours
timeframe == "180"=> 10800 // 3 hours
timeframe == "240"=> 14400 // 4 hours
timeframe == "480"=> 28800 // 8 hours
timeframe == "720"=> 43200 // 12 hours
timeframe == "D" => 86400 // 1 day
timeframe == "W" => 604800 // 1 week
timeframe == "M" => 2595000 // 1 month
ct_int = tf_to_int(currentTF)
ht1_int = tf_to_int(tf2)
ht2_int = tf_to_int(tf3)
ht1_mult = int(ht1_int / ct_int)
ht2_mult = int(ht2_int / ct_int)
manualRSI(time_mult, len)=>
htclose = close
u = math.max(htclose - htclose[time_mult], 0) // upward ta.change
d = math.max(htclose[time_mult] - htclose, 0) // downward ta.change
rs = ta.rma(u, len * time_mult) / ta.rma(d, len * time_mult)
res = 100 - 100 / (1 + rs)
res
rsi2_man = manualRSI(ht1_mult, length)
rsi3_man = manualRSI(ht2_mult, length)
rsi2 = calcType == "Security Function" ? rsi2_sec : rsi2_man
rsi3 = calcType == "Security Function" ? rsi3_sec : rsi3_man
plot(rsi,color=color.yellow,title="RSI Current TF")
plot(rsi2,color=color.new(color.yellow,50),title="RSI HT1")
plot(rsi3,color=color.new(color.yellow,75),title="RSI HT2")
lm=hline(os,title="Oversold")
hm=hline(ob,title="Overbought")
fill(hm,lm,color=color.new(color.blue,95))
// Long Settings
htCross = (ta.crossover(rsi2,os) and rsi3>os and rsi>os)
or (ta.crossover(rsi3,os) and rsi2>os and rsi>os)
buySig = (ta.crossover(rsi,os) and rsi2 < os and rsi3 < os) or htCross
sellSig = ta.crossunder(rsi,ob)
// Short Settings
htCross_short = (ta.crossunder(rsi2,ob) and rsi3<ob and rsi<ob) or (ta.crossunder(rsi3,ob) and rsi2<ob and rsi<ob)
shortEntry = (ta.crossunder(rsi,ob) and rsi2 > ob and rsi3 > ob) or htCross_short
shortExit = ta.crossover(rsi,os)
//Risk Settings
ema200 = ta.ema(close,emaLen)
filter = use200ma ? close>ema200 ? true : false : true
shortfilter = use200ma ? close<ema200 ? true : false : true
stoplosslevel_long = (1-(stoplosspercent/100)) * ta.valuewhen(buySig and filter,close,0)
stoplosslevel_short = (1+(stoplosspercent/100)) * ta.valuewhen(shortEntry and shortfilter,close,0)
initiate_stoploss_long = stoploss ? ta.crossunder(close,stoplosslevel_long) : na
initiate_stoploss_short = stoploss ? ta.crossover(close,stoplosslevel_short) : na
if buySig and filter
strategy.entry("Long",strategy.long)
if sellSig or initiate_stoploss_long
strategy.close("Long")
if shortEntry and shortfilter and tradeType == "Long and Short"
strategy.entry("Short",strategy.short)
if shortExit or initiate_stoploss_short
strategy.close("Short")
plotshape(buySig and filter,title="Buysig",style=shape.triangleup,location=location.bottom,color=color.green,size=size.tiny)
plotshape(sellSig or initiate_stoploss_long,title="Sellsig",style=shape.triangledown,location=location.top,color=color.red,size=size.tiny) |
Last Price minus Open Price Intraday Volume | https://www.tradingview.com/script/bhlo7KAz-Last-Price-minus-Open-Price-Intraday-Volume/ | avsr90 | https://www.tradingview.com/u/avsr90/ | 41 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © avsr90
//@version=5
strategy(title="Lp-Op vol",shorttitle="LPV", max_bars_back = 5000,overlay=false,format=format.volume )
//Resolutions
Resn=input.timeframe(defval="",title="resolution")
Resn1=input.timeframe(defval="D",title="resolution")
//Intraday Open and Last Price and Last price- Open Price calculations.
Last_Price=math.round_to_mintick(close)
Open_Price = request.security(syminfo.tickerid ,Resn1,close[1],barmerge.gaps_off, barmerge.lookahead_on)
Op_Cl=math.round_to_mintick(Last_Price-Open_Price)
//length from Intra Day Open Price
Nifnum= ta.change(Open_Price)
Length_Intraday=int(math.max(1, nz(ta.barssince(Nifnum)) + 1))
//Input for Length for Volume
Length_Vol=input(defval=20, title="L for Vol")
// Last Price- Open price Volume, Average Intraday Last price-Open Price Volume
//and Volume Bars calculations.
Op_Cl_Vol=(Op_Cl*volume)
Avg_Vol_Opcl=ta.sma(Op_Cl_Vol,Length_Intraday)
Vol_Bars=ta.sma(volume,Length_Vol)
//Plots
plot(Op_Cl_Vol,color=Op_Cl_Vol>0 ? color.green:color.red,title="OPCLV")
plot(Avg_Vol_Opcl, title="Avg Vol", color=color.fuchsia)
plot(Vol_Bars, title="Vol Bars", color=color.yellow)
//Strategy parameters
startst=timestamp(2015,10,1)
strategy.entry("lo",strategy.long,when= ta.crossover(Op_Cl_Vol,Avg_Vol_Opcl) and ta.crossover(volume,Vol_Bars))
strategy.entry("sh",strategy.short,when=ta.crossunder(Op_Cl_Vol,Avg_Vol_Opcl)and ta.crossunder(volume,Vol_Bars ))
|
Backtest Adapter | https://www.tradingview.com/script/Pu38F2pB-Backtest-Adapter/ | jdehorty | https://www.tradingview.com/u/jdehorty/ | 3,412 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jdehorty
//@version=5
strategy("Backtest Adapter", overlay=true)
useDateFilter = input.bool(true, title="Begin Backtest at Start Date", group="Backtest Time Period")
backtestStartDate = input.time(timestamp("11 May 2022"), title="Start Date", group="Backtest Time Period")
inTradeWindow = not useDateFilter or time >= backtestStartDate
src = input.source(title="Source", defval=close, tooltip="Source of the input data", group="General Settings")
// Set up your entry and exit conditions for positions based on the indicator stream.
// The values here must correspond to the values in the Source indicator.
startLongTrade = src == 1
endLongTrade = src == 2
startShortTrade = src == -1
endShortTrade = src == -2
transactionQty = 1
if startLongTrade and inTradeWindow
strategy.order("Enter Long", strategy.long, qty=transactionQty)
if endLongTrade and strategy.position_size > 0 and inTradeWindow
strategy.order("Exit Long", strategy.short, qty=transactionQty)
if startShortTrade and inTradeWindow
strategy.order("Enter Short", strategy.short, qty=transactionQty)
if endShortTrade and strategy.position_size < 0 and inTradeWindow
strategy.order("Exit Short", strategy.long, qty=transactionQty) |
Strategy Myth-Busting #12 - OSGFC+SuperTrend - [MYN] | https://www.tradingview.com/script/eg9wcYuj-Strategy-Myth-Busting-12-OSGFC-SuperTrend-MYN/ | myncrypto | https://www.tradingview.com/u/myncrypto/ | 431 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © myn
//@version=5
strategy('Strategy Myth-Busting #12 - OSGFC+SuperTrend - [MYN]', max_bars_back=5000, overlay=true, pyramiding=0, initial_capital=1000, currency='USD', default_qty_type=strategy.percent_of_equity, default_qty_value=10.0, commission_value=0.075, use_bar_magnifier = false)
/////////////////////////////////////
//* Put your strategy logic below *//
/////////////////////////////////////
// 5XVKG4ZzVvY
// Trading Rules: 15 mins, Forex / Crypto
// SuperTrend and OSGFC generate buy signal
// Close Buy on Gaussian generating a sell signal
// Gausian generates sell signal (close signal)
// One-Sided Gaussian Filter w/ Channels By Loxx
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
//ehlers 2-pole super smoother
_twopoless(float src, int len)=>
a1 = 0., b1 = 0.
coef1 = 0., coef2 = 0., coef3 = 0.
filt = 0., trig = 0.
a1 := math.exp(-1.414 * math.pi / len)
b1 := 2 * a1 * math.cos(1.414 * math.pi / len)
coef2 := b1
coef3 := -a1 * a1
coef1 := 1 - coef2 - coef3
filt := coef1 * src + coef2 * nz(filt[1]) + coef3 * nz(filt[2])
filt := bar_index < 3 ? src : filt
filt
_gaussian(size, x)=>
out = (math.exp(-x * x * 9 / ((size + 1) * (size + 1))))
out
//calc fibonacci numbers 0, 1, 1, 2, 3, 5, 8, 13, 21 ... etc
_fiblevels(len)=>
arr_levels = array.new_float(len, 0.)
t1 = 0, t2 = 1
nxt = t1 + t2
for i = 0 to len - 1
array.set(arr_levels, i, nxt)
t1 := t2
t2 := nxt
nxt := t1 + t2
arr_levels
//calc weights given fibo numbers and how many fibos chosen
_gaussout(levels)=>
perin = array.size(levels)
arr_gauss = matrix.new<float>(perin, perin, 0.)
for k = 0 to array.size(levels) - 1
sum = 0.
for i = 0 to perin - 1
if (i >= array.get(levels, k))
break
matrix.set(arr_gauss, i, k, _gaussian(array.get(levels, k), i))
sum += matrix.get(arr_gauss, i, k)
for i = 0 to perin - 1
if (i >= array.get(levels, k))
break
temp = matrix.get(arr_gauss, i, k) / sum
matrix.set(arr_gauss, i, k, temp)
arr_gauss
//calc moving average applying fibo numbers
_smthMA(level, src, per)=>
sum = 0.
lvltemp = _fiblevels(per)
gtemp = _gaussout(lvltemp)
for i = 0 to matrix.rows(gtemp) - 1
sum += matrix.get(gtemp, i, level) * nz(src[i])
sum
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "One-Sided Gaussian Filter w/ Channels")
srcoption = input.string("Close", "Source", group= "One-Sided Gaussian Filter w/ Channels",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
smthper = input.int(10, "Guassian Levels Depth", maxval = 100, group= "Basic Settings")
extrasmthper = input.int(10, "Extra Smoothing (2-Pole Ehlers Super Smoother) Period", group= "Basic Settings")
atrper = input.int(21, "ATR Period", group = "Basic Settings")
mult = input.float(.628, "ATR Multiplier", group = "Basic Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showsignals = input.bool(true, "Show signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
float src = switch srcoption
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
lmax = smthper + 1
out1 = _smthMA(smthper, src, lmax)
out = _twopoless(out1, extrasmthper)
sig = out[1]
colorout = out > sig ? greencolor : redcolor
atr = ta.atr(atrper)
smax = out + atr * mult
smin = out - atr * mult
plot(smax, color = bar_index % 2 ? color.silver : na, linewidth = 1)
plot(smin, color = bar_index % 2 ? color.silver : na, linewidth = 1)
plot(out, "GMA", color = colorout, linewidth = 4)
barcolor(colorbars ? colorout : na)
goLong = ta.crossover(out, sig)
goShort = ta.crossunder(out, sig)
plotshape(goLong and showsignals, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(goShort and showsignals, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title="Long", message="One-Sided Gaussian Filter w/ Channels [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="One-Sided Gaussian Filter w/ Channels [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
OSGFCLongEntry = goLong
OSGFCShortgEntry = goShort
i_numLookbackBarsOSGFC = input(0,title="Number of bars to look back to validate Trend")
OSGFCLongEntryFinal = goLong and ta.barssince(OSGFCShortgEntry) > i_numLookbackBarsOSGFC
OSGFCShortgEntryFinal = goShort and ta.barssince(OSGFCLongEntry) > i_numLookbackBarsOSGFC
OSGFCLongClose = OSGFCShortgEntry
OSGFCShortClose = OSGFCLongEntry
// SuperTrend (TradingView Interal)
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
atrPeriod1 = input(10, "ATR Length", group="SuperTrend")
factor = input.float(3.0, "Factor", step = 0.01)
[supertrend1, direction1] = ta.supertrend(factor, atrPeriod1)
bodyMiddle = plot((open + close) / 2, display=display.none)
upTrend = plot(direction1 < 0 ? supertrend1 : na, "Up Trend", color = color.green, style=plot.style_linebr)
downTrend = plot(direction1 < 0 ? na : supertrend1, "Down Trend", color = color.red, style=plot.style_linebr)
fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)
superTrendLongEntry = direction1 < 0
superTrendShortEntry = direction1 > 0
i_numLookbackBarsST = input(0,title="Number of bars to look back to validate Trend")
superTrendLongEntryFinal = superTrendLongEntry and ta.barssince(superTrendShortEntry) > i_numLookbackBarsST
superTrendShortEntryFinal = superTrendShortEntry and ta.barssince(superTrendLongEntry) > i_numLookbackBarsST
//////////////////////////////////////
//* Put your strategy rules below *//
/////////////////////////////////////
longCondition = OSGFCLongEntryFinal and superTrendLongEntryFinal
shortCondition = OSGFCShortgEntryFinal and superTrendShortEntryFinal
//define as 0 if do not want to use
closeLongCondition = OSGFCLongClose
closeShortCondition = OSGFCShortClose
// ADX
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
adxEnabled = input.bool(defval = false , title = "Average Directional Index (ADX)", tooltip = "", group ="ADX" )
adxlen = input(14, title="ADX Smoothing", group="ADX")
adxdilen = input(14, title="DI Length", group="ADX")
adxabove = input(25, title="ADX Threshold", group="ADX")
adxdirmov(len) =>
adxup = ta.change(high)
adxdown = -ta.change(low)
adxplusDM = na(adxup) ? na : (adxup > adxdown and adxup > 0 ? adxup : 0)
adxminusDM = na(adxdown) ? na : (adxdown > adxup and adxdown > 0 ? adxdown : 0)
adxtruerange = ta.rma(ta.tr, len)
adxplus = fixnan(100 * ta.rma(adxplusDM, len) / adxtruerange)
adxminus = fixnan(100 * ta.rma(adxminusDM, len) / adxtruerange)
[adxplus, adxminus]
adx(adxdilen, adxlen) =>
[adxplus, adxminus] = adxdirmov(adxdilen)
adxsum = adxplus + adxminus
adx = 100 * ta.rma(math.abs(adxplus - adxminus) / (adxsum == 0 ? 1 : adxsum), adxlen)
adxsig = adxEnabled ? adx(adxdilen, adxlen) : na
isADXEnabledAndAboveThreshold = adxEnabled ? (adxsig > adxabove) : true
//Backtesting Time Period (Input.time not working as expected as of 03/30/2021. Giving odd start/end dates
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
useStartPeriodTime = input.bool(true, 'Start', group='Date Range', inline='Start Period')
startPeriodTime = input.time(timestamp('1 Jan 2019'), '', group='Date Range', inline='Start Period')
useEndPeriodTime = input.bool(true, 'End', group='Date Range', inline='End Period')
endPeriodTime = input.time(timestamp('31 Dec 2030'), '', group='Date Range', inline='End Period')
start = useStartPeriodTime ? startPeriodTime >= time : false
end = useEndPeriodTime ? endPeriodTime <= time : false
calcPeriod = not start and not end
// Trade Direction
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tradeDirection = input.string('Long and Short', title='Trade Direction', options=['Long and Short', 'Long Only', 'Short Only'], group='Trade Direction')
// Percent as Points
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
per(pcnt) =>
strategy.position_size != 0 ? math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na)
// Take profit 1
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp1 = input.float(title='Take Profit 1 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 1')
q1 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 1')
// Take profit 2
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp2 = input.float(title='Take Profit 2 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 2')
q2 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 2')
// Take profit 3
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp3 = input.float(title='Take Profit 3 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 3')
q3 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 3')
// Take profit 4
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp4 = input.float(title='Take Profit 4 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit')
/// Stop Loss
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
stoplossPercent = input.float(title='Stop Loss (%)', defval=999, minval=0.01, group='Stop Loss') * 0.01
slLongClose = close < strategy.position_avg_price * (1 - stoplossPercent)
slShortClose = close > strategy.position_avg_price * (1 + stoplossPercent)
/// Leverage
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
leverage = input.float(1, 'Leverage', step=.5, group='Leverage')
contracts = math.min(math.max(.000001, strategy.equity / close * leverage), 1000000000)
/// Trade State Management
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
isInLongPosition = strategy.position_size > 0
isInShortPosition = strategy.position_size < 0
/// ProfitView Alert Syntax String Generation
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
alertSyntaxPrefix = input.string(defval='CRYPTANEX_99FTX_Strategy-Name-Here', title='Alert Syntax Prefix', group='ProfitView Alert Syntax')
alertSyntaxBase = alertSyntaxPrefix + '\n#' + str.tostring(open) + ',' + str.tostring(high) + ',' + str.tostring(low) + ',' + str.tostring(close) + ',' + str.tostring(volume) + ','
/// Trade Execution
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
longConditionCalc = (longCondition and isADXEnabledAndAboveThreshold)
shortConditionCalc = (shortCondition and isADXEnabledAndAboveThreshold)
if calcPeriod
if longConditionCalc and tradeDirection != 'Short Only' and isInLongPosition == false
strategy.entry('Long', strategy.long, qty=contracts)
alert(message=alertSyntaxBase + 'side:long', freq=alert.freq_once_per_bar_close)
if shortConditionCalc and tradeDirection != 'Long Only' and isInShortPosition == false
strategy.entry('Short', strategy.short, qty=contracts)
alert(message=alertSyntaxBase + 'side:short', freq=alert.freq_once_per_bar_close)
//Inspired from Multiple %% profit exits example by adolgo https://www.tradingview.com/script/kHhCik9f-Multiple-profit-exits-example/
strategy.exit('TP1', qty_percent=q1, profit=per(tp1))
strategy.exit('TP2', qty_percent=q2, profit=per(tp2))
strategy.exit('TP3', qty_percent=q3, profit=per(tp3))
strategy.exit('TP4', profit=per(tp4))
strategy.close('Long', qty_percent=100, comment='SL Long', when=slLongClose)
strategy.close('Short', qty_percent=100, comment='SL Short', when=slShortClose)
strategy.close_all(when=closeLongCondition or closeShortCondition, comment='Close Postion')
/// Dashboard
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Inspired by https://www.tradingview.com/script/uWqKX6A2/ - Thanks VertMT
showDashboard = input.bool(group="Dashboard", title="Show Dashboard", defval=true)
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
_cellText = _title + "\n" + _value
table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=size.auto)
// Draw dashboard table
if showDashboard
var bgcolor = color.new(color.black,0)
// Keep track of Wins/Losses streaks
newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
varip int winRow = 0
varip int lossRow = 0
varip int maxWinRow = 0
varip int maxLossRow = 0
if newWin
lossRow := 0
winRow := winRow + 1
if winRow > maxWinRow
maxWinRow := winRow
if newLoss
winRow := 0
lossRow := lossRow + 1
if lossRow > maxLossRow
maxLossRow := lossRow
// Prepare stats table
var table dashTable = table.new(position.bottom_right, 1, 15, border_width=1)
if barstate.islastconfirmedhistory
// Update table
dollarReturn = strategy.netprofit
f_fillCell(dashTable, 0, 0, "Start:", str.format("{0,date,long}", strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.closedtrades.entry_time(0))
f_fillCell(dashTable, 0, 1, "End:", str.format("{0,date,long}", strategy.opentrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.opentrades.entry_time(0))
_profit = (strategy.netprofit / strategy.initial_capital) * 100
f_fillCell(dashTable, 0, 2, "Net Profit:", str.tostring(_profit, '##.##') + "%", _profit > 0 ? color.green : color.red, color.white)
_numOfDaysInStrategy = (strategy.opentrades.entry_time(0) - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24)
f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit / _numOfDaysInStrategy, '#########################.#####')+"%", _profit > 0 ? color.green : color.red, color.white)
_winRate = ( strategy.wintrades / strategy.closedtrades ) * 100
f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? color.red : _winRate < 75 ? #999900 : color.green, color.white)
f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? color.green : color.red, color.white)
f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white)
f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white)
f_fillCell(dashTable, 0, 9, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white) |
Strategy Myth-Busting #23 - 2xEMA+DPO- [MYN] | https://www.tradingview.com/script/vZaoAA3o-Strategy-Myth-Busting-23-2xEMA-DPO-MYN/ | myncrypto | https://www.tradingview.com/u/myncrypto/ | 115 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © myn
//@version=5
strategy('Strategy Myth-Busting #23 - 2xEMA+DPO- [MYN]', max_bars_back=5000, overlay=true, pyramiding=0, initial_capital=1000, currency='NONE', default_qty_type=strategy.percent_of_equity, default_qty_value=1.0, commission_value=0.075, use_bar_magnifier = false)
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// indicators:
// EMA 40
// EMA 12
// Untrend Price DPO indicator ( jTradeuh ), on style untick the DPOvalue
// Entry rules:
// Longs: EMA 12 have to cross EMA 40 and need to be above it and the Untrend price DPO indicator has to have multiple green bars,
// Shorts: EMA 12 have to cross EMA 40 and need to be under it and the Untrend price DPO indicator has to have multiple reed bars,
// SL recent swing high/low
// TP 2.5 risk reward ratio.
// Second confluence using Untrend Price DPO
// 2 EMA
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
len1 = input.int(40, minval=1, title="Length", group="EMA 1")
src1 = input(close, title="Source")
offset1 = input.int(title="Offset", defval=0, minval=-500, maxval=500)
out1 = ta.ema(src1, len1)
plot(out1, title="EMA 1", color=color.white, offset=offset1, linewidth=2)
len2 = input.int(12, minval=1, title="Length", group="EMA 2")
src2 = input(close, title="Source")
offset2 = input.int(title="Offset", defval=0, minval=-500, maxval=500)
out2 = ta.ema(src2, len2)
plot(out2, title="EMA 2", color=color.yellow, offset=offset2, linewidth=2)
emaLongEntry = ta.crossover(source1=out2 , source2 =out1 )
emaShortEntry = ta.crossunder(source1=out2 , source2 =out1 )
// Uptrend Price DPO indicator
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
period_ = input.int(21, title='Period', minval=1,group="UpTrend DPO")
isCentered = input(false)
barsback = period_ / 2 + 1
ma = ta.sma(close, period_)
dpo = isCentered ? close[barsback] - ma : close - ma[barsback]
sma = ta.ema(dpo, 30)
COLOR = dpo > 0 ? color.lime : color.red
//plot(sma, offset=isCentered ? -barsback : 0, title='DPO', color=COLOR, style=plot.style_histogram)
//hline(0, title='Zero')
// Last 2 bars at least need to be green
upTrenndDPOEntryLong = dpo > 0 and dpo[1] > 0 and dpo[2] > 0
// Last 2 bars at least need to be red
upTrendDPOEntryShort = dpo < 0 and dpo[1] < 0 and dpo[2] < 0
// Put Your Strategy Rules Below
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
longCondition = emaLongEntry and upTrenndDPOEntryLong // default: false
shortCondition = emaShortEntry and upTrendDPOEntryShort // default: false
//define as 0 if do not want to have a conditional close
closeLongCondition = false // default: 0
closeShortCondition = false // default: 0
// EMA Filter
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_emaFilterEnabled = input.bool(defval = false , title = "Enable EMA Filter", tooltip = "Enable if you would like to conditionally have entries incorporate EMA as a filter where source is above/below the EMA line", group ="EMA Filter" )
i_emaLength = input.int(200, title="EMA Length", minval=1, group ="EMA Filter")
i_emaSource = input.source(close,"EMA Source" , group ="EMA Filter")
emaValue = i_emaFilterEnabled ? ta.ema(i_emaSource, i_emaLength) : na
bool isEMAFilterEnabledAndCloseAboveMA = i_emaFilterEnabled ? i_emaSource > emaValue : true
bool isEMAFilterEnabledAndCloseBelowMA = i_emaFilterEnabled ? i_emaSource < emaValue : true
// ADX Filter
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_adxFilterEnabled = input.bool(defval = false , title = "Enable ADX Filter", tooltip = "Enable if you would like to conditionally have entries incorporate ADX as a filter", group ="ADX Filter" )
i_adxVariant = input.string('ORIGINAL', title='ADX Variant', options=['ORIGINAL', 'MASANAKAMURA'], group ="ADX Filter" )
i_adxSmoothing = input.int(14, title="ADX Smoothing", group="ADX Filter")
i_adxDILength = input.int(14, title="DI Length", group="ADX Filter")
i_adxLowerThreshold = input.float(25, title="ADX Threshold", step=.5, group="ADX Filter")
calcADX_Masanakamura(int _len) =>
_smoothedTrueRange = 0.0
_smoothedDirectionalMovementPlus = 0.0
_smoothed_directionalMovementMinus = 0.0
_trueRange = math.max(math.max(high - low, math.abs(high - nz(close[1]))), math.abs(low - nz(close[1])))
_directionalMovementPlus = high - nz(high[1]) > nz(low[1]) - low ? math.max(high - nz(high[1]), 0) : 0
_directionalMovementMinus = nz(low[1]) - low > high - nz(high[1]) ? math.max(nz(low[1]) - low, 0) : 0
_smoothedTrueRange := nz(_smoothedTrueRange[1]) - nz(_smoothedTrueRange[1]) / _len + _trueRange
_smoothedDirectionalMovementPlus := nz(_smoothedDirectionalMovementPlus[1]) - nz(_smoothedDirectionalMovementPlus[1]) / _len + _directionalMovementPlus
_smoothed_directionalMovementMinus := nz(_smoothed_directionalMovementMinus[1]) - nz(_smoothed_directionalMovementMinus[1]) / _len + _directionalMovementMinus
DIP = _smoothedDirectionalMovementPlus / _smoothedTrueRange * 100
DIM = _smoothed_directionalMovementMinus / _smoothedTrueRange * 100
_DX = math.abs(DIP - DIM) / (DIP + DIM) * 100
adx = ta.sma(_DX, _len)
[DIP, DIM, adx]
[DIPlusO, DIMinusO, ADXO] = ta.dmi(i_adxDILength, i_adxSmoothing)
[DIPlusM, DIMinusM, ADXM] = calcADX_Masanakamura(i_adxDILength)
adx = i_adxFilterEnabled and i_adxVariant == "ORIGINAL" ? ADXO : ADXM
bool isADXFilterEnabledAndAboveThreshold = i_adxFilterEnabled ? adx > i_adxLowerThreshold : true
// Start / End Time Periods
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_startPeriodEnabled = input.bool(true, 'Start', group='Date Range', inline='Start Period')
i_startPeriodTime = input.time(timestamp('1 Jan 2019'), '', group='Date Range', inline='Start Period')
i_endPeriodEnabled = input.bool(true, 'End', group='Date Range', inline='End Period')
i_endPeriodTime = input.time(timestamp('31 Dec 2030'), '', group='Date Range', inline='End Period')
isStartPeriodEnabledAndInRange = i_startPeriodEnabled ? i_startPeriodTime <= time : true
isEndPeriodEnabledAndInRange = i_endPeriodEnabled ? i_endPeriodTime >= time : true
// Time-Of-Day Window
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Inspired from https://www.tradingview.com/script/3BmID7aW-Highlight-Trading-Window-Simple-Hours-Time-of-Day-Filter/
i_timeFilterEnabled = input.bool(defval = false , title = "Enable Time-Of-Day Window", tooltip = "Limit the time of day for trade execution", group ="Time Window" )
i_timeZone = input.string(title="Select Local Time Zone", defval="GMT-5", options=["GMT-8","GMT-7", "GMT-6", "GMT-5", "GMT-4", "GMT-3", "GMT-2", "GMT-1", "GMT", "GMT+1", "GMT+2", "GMT+3","GMT+4","GMT+5","GMT+6","GMT+7","GMT+8","GMT+9","GMT+10","GMT+11","GMT+12","GMT+13"], group="Time Window")
i_betweenTime = input.session('0700-0900', title = "Time Filter", group="Time Window") // '0000-0000' is anytime to enter
isWithinWindowOfTime(_position) =>
currentTimeIsWithinWindowOfTime = not na(time(timeframe.period, _position + ':1234567', i_timeZone))
bool isTimeFilterEnabledAndInRange = i_timeFilterEnabled ? isWithinWindowOfTime(i_betweenTime) : true
isStartEndPeriodsAndTimeInRange = isStartPeriodEnabledAndInRange and isEndPeriodEnabledAndInRange and isTimeFilterEnabledAndInRange
// Trade Direction and State Management
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_tradeDirection = input.string('Long and Short', title='Trade Direction', options=['Long and Short', 'Long Only', 'Short Only'], group='Trade Direction')
// Todo Add logic to reenter trade only if condition is still met only on TP
//i_reenterPosition = input.bool(defval=true, title='Re-Enter Position on TP' , group='Trade Direction')
//longConditionFinal = i_reenterPosition ? longCondition : longCondition and not longCondition[1]
//shortConditionFinal = i_reenterPosition ? shortCondition : shortCondition and not shortCondition[1]
isInLongPosition = strategy.position_size > 0
isInShortPosition = strategy.position_size < 0
longConditionFinal = (longCondition and isADXFilterEnabledAndAboveThreshold and isEMAFilterEnabledAndCloseAboveMA) and i_tradeDirection != 'Short Only' and isInLongPosition == false
shortConditionFinal = (shortCondition and isADXFilterEnabledAndAboveThreshold and isEMAFilterEnabledAndCloseBelowMA) and i_tradeDirection != 'Long Only' and isInShortPosition == false
// Trade Entry variables (not in position yet)
bool openingLongPosition = longConditionFinal and not (strategy.opentrades.size(strategy.opentrades - 1) > 0)
bool openingShortPosition = shortConditionFinal and not (strategy.opentrades.size(strategy.opentrades - 1) < 0)
bool openingAnyPosition = openingLongPosition or openingShortPosition
float closePriceWhenPositionOpened = ta.valuewhen(openingAnyPosition,close,0)
// Stop Loss
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Todo: Consider moving the strategy.entry calls above where the TP/SL close orders so that close orders can be executed on same bar.
var groupStopLoss = "🛑 Stop Loss"
i_useStopLoss = input.bool (title="Use Stop Loss", defval = true, group=groupStopLoss)
i_typeOfStopLoss = input.string (title="Type Of Stop Loss", defval="Last Swing High/Low", options=["Fixed %","Last Swing High/Low","ATR"], group=groupStopLoss)
i_fixedPercentSL = input.float(title='Fixed %', defval=1, minval=0, step=0.5, group=groupStopLoss) * 0.01
i_swingHighLowLookbackSL = input.int(21, title="Swing High/Low Lookback", group=groupStopLoss)
i_atrLengthSL = input.int(title="ATR Length", defval=14, minval = 1, inline="ATR SL", group=groupStopLoss)
i_atrMultiplierSL = input.float(title="ATR Multiplier", defval=1, minval = 0, step=0.1, inline="ATR SL", group=groupStopLoss)
// Fixed Percent Stop Loss
float fixedPercentSLPriceWhenLongPositionEntered = ta.valuewhen(openingLongPosition,close,0) * (1 - i_fixedPercentSL)
float fixedPercentSLPriceWhenShortPositionEntered = ta.valuewhen(openingShortPosition,close,0) * (1 + i_fixedPercentSL)
// Swing High/Low Stop Loss
float swingLowPriceWhenLongPostionEntered = ta.valuewhen(openingLongPosition, source = ta.lowest(low, i_swingHighLowLookbackSL), occurrence = 0)
float swingHighPriceWhenShortPositionEntered = ta.valuewhen(openingShortPosition, source = ta.highest(high, i_swingHighLowLookbackSL), occurrence = 0)
// Debug Start
// drawLabel(_offset, _pivot, _style, _color) =>
// if not na(_pivot)
// label.new(bar_index[_offset], _pivot, str.tostring(_pivot, format.mintick), style=_style, color=_color, textcolor=#131722)
// drawLabel(i_swingHighLowLookbackSL, ta.pivothigh(high, i_swingHighLowLookbackSL, i_swingHighLowLookbackSL), label.style_label_down, color.red)
// drawLabel(i_swingHighLowLookbackSL, ta.pivotlow(low, i_swingHighLowLookbackSL, i_swingHighLowLookbackSL), label.style_label_up, color.blue)
// Debug End
//ATR
//todo determine if close should be source for both long/short or if high/low should be used?
float ATRSLPriceWhenLongPositionEntered = ta.valuewhen(openingLongPosition, close - (ta.atr(i_atrLengthSL) * i_atrMultiplierSL) ,0)
float ATRSLPriceWhenShortPositionEntered = ta.valuewhen(openingShortPosition, close + (ta.atr(i_atrLengthSL) * i_atrMultiplierSL) ,0)
//plot(close + (ta.atr(i_atrLengthSL) * i_atrMultiplierSL), color=color.new(color.green, 0))
//plot(close - (ta.atr(i_atrLengthSL) * i_atrMultiplierSL), color=color.new(color.red, 0))
f_calculateStopLoss(string direction, string typeOfStopLoss) =>
// TODO init these to be 0 and "" as slPriceLong/Short is referenced by TP Risk:Reward calculation
float slOrderClosePrice = na
string slOrderComment = na
switch typeOfStopLoss
"Fixed %" =>
slOrderClosePrice := direction == "long" ? fixedPercentSLPriceWhenLongPositionEntered : fixedPercentSLPriceWhenShortPositionEntered
slOrderComment := direction == "long" ? "SL Fixed % Long" : "SL Fixed % Short"
"Last Swing High/Low" =>
slOrderClosePrice := direction == "long" ? swingLowPriceWhenLongPostionEntered : swingHighPriceWhenShortPositionEntered
slOrderComment := direction == "long" ? "SL Swing Low Long" : "SL Swing High Short"
"ATR" =>
slOrderClosePrice := direction == "long" ? ATRSLPriceWhenLongPositionEntered : ATRSLPriceWhenShortPositionEntered
slOrderComment := direction == "long" ? "SL ATR Long" : "SL ATR Short"
[slOrderClosePrice,slOrderComment]
[slPriceLong, slCommentLong] = f_calculateStopLoss( "long",i_typeOfStopLoss)
[slPriceShort, slCommentShort] = f_calculateStopLoss("short",i_typeOfStopLoss)
slLongCondition = close <= slPriceLong
slShortCondition = close >= slPriceShort
// Take Profit
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
var groupTakeProfit = "🟢 Take Profit"
i_useTakeProfit = input.bool (title="Use Take Profit", defval = true, group=groupTakeProfit)
i_typeOfTakeProfit = input.string (title="Type Of Take Profit", defval="Risk:Reward Ratio", options=["Single Fixed %","Multiple Fixed %","Risk:Reward Ratio","ATR"], group=groupTakeProfit)
i_fixedPercentTP = input.float(title='Single Fixed %', defval=1, minval=0, step=0.5, group=groupTakeProfit) * 0.01
i_takeProfitTargetPercent1 = input.float(title='Take Profit 1 - Target %', defval=100, minval=0.0, step=0.5, group=groupTakeProfit, inline='Take Profit 1')
i_takeProfitQuantityPercent1 = input.int(title='% Of Position', defval=100, minval=0, group=groupTakeProfit, inline='Take Profit 1')
i_takeProfitTargetPercent2 = input.float(title='Take Profit 2 - Target %', defval=100, minval=0.0, step=0.5, group=groupTakeProfit, inline='Take Profit 2')
i_takeProfitQuantityPercent2 = input.int(title='% Of Position', defval=100, minval=0, group=groupTakeProfit, inline='Take Profit 2')
i_takeProfitTargetPercent3 = input.float(title='Take Profit 3 - Target %', defval=100, minval=0.0, step=0.5, group=groupTakeProfit, inline='Take Profit 3')
i_takeProfitQuantityPercent3 = input.int(title='% Of Position', defval=100, minval=0, group=groupTakeProfit, inline='Take Profit 3')
i_takeProfitTargetPercent4 = input.float(title='Take Profit 4 - Target %', defval=100, minval=0.0, step=0.5, group=groupTakeProfit)
i_RiskRewardRatioTP = input.float(title="Risk:Reward Ratio 1:#", defval=2.5, minval=0 , step=0.1, group=groupTakeProfit)
i_atrLengthTP = input.int(title="ATR Length", defval=14, minval = 1, inline="ATR TP", group=groupTakeProfit)
i_atrMultiplierTP = input.float(title="ATR Multiplier", defval=1, minval = 0, step=0.1, inline="ATR TP", group=groupTakeProfit)
// Single Fixed Percent Take Profit
float fixedPercentTPPriceWhenLongPositionEntered = ta.valuewhen(openingLongPosition,close,0) * (1 + i_fixedPercentTP)
float fixedPercentTPPriceWhenShortPositionEntered = ta.valuewhen(openingShortPosition,close,0) * (1 - i_fixedPercentTP)
// Multiple
// Risk:Reward Ratio Take Profit
tpRRPriceWhenLongPositionEntered = closePriceWhenPositionOpened + ((closePriceWhenPositionOpened - slPriceLong) * i_RiskRewardRatioTP)
tpRRPriceWhenShortPositionEntered = closePriceWhenPositionOpened + ((closePriceWhenPositionOpened - slPriceShort) * i_RiskRewardRatioTP)
//ATR
//todo determine if close should be source for both long/short or if high/low should be used?
float ATRTPPriceWhenLongPositionEntered = ta.valuewhen(openingLongPosition, close + (ta.atr(i_atrLengthTP) * i_atrMultiplierTP) ,0)
float ATRTPPriceWhenShortPositionEntered = ta.valuewhen(openingShortPosition, close - (ta.atr(i_atrLengthTP) * i_atrMultiplierTP) ,0)
// plot(close + (ta.atr(i_atrLengthTP) * i_atrMultiplierTP), color=color.new(color.green, 0))
// plot(close - (ta.atr(i_atrLengthTP) * i_atrMultiplierTP), color=color.new(color.red, 0))
f_calculateTakeProfit(string direction, string typeOfTakeProfit) =>
float tpOrderClosePrice = na
string tpOrderComment = na
switch typeOfTakeProfit
"Single Fixed %" =>
tpOrderClosePrice := direction == "long" ? fixedPercentTPPriceWhenLongPositionEntered : fixedPercentTPPriceWhenShortPositionEntered
tpOrderComment := direction == "long" ? "TP Single Fixed % Long" : "TP Single Fixed % Short"
"Multiple Fixed %" =>
tpOrderClosePrice := na
tpOrderComment := ""
"Risk:Reward Ratio" =>
tpOrderClosePrice := direction == "long" ? tpRRPriceWhenLongPositionEntered : tpRRPriceWhenShortPositionEntered
tpOrderComment := direction == "long" ? "TP R:R Long" : "TP R:R Short"
"ATR" =>
tpOrderClosePrice := direction == "long" ? ATRTPPriceWhenLongPositionEntered : ATRTPPriceWhenShortPositionEntered
tpOrderComment := direction == "long" ? "TP ATR Long" : "TP ATR Short"
[tpOrderClosePrice,tpOrderComment]
[tpPriceLong, tpCommentLong] = f_calculateTakeProfit( "long",i_typeOfTakeProfit)
[tpPriceShort, tpCommentShort] = f_calculateTakeProfit("short",i_typeOfTakeProfit)
tpLongCondition = close >= tpPriceLong
tpShortCondition = close <= tpPriceShort
// Functions
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
per(pcnt) =>
strategy.position_size != 0 ? math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na)
// Plotting
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
//Plot SL and TP
i_plotTPSL=input(true, title="Plot TP and SL", group='Plotting')
slbp=plot(i_plotTPSL and i_useStopLoss and strategy.position_size > 0 ? slPriceLong[1] : na, color=color.red, style=plot.style_linebr, title="SL")
tpbp=plot(i_plotTPSL and i_useTakeProfit and strategy.position_size > 0 ? tpPriceLong[1] : na, color=color.lime, style=plot.style_linebr, title="TP")
epbp=plot(i_plotTPSL and strategy.position_size > 0 ? strategy.position_avg_price : na, color=color.gray, style=plot.style_linebr, title="Entry")
fill(slbp, epbp, color=color.new(color.red, 90))
fill(tpbp, epbp, color=color.new(color.green, 90))
slsp=plot(i_plotTPSL and i_useStopLoss and strategy.position_size < 0 ? slPriceShort[1] : na, color=color.red, style=plot.style_linebr, title="SL")
tpsp=plot(i_plotTPSL and i_useTakeProfit and strategy.position_size < 0 ? tpPriceShort[1] : na, color=color.lime, style=plot.style_linebr, title="TP")
epsp=plot(i_plotTPSL and strategy.position_size < 0 ? strategy.position_avg_price : na, color=color.gray, style=plot.style_linebr, title="Entry")
fill(slsp, epsp, color=color.new(color.red, 90))
fill(tpsp, epsp, color=color.new(color.green, 90))
/// Leverage
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_leverage = input.float(1, 'Leverage', step=.5, group='Leverage')
i_percentOfEquityToTrade = input.float(100, "% of Equity to Stake Per Trade", minval=0.01, maxval=100, step=5, group='Leverage') * .01
contracts = (i_percentOfEquityToTrade * strategy.equity / close * i_leverage)
/// ProfitView Alert Syntax String Generation
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_alertSyntaxPrefix = input.string(defval='CRYPTANEX_99FTX_Strategy-Name-Here', title='Alert Syntax Prefix', group='ProfitView Alert Syntax')
alertSyntaxBase = i_alertSyntaxPrefix + '\n#' + str.tostring(open) + ',' + str.tostring(high) + ',' + str.tostring(low) + ',' + str.tostring(close) + ',' + str.tostring(volume) + ','
/// Trade Execution
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
if isStartEndPeriodsAndTimeInRange
if longConditionFinal
strategy.entry('Long', strategy.long, qty=contracts)
alert(message=alertSyntaxBase + 'side:long', freq=alert.freq_once_per_bar_close)
if shortConditionFinal
strategy.entry('Short', strategy.short, qty=contracts)
alert(message=alertSyntaxBase + 'side:short', freq=alert.freq_once_per_bar_close)
if i_useTakeProfit
//Inspired from Multiple %% profit exits example by adolgo https://www.tradingview.com/script/kHhCik9f-Multiple-profit-exits-example/
if i_typeOfTakeProfit == "Multiple Fixed %"
strategy.exit('TP1', qty_percent=i_takeProfitQuantityPercent1, profit=per(i_takeProfitTargetPercent1))
strategy.exit('TP2', qty_percent=i_takeProfitQuantityPercent2, profit=per(i_takeProfitTargetPercent2))
strategy.exit('TP3', qty_percent=i_takeProfitQuantityPercent3, profit=per(i_takeProfitTargetPercent3))
strategy.exit('i_takeProfitTargetPercent4', profit=per(i_takeProfitTargetPercent4))
else
strategy.close('Long', comment=tpCommentLong, when=tpLongCondition)
strategy.close('Short', comment=tpCommentShort, when=tpShortCondition)
if i_useStopLoss
strategy.close('Long', comment=slCommentLong, when=slLongCondition)
strategy.close('Short', comment=slCommentShort, when=slShortCondition)
// Conditional Closes
strategy.close('Long', comment='Conditional Close Long', when=closeLongCondition)
strategy.close('Short', comment='Conditional Close Short', when=closeShortCondition)
// Global Dashboard Variables
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Dashboard Table Text Size
i_tableTextSize = input.string(title="Dashboard Size", defval="Small", options=["Auto", "Huge", "Large", "Normal", "Small", "Tiny"], group="Dashboards")
table_text_size(s) =>
switch s
"Auto" => size.auto
"Huge" => size.huge
"Large" => size.large
"Normal" => size.normal
"Small" => size.small
=> size.tiny
tableTextSize = table_text_size(i_tableTextSize)
/// Performance Summary Dashboard
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Inspired by https://www.tradingview.com/script/uWqKX6A2/ - Thanks VertMT
i_showDashboard = input.bool(title="Performance Summary", defval=true, group="Dashboards", inline="Show Dashboards")
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
_cellText = _title + "\n" + _value
table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=tableTextSize)
// Draw dashboard table
if i_showDashboard
var bgcolor = color.new(color.black,0)
// Keep track of Wins/Losses streaks
newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
varip int winRow = 0
varip int lossRow = 0
varip int maxWinRow = 0
varip int maxLossRow = 0
if newWin
lossRow := 0
winRow := winRow + 1
if winRow > maxWinRow
maxWinRow := winRow
if newLoss
winRow := 0
lossRow := lossRow + 1
if lossRow > maxLossRow
maxLossRow := lossRow
// Prepare stats table
var table dashTable = table.new(position.top_right, 1, 15, border_width=1)
if barstate.islastconfirmedhistory
// Update table
lastTime = strategy.position_size == 0 ? strategy.closedtrades.exit_time(strategy.closedtrades-1) : time
dollarReturn = strategy.netprofit
f_fillCell(dashTable, 0, 0, "Start:", str.format("{0,date,long}", strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.closedtrades.entry_time(0))
f_fillCell(dashTable, 0, 1, "End:", str.format("{0,date,long}", lastTime) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.opentrades.entry_time(0))
_profit = (strategy.netprofit / strategy.initial_capital) * 100
f_fillCell(dashTable, 0, 2, "Net Profit:", str.tostring(_profit, '##.##') + "%", _profit > 0 ? color.teal : color.maroon, color.white)
_numOfDaysInStrategy = (lastTime - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24)
f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit / _numOfDaysInStrategy, '#########################.#####')+"%", _profit > 0 ? color.teal : color.maroon, color.white)
_winRate = ( strategy.wintrades / strategy.closedtrades ) * 100
f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? color.maroon : _winRate < 75 ? #999900 : color.teal, color.white)
f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? color.teal : color.maroon, color.white)
f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white)
f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white)
f_fillCell(dashTable, 0, 9, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white)
// Monthly Table Performance Dashboard By @QuantNomad
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_showMonthlyPerformance = input.bool(true, 'Monthly Performance', group='Dashboards', inline="Show Dashboards")
i_monthlyReturnPercision = 2
if i_showMonthlyPerformance
new_month = month(time) != month(time[1])
new_year = year(time) != year(time[1])
eq = strategy.equity
bar_pnl = eq / eq[1] - 1
cur_month_pnl = 0.0
cur_year_pnl = 0.0
// Current Monthly P&L
cur_month_pnl := new_month ? 0.0 :
(1 + cur_month_pnl[1]) * (1 + bar_pnl) - 1
// Current Yearly P&L
cur_year_pnl := new_year ? 0.0 :
(1 + cur_year_pnl[1]) * (1 + bar_pnl) - 1
// Arrays to store Yearly and Monthly P&Ls
var month_pnl = array.new_float(0)
var month_time = array.new_int(0)
var year_pnl = array.new_float(0)
var year_time = array.new_int(0)
last_computed = false
if (not na(cur_month_pnl[1]) and (new_month or barstate.islastconfirmedhistory))
if (last_computed[1])
array.pop(month_pnl)
array.pop(month_time)
array.push(month_pnl , cur_month_pnl[1])
array.push(month_time, time[1])
if (not na(cur_year_pnl[1]) and (new_year or barstate.islastconfirmedhistory))
if (last_computed[1])
array.pop(year_pnl)
array.pop(year_time)
array.push(year_pnl , cur_year_pnl[1])
array.push(year_time, time[1])
last_computed := barstate.islastconfirmedhistory ? true : nz(last_computed[1])
// Monthly P&L Table
var monthly_table = table(na)
if (barstate.islastconfirmedhistory)
monthly_table := table.new(position.bottom_right, columns = 14, rows = array.size(year_pnl) + 1, border_width = 1)
table.cell(monthly_table, 0, 0, "", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 1, 0, "Jan", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 2, 0, "Feb", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 3, 0, "Mar", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 4, 0, "Apr", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 5, 0, "May", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 6, 0, "Jun", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 7, 0, "Jul", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 8, 0, "Aug", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 9, 0, "Sep", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 10, 0, "Oct", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 11, 0, "Nov", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 12, 0, "Dec", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 13, 0, "Year", bgcolor = #999999, text_size=tableTextSize)
for yi = 0 to array.size(year_pnl) - 1
table.cell(monthly_table, 0, yi + 1, str.tostring(year(array.get(year_time, yi))), bgcolor = #cccccc, text_size=tableTextSize)
y_color = array.get(year_pnl, yi) > 0 ? color.new(color.teal, transp = 40) : color.new(color.gray, transp = 40)
table.cell(monthly_table, 13, yi + 1, str.tostring(math.round(array.get(year_pnl, yi) * 100, i_monthlyReturnPercision)), bgcolor = y_color, text_color=color.new(color.white, 0),text_size=tableTextSize)
for mi = 0 to array.size(month_time) - 1
m_row = year(array.get(month_time, mi)) - year(array.get(year_time, 0)) + 1
m_col = month(array.get(month_time, mi))
m_color = array.get(month_pnl, mi) > 0 ? color.new(color.teal, transp = 40) : color.new(color.maroon, transp = 40)
table.cell(monthly_table, m_col, m_row, str.tostring(math.round(array.get(month_pnl, mi) * 100, i_monthlyReturnPercision)), bgcolor = m_color, text_color=color.new(color.white, 0), text_size=tableTextSize)
|
Rocket Grid Algorithm - The Quant Science | https://www.tradingview.com/script/lm2BJL4V-Rocket-Grid-Algorithm-The-Quant-Science/ | thequantscience | https://www.tradingview.com/u/thequantscience/ | 837 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © thequantscience
// ██████╗ ██████╗ ██████╗██╗ ██╗███████╗████████╗ ██████╗ ██████╗ ██╗██████╗ █████╗ ██╗ ██████╗ ██████╗ ██████╗ ██╗████████╗██╗ ██╗███╗ ███╗
// ██╔══██╗██╔═══██╗██╔════╝██║ ██╔╝██╔════╝╚══██╔══╝ ██╔════╝ ██╔══██╗██║██╔══██╗ ██╔══██╗██║ ██╔════╝ ██╔═══██╗██╔══██╗██║╚══██╔══╝██║ ██║████╗ ████║
// ██████╔╝██║ ██║██║ █████╔╝ █████╗ ██║ ██║ ███╗██████╔╝██║██║ ██║ ███████║██║ ██║ ███╗██║ ██║██████╔╝██║ ██║ ███████║██╔████╔██║
// ██╔══██╗██║ ██║██║ ██╔═██╗ ██╔══╝ ██║ ██║ ██║██╔══██╗██║██║ ██║ ██╔══██║██║ ██║ ██║██║ ██║██╔══██╗██║ ██║ ██╔══██║██║╚██╔╝██║
// ██║ ██║╚██████╔╝╚██████╗██║ ██╗███████╗ ██║ ╚██████╔╝██║ ██║██║██████╔╝ ██║ ██║███████╗╚██████╔╝╚██████╔╝██║ ██║██║ ██║ ██║ ██║██║ ╚═╝ ██║
// ╚═╝ ╚═╝ ╚═════╝ ╚═════╝╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝╚═════╝ ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝
//@version=5
strategy(
title = 'Rocket Grid Algorithm - The Quant Science',
overlay = true,
initial_capital = 10000,
commission_type = strategy.commission.percent,
commission_value = 0.07,
pyramiding = 10,
default_qty_type = strategy.percent_of_equity,
process_orders_on_close=true
)
// #########################################################################################################
long = input.bool(defval = false, title = "Long Strategy |", inline = "Strategy", group = "Strategy Side")
short = input.bool(defval = false, title = "Short Selling Strategy ", inline = "Strategy", group = "Strategy Side")
// #########################################################################################################
startDate = input.int(title="Start Date", defval=1, minval=1, maxval=31, group = "DATE PERIOD CONFIGURATION")
startMonth = input.int(title="Start Month", defval=1, minval=1, maxval=12, group = "DATE PERIOD CONFIGURATION")
startYear = input.int(title="Start Year", defval=2018, minval=1800, maxval=2100, group = "DATE PERIOD CONFIGURATION")
endDate = input.int(title="End Date", defval=31, minval=1, maxval=31, group = "DATE PERIOD CONFIGURATION")
endMonth = input.int(title="End Month", defval=12, minval=1, maxval=12, group = "DATE PERIOD CONFIGURATION")
endYear = input.int(title="End Year", defval=2023, minval=1800, maxval=2100, group = "DATE PERIOD CONFIGURATION")
inDateRange = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0)) and (time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0))
// #########################################################################################################
lenght_data = input.int(defval = 10, title = "Lenght: ", minval = 0, group = "Lenght Configuration")
// #########################################################################################################
sma = ta.sma(close, lenght_data)
// #########################################################################################################
ten_grid = input.bool(defval = false, title = "Enable Strategy", tooltip = "Create grid backtesting.", group = "STRATEGY CONFIGURATION")
percentagegrid = input.float(defval = 0.50, minval = 0, step = 0.10, title = "Percentage grid: ", group = "STRATEGY CONFIGURATION")
stop_loss = input.float(defval = 2.00, minval = 0, step = 0.10, title = "Lower destroyer: ", group = "STRATEGY CONFIGURATION")
take_profit = input.float(defval = 2.00, minval = 0, step = 0.10, title = "Upper destroyer: ", group = "STRATEGY CONFIGURATION")
// #########################################################################################################
var float high_start = 0
var float high_end = 0
trigger_event_sma1 = ta.crossunder(close, sma) and barstate.isconfirmed
trigger_event_sma2 = ta.crossover(close, sma) and barstate.isconfirmed
TriggerGrid(type) =>
switch type
'SMA Based Crossunder' => trigger_event_sma1==true
'SMA Based Crossover' => trigger_event_sma2==true
type_input = input.string(
'SMA Based Crossunder',
title = "Select strategy: ",
options = [
'SMA Based Crossunder',
'SMA Based Crossover'
],
group = "Trigger definition"
)
trigger_entry = TriggerGrid(type_input) and strategy.opentrades==0
p_trigger_event = ta.valuewhen(trigger_entry, close, 0)
total_percentage_side = 10 * percentagegrid
if trigger_entry==true
high_start := p_trigger_event + ((p_trigger_event * total_percentage_side)/100)
high_end := p_trigger_event - ((p_trigger_event * total_percentage_side)/100)
grid_range = high_start - high_end
var float grid_1 = 0
var float grid_2 = 0
var float grid_3 = 0
var float grid_4 = 0
var float grid_5 = 0
var float grid_6 = 0
var float grid_7 = 0
var float grid_8 = 0
var float grid_9 = 0
var float grid_10 = 0
var float grid_11 = 0
var float grid_12 = 0
var float grid_13 = 0
var float grid_14 = 0
var float grid_15 = 0
var float grid_16 = 0
var float grid_17 = 0
var float grid_18 = 0
var float grid_19 = 0
var float grid_20 = 0
var float factor = 0
var float p = 0
if ten_grid == true and trigger_entry==true
factor := grid_range / 20
p := p_trigger_event
// UP GRID
grid_1 := (p + (factor * 1))
grid_2 := (p + (factor * 2))
grid_3 := (p + (factor * 3))
grid_4 := (p + (factor * 4))
grid_5 := (p + (factor * 5))
grid_6 := (p + (factor * 6))
grid_7 := (p + (factor * 7))
grid_8 := (p + (factor * 8))
grid_9 := (p + (factor * 9))
grid_10 := (p + (factor * 10))
// DOWN GRID
grid_11 := (p - (factor * 1))
grid_12 := (p - (factor * 2))
grid_13 := (p - (factor * 3))
grid_14 := (p - (factor * 4))
grid_15 := (p - (factor * 5))
grid_16 := (p - (factor * 6))
grid_17 := (p - (factor * 7))
grid_18 := (p - (factor * 8))
grid_19 := (p - (factor * 9))
grid_20 := (p - (factor * 10))
var float new_ten_grid_1 = 0
var float new_ten_grid_2 = 0
var float new_ten_grid_3 = 0
var float new_ten_grid_4 = 0
var float new_ten_grid_5 = 0
var float new_ten_grid_6 = 0
var float new_ten_grid_7 = 0
var float new_ten_grid_8 = 0
var float new_ten_grid_9 = 0
var float new_ten_grid_10 = 0
var float new_ten_grid_11 = 0
var float new_ten_grid_12 = 0
var float new_ten_grid_13 = 0
var float new_ten_grid_14 = 0
var float new_ten_grid_15 = 0
var float new_ten_grid_16 = 0
var float new_ten_grid_17 = 0
var float new_ten_grid_18 = 0
var float new_ten_grid_19 = 0
var float new_ten_grid_20 = 0
destroyall = new_ten_grid_20 - (new_ten_grid_20 * stop_loss / 100)
des_function = ta.crossunder(close, destroyall)
takeprofitlevel = new_ten_grid_10 + (new_ten_grid_10 * take_profit / 100)
des_function2 = ta.crossover(close, takeprofitlevel)
var float lots_up1 = 0
var float lots_up2 = 0
var float lots_up3 = 0
var float lots_up4 = 0
var float lots_up5 = 0
var float lots_up6 = 0
var float lots_up7 = 0
var float lots_up8 = 0
var float lots_up9 = 0
var float lots_up10 = 0
var float lots_down1 = 0
var float lots_down2 = 0
var float lots_down3 = 0
var float lots_down4 = 0
var float lots_down5 = 0
var float lots_down6 = 0
var float lots_down7 = 0
var float lots_down8 = 0
var float lots_down9 = 0
var float lots_down10 = 0
if trigger_entry==true and ten_grid==true and inDateRange and strategy.opentrades==0
new_ten_grid_1 := grid_1
new_ten_grid_2 := grid_2
new_ten_grid_3 := grid_3
new_ten_grid_4 := grid_4
new_ten_grid_5 := grid_5
new_ten_grid_6 := grid_6
new_ten_grid_7 := grid_7
new_ten_grid_8 := grid_8
new_ten_grid_9 := grid_9
new_ten_grid_10 := grid_10
new_ten_grid_11 := grid_11
new_ten_grid_12 := grid_12
new_ten_grid_13 := grid_13
new_ten_grid_14 := grid_14
new_ten_grid_15 := grid_15
new_ten_grid_16 := grid_16
new_ten_grid_17 := grid_17
new_ten_grid_18 := grid_18
new_ten_grid_19 := grid_19
new_ten_grid_20 := grid_20
lots_up1 := (((strategy.equity / close) * 10) /100)
lots_up2 := (((strategy.equity / close) * 9) /100)
lots_up3 := (((strategy.equity / close) * 8) /100)
lots_up4 := (((strategy.equity / close) * 7) /100)
lots_up5 := (((strategy.equity / close) * 6) /100)
lots_up6 := (((strategy.equity / close) * 5) /100)
lots_up7 := (((strategy.equity / close) * 4) /100)
lots_up8 := (((strategy.equity / close) * 3) /100)
lots_up9 := (((strategy.equity / close) * 2) /100)
lots_up10 := (((strategy.equity / close) * 1) /100)
if long == true
if new_ten_grid_1
strategy.entry(id = "O #1", direction = strategy.long, qty = lots_up1, stop = new_ten_grid_1)
if new_ten_grid_2
strategy.entry(id = "O #2", direction = strategy.long, qty = lots_up2, stop = new_ten_grid_2)
if new_ten_grid_3
strategy.entry(id = "O #3", direction = strategy.long, qty = lots_up3, stop = new_ten_grid_3)
if new_ten_grid_4
strategy.entry(id = "O #4", direction = strategy.long, qty = lots_up4, stop = new_ten_grid_4)
if new_ten_grid_5
strategy.entry(id = "O #5", direction = strategy.long, qty = lots_up5, stop = new_ten_grid_5)
if new_ten_grid_6
strategy.entry(id = "O #6", direction = strategy.long, qty = lots_up6, stop = new_ten_grid_6)
if new_ten_grid_7
strategy.entry(id = "O #7", direction = strategy.long, qty = lots_up7, stop = new_ten_grid_7)
if new_ten_grid_8
strategy.entry(id = "O #8", direction = strategy.long, qty = lots_up8, stop = new_ten_grid_8)
if new_ten_grid_9
strategy.entry(id = "O #9", direction = strategy.long, qty = lots_up9, stop = new_ten_grid_9)
if new_ten_grid_10
strategy.entry(id = "O #10", direction = strategy.long, qty = lots_up10, stop = new_ten_grid_10)
if short == true
if new_ten_grid_1
strategy.entry(id = "O #1", direction = strategy.short, qty = lots_up1, limit = new_ten_grid_1)
if new_ten_grid_2
strategy.entry(id = "O #2", direction = strategy.short, qty = lots_up2, limit = new_ten_grid_2)
if new_ten_grid_3
strategy.entry(id = "O #3", direction = strategy.short, qty = lots_up3, limit = new_ten_grid_3)
if new_ten_grid_4
strategy.entry(id = "O #4", direction = strategy.short, qty = lots_up4, limit = new_ten_grid_4)
if new_ten_grid_5
strategy.entry(id = "O #5", direction = strategy.short, qty = lots_up5, limit = new_ten_grid_5)
if new_ten_grid_6
strategy.entry(id = "O #6", direction = strategy.short, qty = lots_up6, limit = new_ten_grid_6)
if new_ten_grid_7
strategy.entry(id = "O #7", direction = strategy.short, qty = lots_up7, limit = new_ten_grid_7)
if new_ten_grid_8
strategy.entry(id = "O #8", direction = strategy.short, qty = lots_up8, limit = new_ten_grid_8)
if new_ten_grid_9
strategy.entry(id = "O #9", direction = strategy.short, qty = lots_up9, limit = new_ten_grid_9)
if new_ten_grid_10
strategy.entry(id = "O #10", direction = strategy.short, qty = lots_up10, limit = new_ten_grid_10)
if des_function or des_function2 or close <= destroyall or close >= takeprofitlevel
strategy.close_all(">>>> Destroyed Grid <<<<")
// #########################################################################################################
fill(plot(grid_1, color = color.new(color.rgb(0, 255, 132), 95)),
plot(grid_2, color = color.new(color.rgb(0, 255, 132), 95)),
color = color.new(#00ff08, 80))
fill(plot(grid_2, color = color.new(color.rgb(0, 255, 132), 95)),
plot(grid_3, color = color.new(color.rgb(0, 255, 132), 95)),
color = color.new(#00ff08, 85))
fill(plot(grid_3, color = color.new(color.rgb(0, 255, 132), 95)),
plot(grid_4, color = color.new(color.rgb(0, 255, 132), 95)),
color = color.new(#00ff08, 85))
fill(plot(grid_4, color = color.new(color.rgb(0, 255, 132), 95)),
plot(grid_5, color = color.new(color.rgb(0, 255, 132), 95)),
color = color.new(#00ff08, 90))
fill(plot(grid_1, color = color.new(color.rgb(0, 255, 132), 95)),
plot(grid_6, color = color.new(color.rgb(0, 255, 132), 95)),
color = color.new(#00ff08, 80))
fill(plot(grid_6, color = color.new(color.rgb(0, 255, 132), 95)),
plot(grid_7, color = color.new(color.rgb(0, 255, 132), 95)),
color = color.new(#00ff08, 80))
fill(plot(grid_7, color = color.new(color.rgb(0, 255, 132), 95)),
plot(grid_8, color = color.new(color.rgb(0, 255, 132), 95)),
color = color.new(#00ff08, 85))
fill(plot(grid_8, color = color.new(color.rgb(0, 255, 132), 95)),
plot(grid_9, color = color.new(color.rgb(0, 255, 132), 95)),
color = color.new(#00ff08, 85))
fill(plot(grid_9, color = color.new(color.rgb(0, 255, 132), 95)),
plot(grid_10, color = color.new(color.rgb(0, 255, 132), 95)),
color = color.new(#00ff08, 90))
fill(plot(grid_11, color = color.new(#ff3c00, 95)),
plot(grid_12, color = color.new(#fd3d36, 95)),
color = color.new(#ff0000, 80))
fill(plot(grid_12, color = color.new(#ff0000, 95)),
plot(grid_13, color = color.new(#ff0000, 95)),
color = color.new(#ff0000, 85))
fill(plot(grid_13, color = color.new(#ff0000, 95)),
plot(grid_14, color = color.new(#ff0000, 95)),
color = color.new(#ff0000, 85))
fill(plot(grid_14, color = color.new(#ff0000, 95)),
plot(grid_15, color = color.new(#ff0000, 95)),
color = color.new(#ff0000, 90))
fill(plot(grid_11, color = color.new(#ff0000, 95)),
plot(grid_16, color = color.new(#ff0800, 95)),
color = color.new(#ff4800, 80))
fill(plot(grid_16, color = color.new(#ff1100, 95)),
plot(grid_17, color = color.new(#ff2600, 95)),
color = color.new(#ff3300, 80))
fill(plot(grid_17, color = color.new(#ff0000, 95)),
plot(grid_18, color = color.new(#ff0000, 95)),
color = color.new(#ff3c00, 85))
fill(plot(grid_18, color = color.new(#ff3300, 95)),
plot(grid_19, color = color.new(#ff3c00, 95)),
color = color.new(#ff3300, 85))
fill(plot(grid_19, color = color.new(#ff3c00, 95)),
plot(grid_20, color = color.new(#ff0800, 95)),
color = color.new(#ff1e00, 90))
// #########################################################################################################
if strategy.equity <= 0
runtime.error(" BANKRUPTCY: BACKTEST RETURN LOSS > EQUITY !!! ")
// ########################################################################################################### |
Exponential Stochastic Strategy | https://www.tradingview.com/script/Sr0hedIS-Exponential-Stochastic-Strategy/ | faytterro | https://www.tradingview.com/u/faytterro/ | 214 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © faytterro
//@version=5
strategy("Exponential Stochastic Strategy", overlay=false, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
len=input.int(14, "length")
ex=input.int(2, title="exp", minval=1, maxval=10)
exp= ex<10? (ex)/(10-ex) : 99
s=100 * (close - ta.lowest(low, len)) / (ta.highest(high, len) - ta.lowest(low, len))
ks=s>50? math.pow(math.abs(s-50),exp)/math.pow(50,exp-1)+50 :
-math.pow(math.abs(s-50),exp)/math.pow(50,exp-1)+50
plot(ks, color= color.white)
bot=input.int(20)
top=input.int(80)
longCondition = ta.crossover(ks, bot) and bar_index>0
if (longCondition)
strategy.entry("My Long Entry Id", strategy.long)
shortCondition = ta.crossunder(ks, top) and bar_index>0
if (shortCondition)
strategy.entry("My Short Entry Id", strategy.short)
// strategy.close("My Long Entry Id")
alertcondition(longCondition, title = "buy")
alertcondition(shortCondition, title = "sell")
h1=hline(top)
h2=hline(bot)
h3=hline(100)
h4=hline(0)
fill(h1,h3, color= color.rgb(255,0,0,200-top*2))
fill(h2,h4, color= color.rgb(0,255,0,bot*2)) |
Strategy Myth-Busting #13 - MultiEMA+BXTrender - [SP/MYN] | https://www.tradingview.com/script/bjqkRVZI-Strategy-Myth-Busting-13-MultiEMA-BXTrender-SP-MYN/ | myncrypto | https://www.tradingview.com/u/myncrypto/ | 197 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © spdoinkal / myncrypto
//@version=5
strategy('Strategy Myth-Busting #13 - MultiEMA+BXTrender - [SP/MYN]', max_bars_back=5000, overlay=true, pyramiding=0, initial_capital=1000, currency='USD', default_qty_type=strategy.percent_of_equity, default_qty_value=10.0, commission_value=0.075, use_bar_magnifier = false)
// Secret EMA Cloud by teddycleps
// B-X Trender
// Keep all default
// Distance between EMA's need to be spaced, otherwise in a ranged market
// 15 min candles
// Stop Loss on previous swing high/low
// No take profit. Exit on new red/green circle
//Long
//EMA Green (21) on top, White (89)in middle and red (200) on bottom and there is distance between EMA's need to be spaced, otherwise in a ranged market
// Price action must pull back into 89 EMA (White line) either close or touching it.
// Once pullback occurs wait for BX Trender to issue a new green circle and BX Trend line must be green and above 0
// Price action must also pull up back above the (Green Line) EMA 21
//Short
//EMA Red (200) on top, White (89) in middle and Green (21) on bottom and there is distance between EMA's need to be spaced, otherwise in a ranged market
// Price action must pull back into 89 EMA (White line) either close or touching it.
// Once pullback occurs wait for BX Trender to issue a new red circle and BX Trend line must be red and below 0
// Price action must also pull up back below the (green Line) EMA 21
// 21/89/200 EMA Cloud
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
var string EMAGroupName = 'EMA Cloud'
i_fastEMALength = input.int(21, title = 'Fast EMA length', step = 1, group = EMAGroupName)
i_midEMALength = input.int(89, title = 'Mid EMA length', step = 1, group = EMAGroupName)
i_slowEMALength = input.int(200, title ='Slow EMA length', step = 10, group = EMAGroupName)
fEMA = ta.ema(close, i_fastEMALength)
mEMA = ta.ema(close, i_midEMALength)
sEMA = ta.ema(close, i_slowEMALength)
plotFEMA = plot(fEMA, 'FAST EMA', color=color.new(color.green, 0), linewidth = 2, style=plot.style_line)
plotMEMA = plot(mEMA, 'MID EMA', color=color.new(color.white, 0), linewidth = 2, style=plot.style_line)
plotSEMA = plot(sEMA, 'SLOW EMA', color=color.new(color.red, 0), linewidth = 2, style=plot.style_line)
fill(plotFEMA, plotSEMA, color=fEMA > sEMA ? color.new(color.green, 80) : color.new(color.red, 70), title='EMA Background Fill')
// B-Xtrender @Puppytherapy
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
var string BXTenderGroupName = 'B-XTENDER INPUTS'
short_l1 = input(5, title='Short - L1', group = BXTenderGroupName)
short_l2 = input(20, title='Short - L2', group = BXTenderGroupName)
short_l3 = input(15, title='Short - L3', group = BXTenderGroupName)
long_l1 = input(20, title='Long - L1', group = BXTenderGroupName)
long_l2 = input(15, title='Long - L2', group = BXTenderGroupName)
shortTermXtrender = ta.rsi(ta.ema(close, short_l1) - ta.ema(close, short_l2), short_l3) - 50
longTermXtrender = ta.rsi(ta.ema(close, long_l1), long_l2) - 50
// shortXtrenderCol = shortTermXtrender > 0 ? shortTermXtrender > shortTermXtrender[1] ? color.lime : #228B22 : shortTermXtrender > shortTermXtrender[1] ? color.red : #8B0000
// plot(shortTermXtrender, color=shortXtrenderCol, style=plot.style_columns, linewidth=1, title='B-Xtrender Osc. - Histogram', transp=50)
t3(src, len) =>
xe1_1 = ta.ema(src, len)
xe2_1 = ta.ema(xe1_1, len)
xe3_1 = ta.ema(xe2_1, len)
xe4_1 = ta.ema(xe3_1, len)
xe5_1 = ta.ema(xe4_1, len)
xe6_1 = ta.ema(xe5_1, len)
b_1 = 0.7
c1_1 = -b_1 * b_1 * b_1
c2_1 = 3 * b_1 * b_1 + 3 * b_1 * b_1 * b_1
c3_1 = -6 * b_1 * b_1 - 3 * b_1 - 3 * b_1 * b_1 * b_1
c4_1 = 1 + 3 * b_1 + b_1 * b_1 * b_1 + 3 * b_1 * b_1
nT3Average_1 = c1_1 * xe6_1 + c2_1 * xe5_1 + c3_1 * xe4_1 + c4_1 * xe3_1
nT3Average_1
maShortTermXtrender = t3(shortTermXtrender, 5)
// colShortTermXtrender = maShortTermXtrender > maShortTermXtrender[1] ? color.lime : color.red
// plot(maShortTermXtrender, color=color.new(#000000, 0), style=plot.style_line, linewidth=3, title='B-Xtrender Shadow')
// plot(maShortTermXtrender, color=colShortTermXtrender, style=plot.style_line, linewidth=3, title='B-Xtrender Color ')
BXTenderLongEntryCondition = maShortTermXtrender > maShortTermXtrender[1] and maShortTermXtrender[1] < maShortTermXtrender[2]
BXTenderShortEntryCondition = maShortTermXtrender < maShortTermXtrender[1] and maShortTermXtrender[1] > maShortTermXtrender[2]
plotshape(BXTenderLongEntryCondition ? maShortTermXtrender : na, location=location.belowbar, style=shape.circle, color=color.new(color.lime, 10), size=size.tiny)
plotshape(BXTenderShortEntryCondition ? maShortTermXtrender : na, location=location.abovebar, style=shape.circle, color=color.new(color.red, 10), size=size.tiny)
/////////////////////////////////////
//* Put your strategy rules below *//
/////////////////////////////////////
uptrend = fEMA > mEMA and mEMA > sEMA
dntrend = fEMA < mEMA and mEMA < sEMA
// Checks for suitable distance between EMAS
var string EMADistanceGroupName = 'Minimum Gap Distance Between EMAs'
i_minDistanceBetweenEMAs = input(78,title="Minimum distance between 21, 89 and 200 EMAs", group = EMADistanceGroupName)
bool EMAUptrendWithDistance = (fEMA > (mEMA + i_minDistanceBetweenEMAs)) and (mEMA > (sEMA + i_minDistanceBetweenEMAs))
bool EMADowntrendWithDistance = (fEMA < (mEMA - i_minDistanceBetweenEMAs)) and (mEMA < (sEMA - i_minDistanceBetweenEMAs))
fill(plotFEMA, plotSEMA, color = EMAUptrendWithDistance or EMADowntrendWithDistance ? color.new(color.gray, 70) : na)
// var string pullBackGroupName = 'EMA Pullback Settings'
// i_marginAboveOrBelowMidEMA = input(100,title="Margin of proximity to middle EMA for pullback detection", group=pullBackGroupName)
// i_lookbackForEMAPullback = input(8, title="Lookback for EMA Pullback", group=pullBackGroupName)
// longMidEMAWithMargin = mEMA + i_marginAboveOrBelowMidEMA
// shortMidEMAWithMargin = mEMA - i_marginAboveOrBelowMidEMA
// longEMAPullBack = close < longMidEMAWithMargin
// shortEMAPullBack= close > shortMidEMAWithMargin
// longPB = ta.barssince(longEMAPullBack) <= i_lookbackForEMAPullback
// shortPB = ta.barssince(shortEMAPullBack) <= i_lookbackForEMAPullback
//Check for pullback / pushup into middle EMA calcs
var string pullBackGroupName = 'EMA Pullback Settings'
PBperc = input.float(0.5, title = "% Diff for EMA Pullback", step = 0.1, group=pullBackGroupName)
PBlength = input.int(8, title = "Lookback for EMA Pullback", group=pullBackGroupName)
// Look for a pullback to the middle EMA (LONGS)
longPercentDiff = ((low - mEMA) / low) * 100
longPBcheck = longPercentDiff <= PBperc
longPB = ta.barssince(longPBcheck) <= PBlength
// Look for a pushup to the middle EMA (SHORTS)
shortPercentDiff = ((mEMA - high) / mEMA) * 100
shortPBcheck = shortPercentDiff <= PBperc
shortPB = ta.barssince(shortPBcheck) <= PBlength
plotshape(longPB and not longPB[1], "", shape.labelup, location.belowbar, color= color.green, textcolor = color.white, text = "(2) Bull Pullback")
plotshape(shortPB and not shortPB[1], "", shape.labeldown, location.abovebar, color= color.red, textcolor = color.white, text = "(2) Bear Pullback")
longCondition = uptrend and EMAUptrendWithDistance and longPB and BXTenderLongEntryCondition and longTermXtrender > 0 and ta.rising(longTermXtrender, 1) and close > fEMA
shortCondition = dntrend and EMADowntrendWithDistance and shortPB and BXTenderShortEntryCondition and longTermXtrender < 0 and ta.falling(longTermXtrender, 1) and close < fEMA
closeLong = BXTenderShortEntryCondition
closeShort = BXTenderLongEntryCondition
useClose = input.bool(true, title = "Use Close Signal", group='Trade Direction')
//define as 0 if do not want to use
closeLongCondition = useClose ? closeLong : 0
closeShortCondition = useClose ? closeShort : 0
// ADX
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
adxEnabled = input.bool(defval = false , title = "Average Directional Index (ADX)", tooltip = "", group ="ADX" )
adxlen = input(14, title = "ADX Smoothing", group="ADX")
adxdilen = input(14, title = "DI Length", group="ADX")
adxabove = input(26, title = "ADX Threshold", group="ADX")
adxdirmov(len) =>
adxup = ta.change(high)
adxdown = -ta.change(low)
adxplusDM = na(adxup) ? na : (adxup > adxdown and adxup > 0 ? adxup : 0)
adxminusDM = na(adxdown) ? na : (adxdown > adxup and adxdown > 0 ? adxdown : 0)
adxtruerange = ta.rma(ta.tr, len)
adxplus = fixnan(100 * ta.rma(adxplusDM, len) / adxtruerange)
adxminus = fixnan(100 * ta.rma(adxminusDM, len) / adxtruerange)
[adxplus, adxminus]
adx(adxdilen, adxlen) =>
[adxplus, adxminus] = adxdirmov(adxdilen)
adxsum = adxplus + adxminus
adx = 100 * ta.rma(math.abs(adxplus - adxminus) / (adxsum == 0 ? 1 : adxsum), adxlen)
adxsig = adxEnabled ? adx(adxdilen, adxlen) : na
isADX = adxEnabled ? (adxsig > adxabove) : true
//Backtesting Time Period (Input.time not working as expected as of 03/30/2021. Giving odd start/end dates
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
useStartPeriodTime = input.bool(true, 'Start', group='Date Range', inline='Start Period')
startPeriodTime = input.time(timestamp('1 Jan 2019'), '', group='Date Range', inline='Start Period')
useEndPeriodTime = input.bool(true, 'End', group='Date Range', inline='End Period')
endPeriodTime = input.time(timestamp('31 Dec 2030'), '', group='Date Range', inline='End Period')
start = useStartPeriodTime ? startPeriodTime >= time : false
end = useEndPeriodTime ? endPeriodTime <= time : false
calcPeriod = not start and not end
// Trade Direction
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tradeDirection = input.string('Long and Short', title = 'Trade Direction', options=['Long and Short', 'Long Only', 'Short Only'], group='Trade Direction')
// Percent as Points
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
per(pcnt) =>
strategy.position_size != 0 ? math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na)
// Take profit 1
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp1 = input.float(title = 'Take Profit 1 - Target %', defval=0.5, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 1')
q1 = input.int(title = '% Of Position', defval=25, minval=0, group='Take Profit', inline='Take Profit 1')
// Take profit 2
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp2 = input.float(title = 'Take Profit 2 - Target %', defval=1.5, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 2')
q2 = input.int(title = '% Of Position', defval=50, minval=0, group='Take Profit', inline='Take Profit 2')
// Take profit 3
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp3 = input.float(title = 'Take Profit 3 - Target %', defval=2.5, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 3')
q3 = input.int(title = '% Of Position', defval=25, minval=0, group='Take Profit', inline='Take Profit 3')
// Take profit 4
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp4 = input.float(title = 'Take Profit 4 - Target %', defval=7.5, minval=0.0, step=0.5, group='Take Profit')
/// Stop Loss
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
stoplossPercent = input.float(title = 'Stop Loss (%)', defval=3.0, minval=0.01, step = 0.5, group='Stop Loss') * 0.01
slLongClose = close < strategy.position_avg_price * (1 - stoplossPercent)
slShortClose = close > strategy.position_avg_price * (1 + stoplossPercent)
/// Leverage
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
leverage = input.float(1, 'Leverage', step=.5, group='Leverage')
contracts = math.min(math.max(.000001, strategy.equity / close * leverage), 1000000000)
/// Trade State Management
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
isInLongPosition = strategy.position_size > 0
isInShortPosition = strategy.position_size < 0
/// ProfitView Alert Syntax String Generation
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
alertSyntaxPrefix = input.string(defval='CRYPTANEX_99FTX_Strategy-Name-Here', title = 'Alert Syntax Prefix', group='ProfitView Alert Syntax')
alertSyntaxBase = alertSyntaxPrefix + '\n#' + str.tostring(open) + ',' + str.tostring(high) + ',' + str.tostring(low) + ',' + str.tostring(close) + ',' + str.tostring(volume) + ','
/// Trade Execution
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
longConditionCalc = (longCondition and isADX)
shortConditionCalc = (shortCondition and isADX)
// plotshape(shortConditionCalc, title='Short', style=shape.labeldown, location=location.abovebar, size=size.tiny, text='Short', textcolor=color.new(color.white, 0), color=color.new(color.red, 0))
// plotshape(longConditionCalc, title='Long', style=shape.labelup, location=location.belowbar, size=size.tiny, text='Long', textcolor=color.new(color.white, 0), color=color.new(color.green, 0))
if calcPeriod
if longConditionCalc and tradeDirection != 'Short Only' and isInLongPosition == false
strategy.entry('Long', strategy.long, qty=contracts)
alert(message=alertSyntaxBase + 'side:long', freq=alert.freq_once_per_bar_close)
if shortConditionCalc and tradeDirection != 'Long Only' and isInShortPosition == false
strategy.entry('Short', strategy.short, qty=contracts)
alert(message=alertSyntaxBase + 'side:short', freq=alert.freq_once_per_bar_close)
//Inspired from Multiple %% profit exits example by adolgo https://www.tradingview.com/script/kHhCik9f-Multiple-profit-exits-example/
strategy.exit('TP1', qty_percent=q1, profit=per(tp1))
strategy.exit('TP2', qty_percent=q2, profit=per(tp2))
strategy.exit('TP3', qty_percent=q3, profit=per(tp3))
strategy.exit('TP4', profit=per(tp4))
strategy.close('Long', qty_percent=100, comment='SL Long', when=slLongClose)
strategy.close('Short', qty_percent=100, comment='SL Short', when=slShortClose)
strategy.close_all(when=closeLongCondition or closeShortCondition, comment='Close Postion')
/// Dashboard
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Inspired by https://www.tradingview.com/script/uWqKX6A2/ - Thanks VertMT
showDashboard = input.bool(group="Dashboard", title = "Show Dashboard", defval=true)
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
_cellText = _title + "\n" + _value
table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=size.auto)
// Draw dashboard table
if showDashboard
var bgcolor = color.new(color.black,0)
// Keep track of Wins/Losses streaks
newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
varip int winRow = 0
varip int lossRow = 0
varip int maxWinRow = 0
varip int maxLossRow = 0
if newWin
lossRow := 0
winRow := winRow + 1
if winRow > maxWinRow
maxWinRow := winRow
if newLoss
winRow := 0
lossRow := lossRow + 1
if lossRow > maxLossRow
maxLossRow := lossRow
// Prepare stats table
var table dashTable = table.new(position.bottom_right, 1, 15, border_width=1)
if barstate.islastconfirmedhistory
// Update table
dollarReturn = strategy.netprofit
f_fillCell(dashTable, 0, 0, "Start:", str.format("{0,date,long}", strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.closedtrades.entry_time(0))
f_fillCell(dashTable, 0, 1, "End:", str.format("{0,date,long}", strategy.opentrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.opentrades.entry_time(0))
_profit = (strategy.netprofit / strategy.initial_capital) * 100
f_fillCell(dashTable, 0, 2, "Net Profit:", str.tostring(_profit, '##.##') + "%", _profit > 0 ? color.green : color.red, color.white)
_numOfDaysInStrategy = (strategy.opentrades.entry_time(0) - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24)
f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit / _numOfDaysInStrategy, '#########################.#####')+"%", _profit > 0 ? color.green : color.red, color.white)
_winRate = ( strategy.wintrades / strategy.closedtrades ) * 100
f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? color.red : _winRate < 75 ? #999900 : color.green, color.white)
f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? color.green : color.red, color.white)
f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white)
f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white)
f_fillCell(dashTable, 0, 9, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white)
|
Kimchi Premium Strategy | https://www.tradingview.com/script/rgwM3P1f/ | chanu_lev10k | https://www.tradingview.com/u/chanu_lev10k/ | 155 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © chanu_lev10k
//@version=5
strategy("Kimchi Premium Strategy", overlay=false)
// Inputs
sym_krw = input.symbol(title='Select BTCKRW Market', defval='BITHUMB:BTCKRW')
sym_usd = input.symbol(title='Select BTCUSD Market', defval='BITSTAMP:BTCUSD')
res = input.timeframe(title='Resolution', defval='')
src = input.source(title='Source', defval=close)
len1 = input.int(defval=4, title='Length of RSI')
len2 = input.int(defval=12, title='Length of Inverse Kimchi Premium RSI')
isikp = input.bool(title='Use Combination of Inverse Kimchi Premium RSI ?', defval=true)
bullLevel = input.float(title='Bull Level', defval=63, step=1.0, maxval=100, minval=0)
bearLevel = input.float(title='Bear Level', defval=28, step=1.0, maxval=100, minval=0)
highlightBreakouts = input(title='Highlight Bull/Bear Breakouts ?', defval=true)
// Inverse Kimichi Premium RSI Definition
up = ta.rma(math.max(ta.change(src), 0), len1)
down = ta.rma(-math.min(ta.change(src), 0), len1)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
usdkrw = request.security('FX_IDC:USDKRW', res, src)
btckrw = request.security(sym_krw, res, src)
btcusd = request.security(sym_usd, res, src)
btcusd_to_krw = btcusd * usdkrw
ikp = (btcusd_to_krw / btckrw - 1) * 100
ikp_f(res, len1, len2) =>
n = rsi
t = (rsi + ta.rsi(ikp, len2))/2
isikp ? t : n
tot_rsi = ikp_f(res, len1, len2)
// Plot
rcColor = tot_rsi > bullLevel ? #0ebb23 : tot_rsi < bearLevel ? #ff0000 : #f4b77d
maxBand = hline(100, title='Max Level', linestyle=hline.style_dotted, color=color.white)
hline(0, title='Zero Level', linestyle=hline.style_dotted)
minBand = hline(0, title='Min Level', linestyle=hline.style_dotted, color=color.white)
bullBand = hline(bullLevel, title='Bull Level', linestyle=hline.style_dotted)
bearBand = hline(bearLevel, title='Bear Level', linestyle=hline.style_dotted)
fill(bullBand, bearBand, color=color.new(color.purple, 95))
bullFillColor = tot_rsi > bullLevel and highlightBreakouts ? color.green : na
bearFillColor = tot_rsi < bearLevel and highlightBreakouts ? color.red : na
fill(maxBand, bullBand, color=color.new(bullFillColor, 80))
fill(minBand, bearBand, color=color.new(bearFillColor, 80))
plot(tot_rsi, title='Total RSI', linewidth=2, color=rcColor)
plot(rsi, title='RSI', linewidth=1, color=color.new(color.purple, 0))
plot(ta.rsi(ikp, len2), title='Inverse Kimchi Premium RSI', linewidth=1, color=color.new(color.blue, 0))
// Long Short conditions
longCondition = ta.crossover(tot_rsi, bullLevel)
if longCondition
strategy.entry('Long', strategy.long)
shortCondition = ta.crossunder(tot_rsi, bearLevel)
if shortCondition
strategy.entry('Short', strategy.short) |
Simple_RSI+PA+DCA Strategy | https://www.tradingview.com/script/q4JwUUwC-Simple-RSI-PA-DCA-Strategy/ | A3Sh | https://www.tradingview.com/u/A3Sh/ | 279 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0///
// © A3Sh
//@version=5
// Study of a Simple RSI based, PA (priceaveraging) and DCA strategy that opens a new position everytime it hits a specified price level below the first entry.
// The first entry is opened when the specified rsi and moving average conditions are met.
// The following DCA levels are calculated exponentially and set, starting with a specified % of price drop.
// The disctance between the dca levels can be changed with the exponential scale.
// Each position closes individually when it reaches a specified take profit.
// The position can re-open again when it hits the price level again.
// Each time a position is closed and reopened, the average price drops a little.
// The position stays open until the first entry closes or when the price reaches the Stop level.
// When the price reaches the Stop level, all positions will close at once.
// The RSI and MA code for opening the entry is adapted from the Optimized RSI Buy the Dips strategy, by Coinrule.
// This code is used for study purposes, but any other low/ dip finding indicator can be used.
// https://www.tradingview.com/script/Pm1WAtyI-Optimized-RSI-Strategy-Buy-The-Dips-by-Coinrule/
// Dynamic DCA layers are inspired by the Backtesting 3commas DCA Bot v2, by rouxam
// This logic gives more flexibility because you can dyanically change the amount of dca entries.
// https://www.tradingview.com/script/8d6Auyst-Backtesting-3commas-DCA-Bot-v2/
// The use of for loops to (re)open and close different entries separately is based on the Simple_Pyramiding strategy.
// https://www.tradingview.com/script/t6cNLqDN-Simple-Pyramiding/
strategy('Simple_RSI+PA+DCA', overlay=true, pyramiding=99, initial_capital=500, calc_on_order_fills=true, default_qty_type=strategy.percent_of_equity, commission_type=strategy.commission.percent, commission_value=0.075, close_entries_rule='FIFO')
// Backtest Window //
start_time = input.time(defval=timestamp("01 April 2021 20:00"), group = "Backtest Window", title="Start Time")
end_time = input.time(defval=timestamp("01 Aug 2030 20:00"), group = "Backtest Window", title="End Time")
window() => time >= start_time and time <= end_time
// Inputs //
takeProfit = input.float (3, group = 'Risk', title = 'Take Profit %', step=0.1)
takeProfitAll = input.float (6, group = "Risk", title = 'Close All %', step=0.1)
linear_mode = input.bool (false, group = 'DCA Settings', title = 'Switch to linear DCA Layers')
posCount = input.int (8, group = 'DCA Settings', title = 'Max Amount of DCA Layers')
increment = input.float (2, group = 'DCA Settings', title = 'Base % to calculate DCA layers', step=0.5, minval=1.1)
bar_lookback = input.int (4999, group = 'DCA Settings', title = 'Lines Bar Lookback', maxval = 4999)
plotMA = input.bool (false, group = 'Moving Average', title = 'Plot Moving Average')
moving_average = input.int (100, group = 'Moving Average', title = 'MA Length' )
rsiLengthInput = input.int (14, group = 'RSI Settings', title = "RSI Length", minval=1)
rsiSourceInput = input.source (close, group = 'RSI Settings', title = 'Source')
overSold = input.int (29, group = 'RSI Settings', title = 'Oversold, Trigger to Enter First Position')
// variables //
var open_position = true // true when there are open positions
var entry_price = 0.0 // the entry price of the first entry
var dca_price = 0.0 // the price of the different dca layers
var int count = 0 // bar counter since first open position
var int max_bar = 0 // max bar buffer variable for DCA lines, stop lines, average price
var line dca_line = na // lines variable for creating dca lines
// arrays //
linesArray = array.new_float(posCount,na) // array to store different dca price levels for creating the dca lines
// Create max bar buffer for DCA lines, Stop and average price lines ///
max_bar := count >= bar_lookback ? bar_lookback : count
// Order size based on first entry and amount of DCA layers
q = (strategy.equity / posCount + 1) / open
// Calculate Moving Averages
movingaverage_signal = ta.sma(close ,moving_average)
plot (plotMA ? movingaverage_signal : na, color = color.new(#f5ff35, 0))
// RSI calculations //
up = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)
down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
// Buy Signal (co)
co = ta.crossover(rsi, overSold) and close < movingaverage_signal
// Create a white line for average price, since the last opened position //
average_price = line.new(x1 = bar_index - max_bar, y1 = strategy.position_avg_price, x2 = bar_index, y2 = strategy.position_avg_price, color = color.white)
// Stop //
// Create a red Stop level line based on a specified % above the average price //
stop_level = strategy.position_avg_price + (strategy.position_avg_price / 100 * takeProfitAll)
stop_line = line.new(x1 = bar_index - max_bar, y1 = stop_level, x2 = bar_index, y2 = stop_level, color = color.red)
// Take profit definition per open position //
take_profit_price = close * takeProfit / 100 / syminfo.mintick
// Make sure the Stop level and average price level don't excied the bar buffer to avoid errors //
if count <= bar_lookback
line.set_x1(stop_line, strategy.opentrades.entry_bar_index(strategy.opentrades - 1))
line.set_x1(average_price, strategy.opentrades.entry_bar_index(strategy.opentrades - 1))
// Exponential DCA Layer Calculation fucntion --> New caclulation, the base number is calculated based the range between the entry_price and 0 and the amount of DCA layers //
dca_exponent_level(index) =>
base_number = math.pow(entry_price, (1 / posCount))
dca_level_calc = (entry_price - (math.pow(base_number,index))) * (1 - ((math.pow(1 + (increment / 100),index)) - 1))
// Linear DCA Layer Calculation // Added option to switch
dca_linear_level(index) =>
entry_price - ((entry_price / posCount) * index)
// Set Entries //
// Open the first entry and set the entry price //
if co and strategy.position_size == 0 and window()
open_position := true
entry_price := close
strategy.entry(id = 'FE1', direction = strategy.long, qty = q)
first_entry_line = line.new(x1 = bar_index - max_bar, y1 = entry_price, x2 = bar_index, y2 = entry_price, color = color.blue)
// Start bar counting since the position is open //
if open_position == true
count := count + 1
// Set the DCA entries //
// Prices below 1 are not set to avoid negative prices //
if strategy.position_size > 0 and window()
for i = 0 to strategy.opentrades
dca_level_mode = linear_mode ? dca_linear_level(i) : dca_exponent_level(i)
if strategy.opentrades == i and i < posCount
dca_price := dca_level_mode
entry_id = 'DCA' + str.tostring(i + 1)
strategy.entry(id = entry_id, direction = strategy.long, limit = dca_price, qty = q)
// Store the values of the different dca price levels in an array and create the dca lines //
// Prices below 1 are not stored//
if open_position==true and window()
for i = 1 to posCount -1
dca_level_mode = linear_mode ? dca_linear_level(i) : dca_exponent_level(i)
array.push(linesArray, dca_level_mode)
for i = 1 to array.size(linesArray) - 1
dca_line := line.new(x1 = bar_index - max_bar, y1 = array.get(linesArray, i), x2 = bar_index, y2 = array.get(linesArray, i),color = color.blue)
// Create thick line to show the last Entry price //
last_entry_price = line.new(x1 = bar_index[5], y1 = strategy.opentrades.entry_price(strategy.opentrades - 1), x2 = bar_index, y2 = strategy.opentrades.entry_price(strategy.opentrades - 1),color = color.rgb(255, 0, 204), width = 5)
// Exit the first entry when the take profit triggered //
if strategy.opentrades > 0 and window()
strategy.exit(id = 'Exit FE', from_entry = 'FE1', profit = take_profit_price)
// Exit DCA entries when take profit is triggered //
if strategy.opentrades > 0 and window()
for i = 1 to strategy.opentrades
exit_from = 'DCA' + str.tostring(i + 1)
exit_id = 'Exit_' + str.tostring(i + 1)
strategy.exit(id = exit_id, from_entry = exit_from, profit = take_profit_price)
// Close all positions at once when Stop is crossed //
if strategy.opentrades > 0 and ta.crossover(close,stop_level) and window()
strategy.close_all()
// Make sure nothing is open after alle positions are closed and set the condiftion back to be open for new entries //
if strategy.position_size[1] > 0 and strategy.position_size == 0
strategy.cancel_all()
strategy.close_all()
line.delete(average_price)
line.delete(stop_line)
line.delete(dca_line)
open_position := false // All position are closed, so back to false
count := 0 // Reset bar counter
|
Athena Momentum Squeeze - Short, Lean, and Mean | https://www.tradingview.com/script/Oy4huVQ2-Athena-Momentum-Squeeze-Short-Lean-and-Mean/ | jrandolph1046 | https://www.tradingview.com/u/jrandolph1046/ | 103 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © vitruvius
//@version=5
strategy("Athena Momentum Squeeze - Autoview", overlay=true)
// Inputs {
// -- Automate
broker = input.string("tradovate","Broker",group="AutoView",tooltip = "tradovate/tradovatesim")
pair0 = input.string("MSFT","Pair:",group="AutoView",tooltip = "ZNH2/MSFT/ESH2")
qty = input.string("1","Qty:",group="AutoView",tooltip = "q=10% (% of accountsize) \n q=50(Qty)")
lo_mess = "e="+str.tostring(broker) +" s="+str.tostring(pair0) +" b=long" +" q="+str.tostring(qty) + " t=market delay=1"
sh_mess = "e="+str.tostring(broker) +" s="+str.tostring(pair0) +" b=short" +" q="+str.tostring(qty) + " t=market delay=1"
exl_mess = "e="+str.tostring(broker) +" s="+str.tostring(pair0) +"b=long c=position t=market"
exs_mess = "e="+str.tostring(broker) +" s="+str.tostring(pair0) +"b=short c=position t=market"
// Entry {
entry_gr_name = "Entry"
entry_tt_sqz_filter = "Checks number of dark blue dots before entering a position"
entry_long_light_green = "Light green", entry_long_dark_green = "Dark green", entry_long_none = "None"
entry_short_light_red = "Light red", entry_short_dark_red = "Dark red", entry_short_none = "None"
in_entry_sqz_bar_type_long = input.string(entry_long_light_green, "Long entry", [entry_long_light_green, entry_long_dark_green, entry_long_none], group=entry_gr_name)
in_entry_sqz_bar_type_short = input.string(entry_short_light_red, "Short entry", [entry_short_light_red, entry_short_dark_red, entry_short_none], group=entry_gr_name)
in_entry_sqz_filter_en = input.bool(true, "Enable squeeze filter?", tooltip=entry_tt_sqz_filter, group=entry_gr_name)
in_entry_sqz_filter_cnt = input.int(6, "Squeeze dot count", group=entry_gr_name)
//}
// Exit {
exit_gr_name = "Exit"
exit_long_light_green = "Light green", exit_long_dark_green = "Dark green", exit_long_light_red = "Light red", exit_long_dark_red = "Dark red", exit_long_none = "None"
exit_short_light_green = "Light green", exit_short_dark_green = "Dark green", exit_short_light_red = "Light red", exit_short_dark_red = "Dark red", exit_short_none = "None"
exit_type_per_tp = "Percentage", exit_type_atr_tp = "ATR", exit_type_rr_tp = "Risk/Reward", exit_type_none_tp = "None"
exit_type_per_sl = "Percentage", exit_type_atr_sl = "ATR", exit_type_none_sl = "None"
exit_tt_val_tp = "Percantage: Percentage value\nATR: ATR multiplier\nRisk/Reward: R:R ratio"
exit_tt_val_sl = "Percantage: Percentage value\nATR: ATR multiplier"
in_exit_sqz_bar_type_long = input.string(exit_long_dark_green, "Long close", [exit_long_light_green, exit_long_dark_green, exit_long_light_red, exit_long_dark_red, exit_long_none], group=exit_gr_name)
in_exit_sqz_bar_type_short = input.string(exit_short_dark_red, "Short close", [exit_short_light_green, exit_short_dark_green, exit_short_light_red, exit_short_dark_red, exit_short_none], group=exit_gr_name)
in_exit_sqz_bar_close_in_profit = input.bool(false, "Close only in profit", group=exit_gr_name)
in_exit_type_tp = input.string(exit_type_none_tp, "Take profit type", [exit_type_per_tp, exit_type_atr_tp, exit_type_rr_tp, exit_type_none_tp], group=exit_gr_name)
in_exit_val_tp = input.float(2.0, "Take profit value", step=0.1, tooltip=exit_tt_val_tp, group=exit_gr_name)
in_exit_type_sl = input.string(exit_type_atr_sl, "Stop loss type", [exit_type_per_sl, exit_type_atr_sl, exit_type_none_sl], group=exit_gr_name)
in_exit_val_sl = input.float(2.0, "Stop loss value", step=0.1, tooltip=exit_tt_val_sl, group=exit_gr_name)
in_exit_atr_len = input.int(14, "ATR length", group=exit_gr_name)
//}
// Squeeze Momentum {
sqz_gr_name = "Squeeze Momentum"
in_sqz_length = input(20, title='BB Length', group=sqz_gr_name)
in_sqz_mult = input(2.0, title='BB MultFactor', group=sqz_gr_name)
in_sqz_lengthKC = input(20, title='KC Length', group=sqz_gr_name)
in_sqz_multKC = input(1.5, title='KC MultFactor', group=sqz_gr_name)
in_sqz_useTrueRange = input(true, title='Use TrueRange (KC)', group=sqz_gr_name)
//}
// Moving Average {
ma_gr_name = "Moving Average"
ma_type_rma = "RMA", ma_type_sma = "SMA", ma_type_ema = "EMA", ma_type_wma = "WMA", ma_type_hma = "HMA", ma_type_vwma = "VWMA", ma_type_dema = "DEMA", ma_type_tema = "TEMA"
in_ma_en = input.bool(true, "Enable moving average filter?", group=ma_gr_name)
in_ma_type = input.string(ma_type_sma, "Type", [ma_type_rma, ma_type_sma, ma_type_ema, ma_type_dema, ma_type_tema, ma_type_wma, ma_type_hma, ma_type_vwma], group=ma_gr_name)
in_ma_src = input.source(close, "Source", group=ma_gr_name)
in_ma_len = input.int(200, "Length", group=ma_gr_name)
in_ma_show = input.bool(true, "Plot?", inline="ma_plot", group=ma_gr_name)
in_ma_col = input.color(color.yellow, "", inline="ma_plot", group=ma_gr_name)
in_ma_w = input.int(2, "", inline="ma_plot", group=ma_gr_name)
//}
// Display {
disp_gr_name = "Display"
in_disp_ep_col = input.color(color.gray, "Entry Price", group=disp_gr_name)
in_disp_tp_col = input.color(color.green, "Take Profit", group=disp_gr_name)
in_disp_sl_col = input.color(color.red, "Stop Loss", group=disp_gr_name)
//}
//}
// Variables {
// Entry {
entry_long_sel_light_green = (in_entry_sqz_bar_type_long == entry_long_light_green)
entry_long_sel_dark_green = (in_entry_sqz_bar_type_long == entry_long_dark_green)
entry_short_sel_light_red = (in_entry_sqz_bar_type_short == entry_short_light_red)
entry_short_sel_dark_red = (in_entry_sqz_bar_type_short == entry_short_dark_red)
//}
// Exit {
exit_long_sel_light_green = (in_exit_sqz_bar_type_long == exit_long_light_green)
exit_long_sel_dark_green = (in_exit_sqz_bar_type_long == exit_long_dark_green)
exit_long_sel_light_red = (in_exit_sqz_bar_type_long == exit_long_light_red)
exit_long_sel_dark_red = (in_exit_sqz_bar_type_long == exit_long_dark_red)
exit_short_sel_light_green = (in_exit_sqz_bar_type_short == exit_short_light_green)
exit_short_sel_dark_green = (in_exit_sqz_bar_type_short == exit_short_dark_green)
exit_short_sel_light_red = (in_exit_sqz_bar_type_short == exit_short_light_red)
exit_short_sel_dark_red = (in_exit_sqz_bar_type_short == exit_short_dark_red)
//}
// Strategy {
strat_is_long = strategy.position_size > 0
strat_is_short = strategy.position_size < 0
strat_is_new_pos = (strategy.position_size[1] == 0 and strategy.position_size != 0) or ((strategy.position_size[1] * strategy.position_size) < 0)
//}
//}
// Functions {
// Moving Average {
f_ma(type, src, len) =>
switch type
ma_type_rma => ta.rma(src, len)
ma_type_sma => ta.sma(src, len)
ma_type_ema => ta.ema(src, len)
ma_type_dema =>
e1 = ta.ema(src, len)
e2 = ta.ema(e1, len)
dema = 2 * e1 - e2
ma_type_tema =>
ema1 = ta.ema(src, len)
ema2 = ta.ema(ema1, len)
ema3 = ta.ema(ema2, len)
out = 3 * (ema1 - ema2) + ema3
ma_type_wma => ta.wma(src, len)
ma_type_hma => ta.hma(src, len)
ma_type_vwma => ta.vwma(src, len)
=> ta.ema(src, len)
//}
//}
// Indicator {
// Squeeze Momentum {
var sqz_dark_blue_dot_cnt = 0
// Calculate BB
sqz_source = close
sqz_basis = ta.sma(sqz_source, in_sqz_length)
sqz_dev = in_sqz_multKC * ta.stdev(sqz_source, in_sqz_length)
sqz_upperBB = sqz_basis + sqz_dev
sqz_lowerBB = sqz_basis - sqz_dev
// Calculate KC
sqz_ma = ta.sma(sqz_source, in_sqz_lengthKC)
sqz_range_1 = in_sqz_useTrueRange ? ta.tr : high - low
sqz_rangema = ta.sma(sqz_range_1, in_sqz_lengthKC)
sqz_upperKC = sqz_ma + sqz_rangema * in_sqz_multKC
sqz_lowerKC = sqz_ma - sqz_rangema * in_sqz_multKC
sqz_sqzOn = sqz_lowerBB > sqz_lowerKC and sqz_upperBB < sqz_upperKC
sqz_sqzOff = sqz_lowerBB < sqz_lowerKC and sqz_upperBB > sqz_upperKC
sqz_noSqz = sqz_sqzOn == false and sqz_sqzOff == false
sqz_val = ta.linreg(sqz_source - math.avg(math.avg(ta.highest(high, in_sqz_lengthKC), ta.lowest(low, in_sqz_lengthKC)), ta.sma(close, in_sqz_lengthKC)), in_sqz_lengthKC, 0)
sqz_bar_light_green = (sqz_val > 0) and (sqz_val > nz(sqz_val[1]))
sqz_bar_dark_green = (sqz_val > 0) and not (sqz_val > nz(sqz_val[1]))
sqz_bar_light_red = not (sqz_val > 0) and (sqz_val < nz(sqz_val[1]))
sqz_bar_dark_red = not (sqz_val > 0) and not (sqz_val < nz(sqz_val[1]))
sqz_circle_dark_blue = sqz_noSqz or (not sqz_noSqz and sqz_sqzOn)
sqz_circle_light_blue = (not sqz_noSqz and not sqz_sqzOn)
sqz_bar_cond_long = entry_long_sel_light_green ? sqz_bar_light_green : entry_long_sel_dark_green ? sqz_bar_dark_green : false
sqz_bar_cond_short = entry_short_sel_light_red ? sqz_bar_light_red : entry_short_sel_dark_red ? sqz_bar_dark_red : false
sqz_bar_cond_long := sqz_bar_cond_long and sqz_circle_light_blue
sqz_bar_cond_short := sqz_bar_cond_short and sqz_circle_light_blue
sqz_close_cond_long = exit_long_sel_light_green ? sqz_bar_light_green : exit_long_sel_dark_green ? sqz_bar_dark_green : exit_long_sel_light_red ? sqz_bar_light_red : exit_long_sel_dark_red ? sqz_bar_dark_red : false
sqz_close_cond_short = exit_short_sel_light_green ? sqz_bar_light_green : exit_short_sel_dark_green ? sqz_bar_dark_green : exit_short_sel_light_red ? sqz_bar_light_red : exit_short_sel_dark_red ? sqz_bar_dark_red : false
sqz_dark_blue_dot_cnt := sqz_circle_dark_blue ? sqz_dark_blue_dot_cnt + 1 : 0
sqz_filter_cnt_cond = in_entry_sqz_filter_en ? (sqz_dark_blue_dot_cnt[1] >= in_entry_sqz_filter_cnt) : true
plotchar(sqz_dark_blue_dot_cnt, "Dark blue dot count", "", color=color.blue)
//}
// Moving Average {
ma_val = f_ma(in_ma_type, in_ma_src, in_ma_len)
ma_cond_long = in_ma_en ? (close > ma_val) : true
ma_cond_short = in_ma_en ? (close < ma_val) : true
plot(in_ma_en and in_ma_show ? ma_val : na, "Moving Average", in_ma_col, in_ma_w)
//}
// ATR {
var float atr_at_entry = na
atr_val = ta.atr(in_exit_atr_len)
atr_at_entry := strat_is_new_pos ? atr_val[1] : atr_at_entry
//}
// Strategy {
strat_long_cond = sqz_bar_cond_long and sqz_filter_cnt_cond and ma_cond_long
strat_short_cond = sqz_bar_cond_short and sqz_filter_cnt_cond and ma_cond_short
if (strat_long_cond)
strategy.entry("Long", strategy.long,alert_message = lo_mess)
if (strat_short_cond)
strategy.entry("Short", strategy.short,alert_message = sh_mess)
strat_profit_cond_close = in_exit_sqz_bar_close_in_profit ? (strategy.openprofit > 0) : true
if (strat_is_long and sqz_close_cond_long and strat_profit_cond_close)
strategy.close("Long",alert_message = exl_mess)
if (strat_is_short and sqz_close_cond_short and strat_profit_cond_close)
strategy.close("Short",alert_message = exs_mess)
strat_entry_price = strategy.opentrades.entry_price(strategy.opentrades - 1)
// Stop Loss {
var float strat_sl_price_long = na
var float strat_sl_price_short = na
strat_sl_price_long := if (strat_is_new_pos)
switch in_exit_type_sl
exit_type_per_sl => strategy.position_avg_price * (1 - (in_exit_val_sl * 0.01))
exit_type_atr_sl => strat_entry_price - (in_exit_val_sl * atr_val)
=> na
else
strat_sl_price_long
strat_sl_price_short := if (strat_is_new_pos)
switch in_exit_type_sl
exit_type_per_sl => strategy.position_avg_price * (1 + (in_exit_val_sl * 0.01))
exit_type_atr_sl => strat_entry_price + (in_exit_val_sl * atr_val)
=> na
else
strat_sl_price_short
float strat_sl_price = strat_is_long ? strat_sl_price_long : strat_is_short ? strat_sl_price_short : na
strat_sl_diff = math.abs(strat_entry_price - strat_sl_price)
//}
// Take Profit {
var float strat_tp_price_long = na
var float strat_tp_price_short = na
strat_tp_price_long := if (strat_is_new_pos)
switch in_exit_type_tp
exit_type_per_tp => strategy.position_avg_price * (1 + (in_exit_val_tp * 0.01))
exit_type_atr_tp => strat_entry_price + (in_exit_val_tp * atr_val)
exit_type_rr_tp => strat_entry_price + (in_exit_val_tp * strat_sl_diff)
=> na
else
strat_tp_price_long
strat_tp_price_short := if (strat_is_new_pos)
switch in_exit_type_tp
exit_type_per_tp => strategy.position_avg_price * (1 - (in_exit_val_tp * 0.01))
exit_type_atr_tp => strat_entry_price - (in_exit_val_tp * atr_val)
exit_type_rr_tp => strat_entry_price - (in_exit_val_tp * strat_sl_diff)
=> na
else
strat_tp_price_short
float strat_tp_price = strat_is_long ? strat_tp_price_long : strat_is_short ? strat_tp_price_short : na
//}
if (strat_is_long)
strategy.exit("LE", "Long", stop=strat_sl_price, limit=strat_tp_price, comment_loss="L-SL", comment_profit="L-TP",alert_message = exl_mess)
if (strat_is_short)
strategy.exit("SE", "Short", stop=strat_sl_price, limit=strat_tp_price, comment_loss="S-SL", comment_profit="S-TP",alert_message = exs_mess)
//}
// Display {
p_ep = plot(strat_entry_price, "Entry Price", in_disp_ep_col, 1, plot.style_circles)
p_tp = plot(strat_tp_price, "Take Profit", in_disp_tp_col, 1, plot.style_circles)
p_sl = plot(strat_sl_price, "Stop Loss", in_disp_sl_col, 1, plot.style_circles)
fill(p_ep, p_tp, color.new(in_disp_tp_col, 85), title="Take Profit Fill")
fill(p_ep, p_sl, color.new(in_disp_sl_col, 85), title="Stop Loss Fill")
//}
//} |
Ichimoku Cloud and ADX with Trailing Stop Loss (by Coinrule) | https://www.tradingview.com/script/FjRrmO4K-Ichimoku-Cloud-and-ADX-with-Trailing-Stop-Loss-by-Coinrule/ | Coinrule | https://www.tradingview.com/u/Coinrule/ | 229 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Coinrule
//@version=5
strategy('Ichimoku Cloud with ADX with Trailing Stop Loss',
overlay=true,
initial_capital=1000,
process_orders_on_close=true,
default_qty_type=strategy.percent_of_equity,
default_qty_value=100,
commission_type=strategy.commission.percent,
commission_value=0.1)
showDate = input(defval=true, title='Show Date Range')
timePeriod = time >= timestamp(syminfo.timezone, 2022, 1, 1, 0, 0)
// Inputs
ts_bars = input.int(9, minval=1, title='Tenkan-Sen Bars')
ks_bars = input.int(26, minval=1, title='Kijun-Sen Bars')
ssb_bars = input.int(52, minval=1, title='Senkou-Span B Bars')
cs_offset = input.int(26, minval=1, title='Chikou-Span Offset')
ss_offset = input.int(26, minval=1, title='Senkou-Span Offset')
long_entry = input(true, title='Long Entry')
short_entry = input(true, title='Short Entry')
middle(len) => math.avg(ta.lowest(len), ta.highest(len))
// Ichimoku Components
tenkan = middle(ts_bars)
kijun = middle(ks_bars)
senkouA = math.avg(tenkan, kijun)
senkouB = middle(ssb_bars)
// Plot Ichimoku Kinko Hyo
plot(tenkan, color=color.new(#0496ff, 0), title='Tenkan-Sen')
plot(kijun, color=color.new(#991515, 0), title='Kijun-Sen')
plot(close, offset=-cs_offset + 1, color=color.new(#459915, 0), title='Chikou-Span')
sa = plot(senkouA, offset=ss_offset - 1, color=color.new(color.green, 0), title='Senkou-Span A')
sb = plot(senkouB, offset=ss_offset - 1, color=color.new(color.red, 0), title='Senkou-Span B')
fill(sa, sb, color=senkouA > senkouB ? color.green : color.red, title='Cloud color', transp=90)
ss_high = math.max(senkouA[ss_offset - 1], senkouB[ss_offset - 1])
ss_low = math.min(senkouA[ss_offset - 1], senkouB[ss_offset - 1])
// ADX
[pos_dm, neg_dm, avg_dm] = ta.dmi(14, 14)
// Entry/Exit Signals
tk_cross_bull = tenkan > kijun
tk_cross_bear = tenkan < kijun
cs_cross_bull = ta.mom(close, cs_offset - 1) > 0
cs_cross_bear = ta.mom(close, cs_offset - 1) < 0
price_above_kumo = close > ss_high
price_below_kumo = close < ss_low
bullish = tk_cross_bull and cs_cross_bull and price_above_kumo and avg_dm < 45 and pos_dm > neg_dm
bearish = tk_cross_bear and cs_cross_bear and price_below_kumo and avg_dm > 45 and pos_dm < neg_dm
// Configure trail stop level with input options
longTrailPerc = input.float(title='Trail Long Loss (%)', minval=0.0, step=0.1, defval=3) * 0.01
shortTrailPerc = input.float(title='Trail Short Loss (%)', minval=0.0, step=0.1, defval=3) * 0.01
// Determine trail stop loss prices
longStopPrice = 0.0
shortStopPrice = 0.0
longStopPrice := if strategy.position_size > 0
stopValue = close * (1 - longTrailPerc)
math.max(stopValue, longStopPrice[1])
else
0
shortStopPrice := if strategy.position_size < 0
stopValue = close * (1 + shortTrailPerc)
math.min(stopValue, shortStopPrice[1])
else
999999
strategy.entry('Long', strategy.long, when=bullish and long_entry and timePeriod)
strategy.exit('Long', stop = longStopPrice, limit = shortStopPrice)
//strategy.entry('Short', strategy.short, when=bearish and short_entry and timePeriod)
//strategy.exit('Short', stop = longStopPrice, limit = shortStopPrice)
|
Bull Trend Filtered StochRSI (BTFS) | https://www.tradingview.com/script/TpuQxPsx-Bull-Trend-Filtered-StochRSI-BTFS/ | SnarkyPuppy | https://www.tradingview.com/u/SnarkyPuppy/ | 69 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SnarkyPuppy
//@version=5
strategy("Filtered Stoch", overlay=false, default_qty_value = 100, default_qty_type=strategy.percent_of_equity)
/////high filter...upper donchian channel of ema... or highest ema for a given amount of candles
filter_ema_len= input(6)
ema_donchian_len = input(30)
ema=ta.highest(ta.ema(high,filter_ema_len),ema_donchian_len)
////////////////////////basic stoch rsi with max val 100 and min val 0.. entry above lowerband preset 35
smoothK = input.int(7, "K", minval=1)
smoothD = input.int(4, "D", minval=1)
lengthRSI = input.int(14, "RSI Length", minval=1)
lengthStoch = input.int(14, "Stochastic Length", minval=1)
src = input(close, title="RSI Source")
rsi1 = ta.rsi(src, lengthRSI)
k = math.min(100, math.max(0,ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)))
d = math.max(math.min(ta.sma(k, smoothD),80),35)
plot(k, "K", color=#2962FF)
plot(d, "D", color=#FF6D00)
h0 = hline(80, "Upper Band", color=#787B86)
hline(50, "Middle Band", color=color.new(#787B86, 50))
lowerband=input(35)
h11 = hline(lowerband, "Lower Band", color=#787B86)
fill(h0, h11, color=color.rgb(33, 150, 243, 90), title="Background")
ematrend= close>ema ? 1 : 0
bgcolor(ematrend==1?color.rgb(76, 175, 79, 80):na)
longCondition = k>lowerband and ematrend==1
if (longCondition)
strategy.entry("Up", strategy.long)
shortCondition = ta.crossunder(k,lowerband)
if (shortCondition)
strategy.close("Up", shortCondition)
|
PSAR BBPT ZLSMA BTC 1min | https://www.tradingview.com/script/o1YNgHYa-PSAR-BBPT-ZLSMA-BTC-1min/ | Rolan_Kruger | https://www.tradingview.com/u/Rolan_Kruger/ | 331 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Rolan_Kruger
//@version=5
strategy("PSAR BBPT ZLSMA","PBZ", overlay=true,default_qty_type = strategy.percent_of_equity, default_qty_value = 100)
///////////////////////////////////////////////////////////////////////////////////////////////////////
// PSAR BUY/SELL
start = input.float(title='Start', step=0.00005, defval=0.05, group = "PSAR")
increment = input.float(title='Increment', step=0.00005, defval=0.05, group = "PSAR")
maximum = input.float(title='Maximum', step=0.01, defval=0.13, group = "PSAR")
width = input.int(title='Point Width', minval=1, defval=20, group = "PSAR")
highlightStartPoints = input(title='Highlight Start Points ?', defval=false, group = "PSAR")
psar = ta.sar(start, increment, maximum)
dir = psar < close ? 1 : -1
psarColor = psar < close ? #3388bb : #fdcc02
plotshape(dir == 1 and dir[1] == -1 and highlightStartPoints ? psar : na, title='Buy', style=shape.labelup, location=location.absolute, size=size.normal, text='Buy', textcolor=color.new(color.white, 0), color=color.new(color.green, 0))
plotshape(dir == -1 and dir[1] == 1 and highlightStartPoints ? psar : na, title='Sell', style=shape.labeldown, location=location.absolute, size=size.normal, text='Sell', textcolor=color.new(color.white, 0), color=color.new(color.red, 0))
barcolor(dir == 1 ? color.green : color.red, display = display.none)
PSAR_Buy = dir == 1 and dir[1] == -1
PSAR_Sell = dir == -1 and dir[1] == 1
////////////////////////////////////////////////////////////////////////////////////////////////////////
// ZLSMA
length = input(title='Length', defval=50,group = "ZLSMA")
offset = input(title='Offset', defval=0,group = "ZLSMA")
src = input(close, title='Source',group = "ZLSMA")
lsma = ta.linreg(src, length, offset)
lsma2 = ta.linreg(lsma, length, offset)
eq = lsma - lsma2
zlsma = lsma + eq
plot(zlsma, color=color.new(color.yellow, 0), linewidth=3)
ZLSMA_Buy = close > zlsma and open > zlsma and low > zlsma and high > zlsma
ZLSMA_Sell = close < zlsma and open < zlsma and low < zlsma and high < zlsma
////////////////////////////////////////////////////////////////////////////////////////////////////////
// BBPT
//
switch_bbpt = input.bool(false, "Switch BBPT conditionals",group ="Bull Bear Power Trend")
length1 = 8
//
BullTrend_hist = 0.0
BearTrend_hist = 0.0
BullTrend = (close - ta.lowest(low, 50)) / ta.atr(5)
BearTrend = (ta.highest(high, 50) - close) / ta.atr(5)
BearTrend2 = -1 * BearTrend
Trend = BullTrend - BearTrend
if BullTrend < 2
BullTrend_hist := BullTrend - 2
BullTrend_hist
if BearTrend2 > -2
BearTrend_hist := BearTrend2 + 2
BearTrend_hist
//alexgrover-Regression Line Formula
x = bar_index
y = Trend
x_ = ta.sma(x, length1)
y_ = ta.sma(y, length1)
mx = ta.stdev(x, length1)
my = ta.stdev(y, length1)
c = ta.correlation(x, y, length1)
slope = c * (my / mx)
inter = y_ - slope * x_
reg_trend = x * slope + inter
//
BBPT_Buy = BearTrend_hist
BBPT_Sell = BullTrend_hist
if switch_bbpt
BBPT_Buy := BullTrend_hist
BBPT_Sell := BearTrend_hist
///////////////////////////////////////////////////////////////////////////////////////////////////////
// Sessions
enable_sessions = input.bool(false, "Enable Sessions for strategy", group = "Sessions")
bgColor = input.bool(false, "Activate High/Low View", group = "Sessions")
LondonColor = color.new(color.green, 90)
NYColor = color.new(color.red, 90)
AsiaColor = color.new(color.yellow, 90)
SydneyColor = color.new(color.blue, 90)
///Sessions
res = input.timeframe("D", "Resolution", ["D","W","M"], group = "Sessions")
london = input.session("0300-1200:1234567", "London Session", group = "Sessions")
ny = input.session("0800-1700:1234567", "New York Session", group = "Sessions")
tokyo = input.session("2000-0400:1234567", "Tokyo Session", group = "Sessions")
sydney = input.session("1700-0200:1234567", "Sydney Session", group = "Sessions")
//Bars
is_newbar(sess) =>
t = time(res, sess, "America/New_York")
na(t[1]) and not na(t) or t[1] < t
is_session(sess) =>
not na(time(timeframe.period, sess, "America/New_York"))
//London
London = input.bool(false, "London Session")
londonNewbar = is_newbar(london)
londonSession = is_session(london)
float londonLow = na
londonLow := if londonSession
if londonNewbar
low
else
math.min(londonLow[1],low)
else
londonLow
float londonHigh = na
londonHigh := if londonSession
if londonNewbar
high
else
math.max(londonHigh[1],high)
else
londonHigh
plotLL = plot(londonLow, color=color.new(#000000, 100))
plotLH = plot(londonHigh, color=color.new(#000000, 100))
fill(plotLL, plotLH, color = londonSession and London and bgColor ? LondonColor : na)
bgcolor(londonSession and London and not bgColor ? LondonColor : na)
//New York
NY = input.bool(false, "New York Session")
nyNewbar = is_newbar(ny)
nySession = is_session(ny)
float nyLow = na
nyLow := if nySession
if nyNewbar
low
else
math.min(nyLow[1],low)
else
nyLow
float nyHigh = na
nyHigh := if nySession
if nyNewbar
high
else
math.max(nyHigh[1],high)
else
nyHigh
plotNYL = plot(nyLow, color=color.new(#000000, 100))
plotNYH = plot(nyHigh, color=color.new(#000000, 100))
fill(plotNYL, plotNYH, color = nySession and NY and bgColor ? NYColor : na)
bgcolor(nySession and NY and not bgColor ? NYColor : na)
//Tokyo
Tokyo = input.bool(false, "Tokyo Session")
tokyoNewbar = is_newbar(tokyo)
tokyoSession = is_session(tokyo)
float tokyoLow = na
tokyoLow := if tokyoSession
if tokyoNewbar
low
else
math.min(tokyoLow[1],low)
else
tokyoLow
float tokyoHigh = na
tokyoHigh := if tokyoSession
if tokyoNewbar
high
else
math.max(tokyoHigh[1],high)
else
tokyoHigh
plotTL = plot(tokyoLow, color=color.new(#000000, 100))
plotTH = plot(tokyoHigh, color=color.new(#000000, 100))
fill(plotTL, plotTH, color = tokyoSession and Tokyo and bgColor ? AsiaColor : na)
bgcolor(tokyoSession and Tokyo and not bgColor ? AsiaColor : na)
//Sydney
Sydney = input.bool(false, "Sydney Session")
sydneyNewbar = is_newbar(sydney)
sydneySession = is_session(sydney)
float sydneyLow = na
sydneyLow := if sydneySession
if sydneyNewbar
low
else
math.min(sydneyLow[1],low)
else
sydneyLow
float sydneyHigh = na
sydneyHigh := if sydneySession
if sydneyNewbar
high
else
math.max(sydneyHigh[1],high)
else
sydneyHigh
plotSL = plot(sydneyLow, color=color.new(#000000, 100))
plotSH = plot(sydneyHigh, color=color.new(#000000, 100))
fill(plotSL, plotSH, color = sydneySession and Sydney and bgColor ? SydneyColor : na)
bgcolor(sydneySession and Sydney and not bgColor ? SydneyColor : na)
London_ok = London and londonSession
NY_ok = NY and nySession
Tokyo_ok = Tokyo and tokyoSession
Sydney_ok = Sydney and sydneySession
in_session = true
if London_ok or NY_ok or Tokyo_ok or Sydney_ok and enable_sessions
in_session := true
else if enable_sessions == true
in_session := false
///////////////////////////////////////////////////////////////////////////////////////////////////////
// EMA Filter
ema_filter = input.bool(false, "Enable EMA filter", group = "EMA")
ema_lenght = input.int(50, "EMA lenght", group = "EMA")
ema1 = ta.ema(close, ema_lenght)
plot(ema1, "EMA", color.white, 3)
EMA_Buy = true
EMA_Sell = true
if ema_filter == true
EMA_Buy := close > ema1
EMA_Sell := ema1 > close
///////////////////////////////////////////////////////////////////////////////////////////////////////
// ZLSMA angle calc
zlsma_angle_filter = input.bool(true, "ZLSMA angle filter", group = "ZLSMA")
ZLSMA_Up = true
ZLSMA_Down = true
if zlsma_angle_filter == true
ZLSMA_Up := 1 < (zlsma - zlsma[1])
ZLSMA_Down := -1 > (zlsma - zlsma[1])
///////////////////////////////////////////////////////////////////////////////////////////////////////
// SL/TP
// Assumes quote currency is FIAT as with BTC/USDT pair
max_sl = input.float(0.2, "Max SL size in %", group = "SL/TP", minval = 0.1, tooltip = "Cancels trade if SL is too big" )
zlsma_offset = input.float(0.02, title="ZLSMA SL offset in %", group = "SL/TP",maxval = 1)
tp1_multi = input.float(1, title="TP 1 multiplier", group = "SL/TP")
tp2_multi = input.float(2, title="TP 2 multiplier", group = "SL/TP")
tp1_persentage = input.float(0.001, "Persentage of trade close on TP1", group ="SL/TP", maxval = 100, minval = 0.001)
// SL too big check
sl_check = ((math.abs(close - zlsma))/close * 100) + zlsma_offset
sl_ok = true
if sl_check > max_sl
sl_ok := false
// ZLSMA SL and TP
not_in_trade = strategy.position_size == 0
check_if_long = PSAR_Buy and ZLSMA_Buy and BBPT_Buy and EMA_Buy and ZLSMA_Up and sl_ok and in_session
check_if_short = PSAR_Sell and ZLSMA_Sell and BBPT_Sell and EMA_Sell and ZLSMA_Down and sl_ok and in_session
var float sl = 0.0
var float tp1 = 0.0
var float tp2 = 0.0
if check_if_long and not_in_trade
sl := ((close - zlsma)/close * 100) + zlsma_offset
tp1 := (((close - zlsma)/close * 100) + zlsma_offset)*tp1_multi
tp2 := (((close - zlsma)/close * 100) + zlsma_offset)*tp2_multi
if check_if_short and not_in_trade
sl := ((zlsma - close)/close * 100) + zlsma_offset
tp1 := (((zlsma - close)/close * 100) + zlsma_offset)*tp1_multi
tp2 := (((zlsma - close)/close * 100) + zlsma_offset)*tp2_multi
// FUNCTIONS
// Stochastic
f_stochastic() =>
stoch = ta.stoch(close, high, low, 14)
stoch_K = ta.sma(stoch, 3)
stoch_D = ta.sma(stoch_K, 3)
stRD = ta.crossunder(stoch_K, stoch_D)
stGD = ta.crossover(stoch_K, stoch_D)
[stoch_K, stoch_D, stRD, stGD]
// VARIABLES
[bbMiddle, bbUpper, bbLower] = ta.bb(close, 20, 2)
[stoch_K, stoch_D, stRD, stGD] = f_stochastic()
// ORDERS
// Active Orders
// Check if strategy has open positions
inLong = strategy.position_size > 0
inShort = strategy.position_size < 0
// Check if strategy reduced position size in last bar
longClose = strategy.position_size < strategy.position_size[1]
shortClose = strategy.position_size > strategy.position_size[1]
// Entry Conditions
// Enter long when during last candle these conditions are true:
// Candle high is greater than upper Bollinger Band
// Stochastic K line crosses under D line and is oversold
longCondition = PSAR_Buy and ZLSMA_Buy and BBPT_Buy and EMA_Buy and ZLSMA_Up and sl_ok and in_session
// Enter short when during last candle these conditions are true:
// Candle low is lower than lower Bollinger Band
// Stochastic K line crosses over D line and is overbought
shortCondition = PSAR_Sell and ZLSMA_Sell and BBPT_Sell and EMA_Sell and ZLSMA_Down and sl_ok and in_session
// Exit Conditions
// Calculate Take Profit
longTP1 = strategy.position_avg_price * ((100 + tp1)/100)
longTP2 = strategy.position_avg_price * ((100 + tp2)/100)
shortTP1 = strategy.position_avg_price * ((100 - tp1)/100)
shortTP2 = strategy.position_avg_price * ((100 - tp2)/100)
// Calculate Stop Loss
// Initialise variables
var float longSL = 0.0
var float shortSL = 0.0
// When not in position, set stop loss using close price which is the price used during backtesting
// When in a position, check to see if the position was reduced on the last bar
// If it was, set stop loss to position entry price. Otherwise, maintain last stop loss value
longSL := if inLong and ta.barssince(longClose) < ta.barssince(longCondition)
strategy.position_avg_price
else if inLong
longSL[1]
else
close * ((100 - sl)/100)
shortSL := if inShort and ta.barssince(shortClose) < ta.barssince(shortCondition)
strategy.position_avg_price
else if inShort
shortSL[1]
else
close * ((100 + sl)/100)
////////////////////////////////////////////////////////////////////////////////////////////////////////
// STRATEGY EXECUTION
// Manage positions
if not_in_trade and longCondition
strategy.entry("Long", strategy.long)
strategy.exit("TP1/SL", from_entry="Long", qty_percent=tp1_persentage, limit=longTP1, stop=longSL)
strategy.exit("TP2/SL", from_entry="Long", limit=longTP2, stop=longSL)
if not_in_trade and shortCondition
strategy.entry("Short", strategy.short)
strategy.exit("TP1/SL", from_entry="Short", qty_percent=tp1_persentage, limit=shortTP1, stop=shortSL)
strategy.exit("TP2/SL", from_entry="Short", limit=shortTP2, stop=shortSL)
|
Simple SuperTrend Strategy for BTCUSD 4H | https://www.tradingview.com/script/N0nYQBlh/ | StrategiesForEveryone | https://www.tradingview.com/u/StrategiesForEveryone/ | 337 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Developed by © StrategiesForEveryone
//@version=5
strategy("SuperTrend Strategy with Rsi filter for BTCUSD 4H", overlay=true, process_orders_on_close = true, initial_capital = 100, default_qty_type = strategy.cash, precision = 2, slippage = 0, commission_value = 0.03, backtest_fill_limits_assumption = 0)
// ------ Inputs for calculating position --------
initial_actual_capital = input.float(defval=100, title = "Enter initial/current capital", group = "Calculate position")
risk_c = input.float(2.5, '% account risk per trade', step=1, group = "Calculate position", tooltip = "Percentage of total account to risk per trade. The USD value that should be used to risk the inserted percentage of the account. Appears green in the upper left corner")
// ------ Date filter (obtained from ZenAndTheArtOfTrading) ---------
initial_date = input.time(title="Initial date", defval=timestamp("10 Feb 2014 13:30 +0000"), group="Time filter", tooltip="Enter the start date and time of the strategy")
final_date = input.time(title="Final date", defval=timestamp("01 Jan 2030 19:30 +0000"), group="Time filter", tooltip="Enter the end date and time of the strategy")
dateFilter(int st, int et) => time >= st and time <= et
colorDate = input.bool(defval=false, title="Date background", tooltip = "Add color to the period of time of the strategy tester")
bgcolor(colorDate and dateFilter(initial_date, final_date) ? color.new(color.blue, transp=90) : na)
// --------------- Rsi filter------------------
overbought = input.int(70, title='Over bought line rsi', minval=50, maxval=100, group = "Rsi", inline = "b")
oversold = input.int(30, title='Over sold line rsi', minval=0, maxval=50, group = "Rsi", inline = "b")
periods = input.int(6, title='Rsi Length', minval=1, maxval=200, group = "Rsi", inline = "b")
rsi_filter = ta.rsi(close, periods)
show_rsi = input.bool(defval = false, title = "Show Rsi ?", group = "Appearance")
plot(show_rsi ? rsi_filter : na, title = "Rsi", color = color.rgb(255, 255, 255), linewidth = 2, display = display.all - display.status_line)
hline(show_rsi ? overbought : na, color=color.rgb(0, 132, 255))
hline(show_rsi ? oversold : na, color=color.rgb(0, 132, 255))
// ------------ Super Trend ----------
atrPeriod = input(9, "ATR Length SuperTrend")
factor = input.float(2.5, "Factor SuperTrend", step = 0.05)
[supertrend, direction] = ta.supertrend(factor, atrPeriod)
show_supertrend = input.bool(defval = false, title="Show supertrend ?", group = "Appearance")
bodyMiddle = plot(show_supertrend ? ((open + close) / 2) : na, display=display.none)
upTrend = plot(show_supertrend and direction < 0 ? supertrend : na, "Up Trend", color = color.green, style=plot.style_linebr, display = display.all - display.status_line)
downTrend = plot(show_supertrend and direction > 0 ? supertrend : na, "Down Trend", color = color.red, style=plot.style_linebr, display = display.all - display.status_line)
fill(bodyMiddle, upTrend, color.new(color.green, 95), fillgaps=false, title = "Supertrend background")
fill(bodyMiddle, downTrend, color.new(color.red, 95), fillgaps=false, title = "Supertrend background")
up_trend_plot = direction < 0
down_trend_plot = direction > 0
// ---------- Atr stop loss (obtained from garethyeo)
long_rsi_plot = ta.crossover(rsi_filter, oversold) and up_trend_plot
short_rsi_plot = ta.crossunder(rsi_filter, overbought) and down_trend_plot
long_supertrend_plot=ta.crossover(close, supertrend)
short_supertrend_plot=ta.crossunder(close, supertrend)
source_atr = input(close, title='Source', group = "Atr stop loss", inline = "A")
length_atr = input.int(14, minval=1, title='Period', group = "Atr stop loss" , inline = "A")
multiplier = input.float(1.5, minval=0.1, step=0.1, title='Atr multiplier', group = "Atr stop loss", inline = "A", tooltip = "Defines the stop loss distance based on the Atr stop loss indicator")
shortStopLoss = source_atr + ta.atr(length_atr) * multiplier
longStopLoss = source_atr - ta.atr(length_atr) * multiplier
show_stoploss = input.bool(defval=true, title="Draw stop loss ?", group = "Appearance", tooltip = "Activate to display stop loss price. It appears as a white point on the chart")
// --------- Stop loss based in last swing high/low --------
high_bars = input.int(defval = 10, title = "Highest price bars: ", group = "Swing highs/lows stop losses")
low_bars = input.int(defval = 10, title = "Lowest price bars: ", group = "Swing highs/lows stop losses")
stop_high = ta.highest(high, high_bars)
stop_low = ta.lowest(low, low_bars)
// --------- Stop loss source selection ---------------
stoploss_type = input.string(defval = "Atr stop loss", title = "Stop loss source", group = "Risk management for trades", options = ["Atr stop loss","Swing high/low"], tooltip = "Change this for getting stop loss based in Atr stop loss indicator or last swing high/low")
if stoploss_type == "Atr stop loss"
shortStopLoss := source_atr + ta.atr(length_atr) * multiplier
longStopLoss := source_atr - ta.atr(length_atr) * multiplier
if stoploss_type == "Swing high/low"
shortStopLoss := stop_high
longStopLoss := stop_low
// Ploting stop losses
plot(show_stoploss and long_supertrend_plot or show_stoploss and long_rsi_plot ? longStopLoss : na, color=color.rgb(255, 255, 255), style = plot.style_circles, linewidth = 2, display = display.all - display.price_scale)
plot(show_stoploss and short_supertrend_plot or show_stoploss and short_rsi_plot ? shortStopLoss : na, color=color.rgb(255, 255, 255), style = plot.style_circles, linewidth = 2, display = display.all - display.price_scale)
// ------------- Money management --------------
strategy_contracts = strategy.equity / close
distance_sl_atr_long = -1 * (longStopLoss - close) / close
distance_sl_atr_short = (shortStopLoss - close) / close
risk = input.float(2.5, '% Account risk per trade for backtesting', step=1, group = "Risk management for trades", tooltip = "Percentage of total account to risk per trade")
long_amount = strategy_contracts * (risk / 100) / distance_sl_atr_long
short_amount = strategy_contracts * (risk / 100) / distance_sl_atr_short
// ---------- Risk management ---------------
risk_reward_breakeven_long= input.float(title="Risk/reward for breakeven long", defval=0.75, step=0.05, group = "Risk management for trades")
risk_reward_take_profit_long= input.float(title="Risk/reward for take profit long", defval=0.75, step=0.05, group = "Risk management for trades")
risk_reward_breakeven_short= input.float(title="Risk/reward for break even short", defval=0.75, step=0.05, group = "Risk management for trades")
risk_reward_take_profit_short= input.float(title="Risk/reward for take profit short", defval=0.75, step=0.05, group = "Risk management for trades")
tp_percent=input.float(title="% of trade for first take profit", defval=50, step=5, group = "Risk management for trades", tooltip = "Closing percentage of the current position when the first take profit is reached.")
// ------------ Trade conditions ---------------
use_rsi_filter = input.bool(defval=true, title="Use Re-entry filter ?", group = "Re-entry filter", tooltip = "Activate to use filter. This will help you to re enter in a trend move")
bought = strategy.position_size > 0
sold = strategy.position_size < 0
up_trend = direction < 0
down_trend = direction > 0
long_rsi_entry = ta.crossover(rsi_filter, oversold) and up_trend and strategy.openprofit[5]>=0
short_rsi_entry = ta.crossunder(rsi_filter, overbought) and down_trend and strategy.openprofit[5]>=0
long_supertrend=ta.crossover(close, supertrend)
short_supertrend=ta.crossunder(close, supertrend)
var float sl_long = na
var float sl_short = na
var float be_long = na
var float be_short = na
var float tp_long = na
var float tp_short = na
if not bought
be_long:=na
sl_long:=na
tp_long:=na
if not sold
be_short
sl_short:=na
tp_short
long_positions = input.bool(defval = true, title = "Long positions ?", group = "Positions management")
short_positions = input.bool(defval = true, title = "Short positions ?", group = "Positions management")
// ---------- Strategy -----------
// Long position
if not bought and long_supertrend and dateFilter(initial_date, final_date) and long_positions or not bought and long_rsi_entry and dateFilter(initial_date, final_date) and use_rsi_filter and long_positions
sl_long:=longStopLoss
long_stoploss_distance = close - longStopLoss
be_long := close + long_stoploss_distance * risk_reward_breakeven_long
tp_long:=close+(long_stoploss_distance*risk_reward_take_profit_long)
strategy.entry('L', strategy.long, long_amount, alert_message = "Long")
strategy.exit("Tp", "L", stop=sl_long, limit=tp_long, qty_percent=tp_percent)
strategy.exit('Exit', 'L', stop=sl_long)
if bought and high > be_long
sl_long := strategy.position_avg_price
strategy.exit("Tp", "L", stop=sl_long, limit=tp_long, qty_percent=tp_percent)
strategy.exit('Exit', 'L', stop=sl_long)
if bought and short_supertrend
strategy.close("L", comment="CL")
// Short position
if not sold and short_supertrend and dateFilter(initial_date, final_date) and short_positions or not sold and short_rsi_entry and dateFilter(initial_date, final_date) and use_rsi_filter and short_positions
sl_short:=shortStopLoss
short_stoploss_distance=shortStopLoss - close
be_short:=((short_stoploss_distance*risk_reward_breakeven_short)-close)*-1
tp_short:=((short_stoploss_distance*risk_reward_take_profit_short)-close)*-1
strategy.entry("S", strategy.short, short_amount, alert_message = "Short")
strategy.exit("Tp", "S", stop=sl_short, limit=tp_short, qty_percent=tp_percent)
strategy.exit("Exit", "S", stop=sl_short)
if sold and low < be_short
sl_short:=strategy.position_avg_price
strategy.exit("Tp", "S", stop=sl_short, limit=tp_short, qty_percent=tp_percent)
strategy.exit("Exit", "S", stop=sl_short)
if sold and long_supertrend
strategy.close("S", comment="CS")
// ---------- Draw positions and signals on chart (strategy as an indicator) -------------
if high>tp_long
tp_long:=na
if low<tp_short
tp_short:=na
if high>be_long
be_long:=na
if low<be_short
be_short:=na
show_position_on_chart = input.bool(defval=true, title="Draw position on chart ?", group = "Appearance", tooltip = "Activate to graphically display profit, stop loss and break even")
position_price = plot(show_position_on_chart? strategy.position_avg_price : na, style=plot.style_linebr, color = color.new(#ffffff, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)
sl_long_price = plot(show_position_on_chart and bought ? sl_long : na, style = plot.style_linebr, color = color.new(color.red, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)
sl_short_price = plot(show_position_on_chart and sold ? sl_short : na, style = plot.style_linebr, color = color.new(color.red, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)
tp_long_price = plot(strategy.position_size>0 and show_position_on_chart? tp_long : na, style = plot.style_linebr, color = color.new(#1fc9fd, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)
tp_short_price = plot(strategy.position_size<0 and show_position_on_chart? tp_short : na, style = plot.style_linebr, color = color.new(#1fc9fd, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)
breakeven_long = plot(strategy.position_size>0 and high<be_long and show_position_on_chart ? be_long : na , style = plot.style_linebr, color = color.new(#00ff40, 60), linewidth = 1, display = display.all - display.status_line - display.price_scale)
breakeven_short = plot(strategy.position_size<0 and low>be_short and show_position_on_chart ? be_short : na , style = plot.style_linebr, color = color.new(#00ff40, 60), linewidth = 1, display = display.all - display.status_line - display.price_scale)
show_break_even_on_chart = input.bool(defval=true, title="Draw first take profit/breakeven price on chart ?", group = "Appearance", tooltip = "Activate to display take profit and breakeven price. It appears as a green point in the chart")
long_stoploss_distance = close - longStopLoss
short_stoploss_distance=shortStopLoss - close
be_long_plot = close + long_stoploss_distance * risk_reward_breakeven_long
be_short_plot =((short_stoploss_distance*risk_reward_breakeven_short)-close)*-1
plot(show_break_even_on_chart and long_supertrend_plot or show_break_even_on_chart and long_rsi_plot ? be_long_plot : na, color=color.new(#1fc9fd, 10), style = plot.style_circles, linewidth = 2, display = display.all - display.price_scale)
plot(show_break_even_on_chart and short_supertrend_plot or show_break_even_on_chart and short_rsi_plot ? be_short_plot : na, color=color.new(#1fc9fd, 10), style = plot.style_circles, linewidth = 2, display = display.all - display.price_scale)
position_profit_long = plot(bought and show_position_on_chart and strategy.openprofit>0 ? close : na, style = plot.style_linebr, color = color.new(#4cd350, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)
position_profit_short = plot(sold and show_position_on_chart and strategy.openprofit>0 ? close : na, style = plot.style_linebr, color = color.new(#4cd350, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)
fill(plot1 = position_price, plot2 = position_profit_long, color = color.new(color.green,90))
fill(plot1 = position_price, plot2 = position_profit_short, color = color.new(color.green,90))
fill(plot1 = position_price, plot2 = sl_long_price, color = color.new(color.red,90))
fill(plot1 = position_price, plot2 = sl_short_price, color = color.new(color.red,90))
fill(plot1 = position_price, plot2 = tp_long_price, color = color.new(color.green,90))
fill(plot1 = position_price, plot2 = tp_short_price, color = color.new(color.green,90))
show_signals = input.bool(defval=true, title="Draw signals on chart ?", group = "Appearance", tooltip = "Activate to display long, close long, short and close short signals. Green triangle represents long and red triangle represents short")
plotshape(show_signals ? long_supertrend : na, style = shape.triangleup, location = location.belowbar, color = color.new(color.green,0), size = size.tiny, display = display.all - display.status_line - display.price_scale)
plotshape(show_signals ? short_supertrend : na, style = shape.triangledown, location = location.abovebar, color = color.new(color.red,0), size = size.tiny, display = display.all - display.status_line - display.price_scale)
plotshape(show_signals ? long_rsi_entry : na, style = shape.triangleup, location = location.belowbar, color = color.new(color.green,0), size = size.tiny, display = display.all - display.status_line - display.price_scale)
plotshape(show_signals ? short_supertrend : na, style = shape.triangledown, location = location.abovebar, color = color.new(color.red,0), size = size.tiny, display = display.all - display.status_line - display.price_scale)
// --------------- Position amount calculator -------------
leverage_x = input.float(defval = 10, title = "Leverage X", group = "Calculate position")
contracts_amount_c = initial_actual_capital / close
distance_sl_long_c = -1 * (longStopLoss - close) / close
distance_sl_short_c = (shortStopLoss - close) / close
long_amount_c = (close * (contracts_amount_c * (risk_c / 100) / distance_sl_long_c))/leverage_x
short_amount_c = (close * (contracts_amount_c * (risk_c / 100) / distance_sl_short_c))/leverage_x
plot(long_supertrend or long_rsi_entry ? long_amount_c : na, color = color.rgb(136, 255, 0), display = display.all - display.pane - display.price_scale)
plot(short_supertrend or short_rsi_entry ? short_amount_c : na, color = color.rgb(136, 255, 0), display = display.all - display.pane - display.price_scale)
|
Hull Kaufman SuperTrend Cloud (HKST Cloud) | https://www.tradingview.com/script/XHnsbKXg-Hull-Kaufman-SuperTrend-Cloud-HKST-Cloud/ | SnarkyPuppy | https://www.tradingview.com/u/SnarkyPuppy/ | 316 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SnarkyPuppy
//@version=5
strategy("HKST Cloud", overlay=true, default_qty_type= strategy.percent_of_equity, default_qty_value=100)
////////////////nAMA
Lengthkaufman = input(20)
xPrice = ohlc4
xvnoise = math.abs(xPrice - xPrice[1])
nfastend = 0.666
nslowend = 0.0645
nsignal = math.abs(xPrice - xPrice[Lengthkaufman])
nnoise = math.sum(xvnoise, Lengthkaufman)
nefratio = nnoise != 0? nsignal / nnoise : 0
nsmooth = math.pow(nefratio * (nfastend - nslowend) + nslowend, 2)
nAMA = float(0)
nAMA := nz(nAMA[1]) + nsmooth * (xPrice - nz(nAMA[1]))
//plot(nAMA,color=color.red)
///short=input(true)
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
////////hull moving average
hull_len=input(20)
hull= ta.hma(nAMA,hull_len)
///////atr trail
atr_factor=input(2)
atr_period=input(5)
[supertrend, direction] = ta.supertrend(atr_factor,atr_period)
/////////cloud
band1= math.max(supertrend,hull,nAMA)
band2= math.min(supertrend,hull,nAMA)
b1=plot(band1, "band1", color = color.rgb(76, 175, 79, 85), style=plot.style_linebr)
b2=plot(band2, "band2", color = color.rgb(255, 82, 82, 78), style=plot.style_linebr)
fill(b1,b2,color.rgb(12, 50, 186, 75))
longCondition = ta.crossover(high,band1) //or ta.crossover(low,band2)
if (longCondition)
strategy.entry("Up", strategy.long)
shortCondition = ta.crossunder(low,band2) or close<band2
if (shortCondition)
strategy.close("Up", shortCondition)
|
Super 8 - 30M BTC | https://www.tradingview.com/script/zFPZofwt/ | Good-Vibe | https://www.tradingview.com/u/Good-Vibe/ | 669 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Good-Vibe
//@version=5
// ———————————————————— Strategy Settings
strategy('Super 8 - 30M BTC',
// The overlay parameter is set to true, which means that the strategy will be plotted on top of the price chart
overlay = true,
// The default_qty_value parameter is set to 0, meaning that the position size will be calculated based on the available capital
default_qty_value = 0,
// The initial_capital parameter is set to 10000, which is the starting capital for the strategy
initial_capital = 10000,
// The pyramiding parameter is set to 0, because it will be controlled by the script
pyramiding = 0,
// The commission_value parameter is set to 0.04, which represents a 0.04% commission for each trade
commission_value = 0.05,
// The commission_type parameter is set to strategy.commission.percent, which means that the commission is a percentage of the trade value
commission_type = strategy.commission.percent,
// The process_orders_on_close parameter is set to true, which means that orders will be executed at the close of the bar
process_orders_on_close = true,
// The margin_long parameter is set to 100, which represents the margin requirement for long positions
margin_long = 100,
// The margin_short parameter is set to 100, which represents the margin requirement for short positions
margin_short = 100,
// The use_bar_magnifier parameter is set to false, which means that the chart will not use a bar magnifier
use_bar_magnifier = false)
// ———————————————————— Inputs
// ————— Source input
// Define the position to take (long, short, or both)
Position = input.string('Both', 'Long / Short', options = ['Long', 'Short', 'Both'], tooltip = "Choose the position to take (long, short, or both)")
// ————— EMA inputs
// Define the slow and fast EMA lengths
sEma_Length = input.int(775, 'Slow EMA Length', minval = 0, step = 25, group = 'EXPONENTIAL MOVING AVERAGE', tooltip = "Set the length of the slow EMA")
fEma_Length = input.int(125, 'Fast EMA Length', minval = 0, step = 25, group = 'EXPONENTIAL MOVING AVERAGE', tooltip = "Set the length of the fast EMA")
// ————— ADX inputs
// Define the ADX parameters
ADX_len = input.int(28, 'ADX Length', minval = 1, group = 'AVERAGE DIRECTIONAL INDEX', tooltip = "Set the length of the ADX")
ADX_smo = input.int(10, 'ADX Smoothing', minval = 1, group = 'AVERAGE DIRECTIONAL INDEX', tooltip = "Set the smoothing of the ADX")
th = input.float(23, 'ADX Threshold', minval = 0, step = 0.5, group = 'AVERAGE DIRECTIONAL INDEX', tooltip = "Set the threshold for the ADX")
// ————— SAR inputs
// Define the SAR parameters
Sst = input.float(0.08, 'SAR star', minval = 0.01, step = 0.01, group = 'PARABOLIC SAR', tooltip = "Set the starting value for the SAR")
Sinc = input.float(0.04, 'SAR inc', minval = 0.01, step = 0.01, group = 'PARABOLIC SAR', tooltip = "Set the increment value for the SAR")
Smax = input.float(0.4, 'SAR max', minval = 0.01, step = 0.01, group = 'PARABOLIC SAR', tooltip = "Set the maximum value for the SAR")
// ————— MOVING AVERAGE CONVERGENCE DIVERGENCE
// Define the MACD and the MAC-Z parameters
MACD_options = input.string('MAC-Z', 'MACD OPTION', options = ['MACD', 'MAC-Z'], group = 'MOVING AVERAGE CONVERGENCE DIVERGENCE', tooltip="Select the type of MACD to use. The MAC-Z is designed to reduce false signals compared to the standard MACD")
fastLength = input.int(24, 'MACD Fast MA Length', minval = 1, group = 'MOVING AVERAGE CONVERGENCE DIVERGENCE', tooltip = "Number of periods for the fast moving average.")
slowLength = input.int(54, 'MACD Slow MA Length', minval = 1, group = 'MOVING AVERAGE CONVERGENCE DIVERGENCE', tooltip = "Number of periods for the slow moving average.")
signalLength = input.int(14, 'MACD Signal Length', minval = 1, group = 'MOVING AVERAGE CONVERGENCE DIVERGENCE', tooltip = "Number of periods for the signal line.")
lengthz = input.int(14, 'Z-VWAP Length', minval = 1, group = 'MOVING AVERAGE CONVERGENCE DIVERGENCE', tooltip = "Number of periods for the Z-VWAP used in the MAC-Z calculation.")
lengthStdev = input.int(11, 'StDev Length', minval = 1, group = 'MOVING AVERAGE CONVERGENCE DIVERGENCE', tooltip = "Number of periods for the standard deviation used in the MAC-Z calculation.")
A = input.float(0.1, "MAC-Z constant A", minval = -2.0, maxval = 2.0, step = 0.1, group = 'MOVING AVERAGE CONVERGENCE DIVERGENCE', tooltip = "Constant A used in the MAC-Z calculation.")
B = input.float(1.0, "MAC-Z constant B", minval = -2.0, maxval = 2.0, step = 0.1, group = 'MOVING AVERAGE CONVERGENCE DIVERGENCE', tooltip = "Constant B used in the MAC-Z calculation.")
// ————— Volume inputs for entries condition and for calculate quantities later
// Define volume factor and simple moving average length for volume condition
volume_f = input.float(1.1, 'Volume Factor', minval = 0, step = 0.1, group = 'VOLUME CONDITION', tooltip = "Factor used to determine the minimum required volume for an entry.")
sma_Length = input.int(89, 'SMA Volume Length', minval = 1, group = 'VOLUME CONDITION', tooltip = "Number of periods for the simple moving average used in the volume condition.")
// ————— Bollinger Bands inputs
// Define inputs for Bollinger Bands
BB_Length = input.int(40, 'BB Length', minval = 1, group = 'BOLLINGER BANDS', tooltip = "Length of the Bollinger Bands period")
BB_mult = input.float(2.0, 'BB Multiplier', minval = 0.1, step = 0.1, group = 'BOLLINGER BANDS', tooltip = "Multiplier for the Bollinger Bands width")
bbMinWidth01 = input.float(5.0, 'Min. BB Width % (New Position)', minval = 0, step = 0.5, group = 'BOLLINGER BANDS', tooltip = "Minimum width of the Bollinger Bands to enter a new position")
bbMinWidth02 = input.float(2.0, 'Min. BB Width % (Pyramiding)', minval = 0, step = 0.5, group = 'BOLLINGER BANDS', tooltip = "Minimum width of the Bollinger Bands to add to an existing position")
// ————— Take Profit / Trailing Stop input
// Define take profit/trailing stop options and parameters
TP_options = input.string('Both', 'Take Profit Option', options = ['Normal', 'Donchian', 'Both'], group = 'TAKE PROFIT / TRAILING STOP', tooltip = "Option for the take profit / trailing stop")
tp = input.float(1.8, 'Take Profit %', minval = 0, step = 0.1, group = 'TAKE PROFIT / TRAILING STOP', tooltip = "Percentage profit target")
trailOffset = input.float(0.3, 'Trail offset %', minval = 0, step = 0.1, group = 'TAKE PROFIT / TRAILING STOP', tooltip = "The offset percentage used for the trailing stop. If set to 0, only the Take Profit option will be used. If set to a value greater than 0, the Trailing Stop option will be used and the use_bar_magnifier parameter must also be set to true for more realistic results.")
// ————— TP Donchian Channel Input
// Define Donchian Channel period for take profit option
DClength = input.int(52, title='Donchian Channel Period', minval = 1, group='TAKE PROFIT / TRAILING STOP', tooltip = 'Defines the period of the Donchian Channel used for the take profit option.')
// ————— Stop Loss input
// Define stop loss options and parameters
SL_options = input.string('Both', 'Stop Loss Option', options = ['Normal', 'ATR', 'Both'], group = 'STOP LOSS', tooltip = 'Select the type of stop loss option you want to use.')
sl = input.float(9.0, 'Stop Loss %', minval = 0, step = 0.5, group = 'STOP LOSS', tooltip = 'Defines the percentage value of the stop loss.')
// ————— SL ATR Inputs
// Define ATR period and multiplier for ATR stop loss option
atrPeriodSl = input.int(14, title='ATR Period', minval = 0, group='STOP LOSS', tooltip = 'Defines the period of the Average True Range used in the ATR stop loss option.')
multiplierPeriodSl = input.float(13.5, 'ATR Multiplier', minval = 0, step = 0.5, group = 'STOP LOSS', tooltip = 'Defines the multiplier used in the ATR stop loss option.')
// ————— Risk input
// Define maximum risk percentage
Risk = input.float(5, 'Max. Risk %', tooltip = "Set the maximum percentage of account balance you're willing to risk per position", minval = 0, maxval = 100, group = 'RISK')
// ————— Pyramiding
// Define pyramiding options and parameters
Pyr = input.int(3, 'Max. Pyramiding', tooltip = "Set the maximum number of trades you are willing to open within a position", minval = 1, maxval = 10, group = 'PYRAMIDING')
StepEntry = input.string('Incremental', 'Step Entry Mode', tooltip = "Select the way you want to add new trades", options = ['Normal', 'Incremental'], group = 'PYRAMIDING')
bbBetterPrice = input.float(1.1, 'Min. Better Price %', tooltip = "Set the minimum better price percentage you want to get when adding new trades", minval = 0.1, step = 0.1, group = 'PYRAMIDING')
// ————— Backtest input
// Setting the start date for the backtesting period as January 1, 2000 at 1:00 UTC
StartDate = timestamp('01 Jan 2000 01:00 +000')
// Setting the start of the trading period for the backtest, using the start date above as the default value
testPeriodStart = input.time(StartDate, 'Start of Trading', tooltip = "Set the start date and time of the backtesting period", group = 'BACKTEST')
// ———————————————————— Average Price Variable
// Setting the average price variable to the close price of each candle, and using the strategy's average price if available
float AveragePrice = close
AveragePrice := nz(strategy.position_avg_price, close)
// ———————————————————— Exponential Moving Average
// Calculating the slow and fast Exponential Moving Averages (EMAs) using the close price
sEMA = ta.ema(close, sEma_Length)
fEMA = ta.ema(close, fEma_Length)
// Setting the conditions for a long or short signal based on the relationship between the fast and slow EMAs
bool EMA_longCond = na
bool EMA_shortCond = na
EMA_longCond := fEMA > sEMA and sEMA > sEMA[1]
EMA_shortCond := fEMA < sEMA and sEMA < sEMA[1]
// Plotting the EMAs on the chart and coloring them based on the long and short conditions
EMA_color = EMA_longCond ? color.new(color.green, 50) : EMA_shortCond ? color.new(color.red, 50) : color.new(color.orange, 50)
plot(sEMA, 'Slow EMA', EMA_color, 3)
plot(fEMA, 'Fast EMA', EMA_color, 2)
// ———————————————————— ADX
// Calculating the Directional Indicator Plus (+DI), Directional Indicator Minus (-DI), and Average Directional Movement Index (ADX)
[DIPlus, DIMinus, ADX] = ta.dmi(ADX_len, ADX_smo)
// Setting the conditions for a long or short signal based on the relationship between +DI and -DI and the ADX value
bool ADX_longCond = na
bool ADX_shortCond = na
ADX_longCond := DIPlus > DIMinus and ADX > th
ADX_shortCond := DIPlus < DIMinus and ADX > th
// Coloring the bars on the chart based on the long and short conditions
ADX_color = ADX_longCond ? color.new(color.green, 25) : ADX_shortCond ? color.new(color.red, 25) : color.new(color.orange, 25)
barcolor(color = ADX_color, title = 'ADX')
// ———————————————————— SAR
// Calculating the Parabolic SAR (SAR) based on the parameters set for step, max, and acceleration factor
SAR = ta.sar(Sst, Sinc, Smax)
// Setting the conditions for a long or short signal based on the relationship between the SAR value and the close price
bool SAR_longCond = na
bool SAR_shortCond = na
SAR_longCond := SAR < close
SAR_shortCond := SAR > close
// Plotting the SAR on the chart and coloring it based on the long and short conditions
plot(SAR, 'SAR', SAR_longCond ? color.new(color.green, 50) : color.new(color.red, 50), style = plot.style_circles)
// ———————————————————— MACD
// Calculating the Moving Average Convergence Divergence (MACD) and its signal line, as well as the MACD-Z value
// Define three variables lMACD, sMACD, and hist by calling the ta.macd() function using the 'close', 'fastLength', 'slowLength', and 'signalLength' as parameters
[lMACD, sMACD, hist] = ta.macd(close, fastLength, slowLength, signalLength)
// ————— MAC-Z calculation
// Define a function calc_zvwap(pds) that calculates the z-score of the volume-weighted average price (VWAP) of 'close' for a given period 'pds'
calc_zvwap(pds) =>
mean = math.sum(volume * close, pds) / math.sum(volume, pds)
vwapsd = math.sqrt(ta.sma(math.pow(close - mean, 2), pds))
(close - mean) / vwapsd
// Define float variables
float zscore = na
float fastMA = na
float slowMA = na
float macd = na
float macz = na
float signal = na
float histmacz = na
// Call the function calc_zvwap(lengthz) to calculate the z-score of the VWAP for a given period 'lengthz'
zscore := calc_zvwap(lengthz)
// Calculate the simple moving averages of the 'close' prices using 'fastLength' and 'slowLength' periods, and assign them to 'fastMA' and 'slowMA' respectively
fastMA := ta.sma(close, fastLength)
slowMA := ta.sma(close, slowLength)
// Assign the 'lMACD' variable to 'macd'
macd := lMACD
// Calculate 'macz' by multiplying the z-score by a constant 'A',
// adding the 'macd' value, and dividing by the product of the standard deviation of the 'close' prices over a period 'lengthStdev' and a constant 'B'
macz := (zscore * A) + (macd / (ta.stdev(close, lengthStdev) * B))
// Calculate the simple moving average of the 'macz' values over a period 'signalLength' and assign it to 'signal'
signal := ta.sma(macz, signalLength)
// Calculate the difference between 'macz' and 'signal' and assign it to 'histmacz'
histmacz := macz - signal
// ————— MACD conditions
// Define two boolean variables 'MACD_longCond' and 'MACD_shortCond'
bool MACD_longCond = na
bool MACD_shortCond = na
// If 'MACD_options' is equal to 'MACD', check if the 'hist' value is greater than 0 and assign the result to 'MACD_longCond';
// otherwise, check if 'histmacz' is greater than 0 and assign the result to 'MACD_longCond'
MACD_longCond := MACD_options == 'MACD' ? hist > 0 : histmacz > 0
// If 'MACD_options' is equal to 'MACD', check if the
MACD_shortCond := MACD_options == 'MACD' ? hist < 0 : histmacz < 0
// ———————————————————— Bollinger Bands
// ————— BB calculation
// Calculates the middle, upper and lower bands using the Bollinger Bands technical analysis indicator
[BB_middle, BB_upper, BB_lower] = ta.bb(close, BB_Length, BB_mult)
// ————— Bollinger Bands width
// Calculates the width of the Bollinger Bands
float BB_width = na
BB_width := (BB_upper - BB_lower) / BB_middle
// ————— Long Bollinger Bands conditions
// Defines the conditions for entering a long position using Bollinger Bands
// New Longs
bool BB_long01 = na
BB_long01 := Position != 'Short' and not ADX_shortCond and ta.crossunder(low, BB_lower) and EMA_longCond and BB_width > (bbMinWidth01 / 100)
// Pyramiding Longs
bool BB_long02 = na
BB_long02 := Position != 'Short' and not ADX_shortCond and ta.crossunder(low, BB_lower) and EMA_longCond and BB_width > (bbMinWidth02 / 100)
// ————— Short Bollinger Bands conditions
// Defines the conditions for entering a short position using Bollinger Bands
// New Shorts
bool BB_short01 = na
BB_short01 := Position != 'Long' and not ADX_longCond and ta.crossover(high, BB_upper) and EMA_shortCond and BB_width > (bbMinWidth01 / 100)
// Pyramiding Shorts
bool BB_short02 = na
BB_short02 := Position != 'Long' and not ADX_longCond and ta.crossover(high, BB_upper) and EMA_shortCond and BB_width > (bbMinWidth02 / 100)
// ————— Bollinger Bands plotting
// Plots the Bollinger Bands on the chart.
u_BB = plot(BB_upper, 'Upper Bollinger Band', EMA_color, 2)
l_BB = plot(BB_lower, 'Lower Bollinger Band', EMA_color, 2)
fill(u_BB, l_BB, title = 'Bollinger Band Background', color = fEMA > sEMA ? color.new(color.green, 95) : color.new(color.red, 95))
// ———————————————————— Volume
// Defines conditions for long and short positions based on volume
bool VOL_longCond = na
bool VOL_shortCond = na
VOL_longCond := volume > ta.sma(volume, sma_Length) * volume_f
VOL_shortCond := VOL_longCond
// ———————————————————— Strategy
// Defines the long and short conditions for entering a trade based on multiple indicators and volume
bool longCond = na
longCond := Position != 'Short' and EMA_longCond and ADX_longCond and SAR_longCond and MACD_longCond and VOL_longCond
bool shortCond = na
shortCond := Position != 'Long' and EMA_shortCond and ADX_shortCond and SAR_shortCond and MACD_shortCond and VOL_shortCond
// ———————————————————— Take Profit
// ————— Donchian Channels Calculation
// Calculates the Donchian Channels for determining take profit levels
float DClower = na
float DCupper = na
float DCbasis = na
DClower := ta.lowest(DClength)
DCupper := ta.highest(DClength)
DCbasis := math.avg(DCupper, DClower)
// ————— Take Profit Conditions
// Determines the take profit levels based on the selected options
float longPriceProfit = na
float shortPriceProfit = na
if TP_options == 'Both'
// Calculate the long and short take profit levels if both options are selected
longPriceProfit := math.max(DCupper, (1 + (tp / 100)) * AveragePrice)
shortPriceProfit := math.min(DClower, (1 - (tp / 100)) * AveragePrice)
else if TP_options == 'Normal'
// Calculate the normal take profit levels if that option is selected
longPriceProfit := (1 + (tp / 100)) * AveragePrice
shortPriceProfit := (1 - (tp / 100)) * AveragePrice
else if TP_options == 'Donchian'
// Calculate the Donchian take profit levels if that option is selected
longPriceProfit := math.max(DCupper, AveragePrice)
shortPriceProfit := math.min(DClower, AveragePrice)
// ————— Take Profit Plotting
// Plot the take profit levels on the chart
plot(strategy.position_size > 0 ? longPriceProfit : strategy.position_size < 0 ? shortPriceProfit : na,
'Take Profit', strategy.position_size > 0 ? color.new(color.blue, 30) : color.new(color.red, 30), 2, plot.style_circles)
// ———————————————————— ATR Stop Loss
// ————— ATR Calculation
// Calculate the ATR stop loss levels
float ATR_SL_Long = low - ta.atr(atrPeriodSl) * multiplierPeriodSl
float ATR_SL_Short = high + ta.atr(atrPeriodSl) * multiplierPeriodSl
float longStopPrev = nz(ATR_SL_Long[1], ATR_SL_Long)
float shortStopPrev = nz(ATR_SL_Short[1], ATR_SL_Short)
ATR_SL_Long := open > longStopPrev ? math.max(ATR_SL_Long, longStopPrev) : ATR_SL_Long
ATR_SL_Short := open < shortStopPrev ? math.min(ATR_SL_Short, shortStopPrev) : ATR_SL_Short
// ————— Price Stop
// Calculate the price stop levels
float longPriceStop = na
float shortPriceStop = na
if SL_options == 'Both'
// Calculate the long and short price stop levels if both options are selected
longPriceStop := math.max(ATR_SL_Long, (1 - (sl / 100)) * AveragePrice)
shortPriceStop := math.min(ATR_SL_Short, (1 + (sl / 100)) * AveragePrice)
else if SL_options == 'Normal'
// Calculate the normal price stop levels if that option is selected
longPriceStop := (1 - (sl / 100)) * AveragePrice
shortPriceStop := (1 + (sl / 100)) * AveragePrice
else if SL_options == 'ATR'
// Calculate the ATR price stop levels if that option is selected
longPriceStop := ATR_SL_Long
shortPriceStop := ATR_SL_Short
// ————— Variable Stop Loss %
// Calculate the variable stop loss percentage levels
float slPercentLong = na
slPercentLong := (math.max(0, (AveragePrice - longPriceStop)) / AveragePrice) * 100
float slPercentShort = na
slPercentShort := (math.max(0, (shortPriceStop - AveragePrice)) / AveragePrice) * 100
// ————— Stop Loss plotting
// Plots the stop loss level based on the current position size and whether it's a long or short position
// Uses circles to visualize the stop loss level
plot(strategy.position_size > 0 ? longPriceStop : strategy.position_size < 0 ? shortPriceStop : na,
'Stop Loss', strategy.position_size > 0 ? color.new(color.aqua, 80) : color.new(color.purple, 70), 2, plot.style_circles)
// ————— Average price plotting
// Plots the average price of the current position, using a cross to visualize the price level
// Uses different colors depending on whether it's a long or short position
plot(ta.change(strategy.position_avg_price) ? strategy.position_avg_price : na,
'Average price', strategy.position_size > 0 ? color.new(color.aqua, 20) : color.new(color.yellow, 20), 2, plot.style_cross)
// ———————————————————— Backtest
// Define the variable "Equity" and assign it the value of "strategy.equity"
float Equity = strategy.equity
// Define the variable "Balance" and assign it the sum of "strategy.initial_capital" and "strategy.netprofit"
float Balance = strategy.initial_capital + strategy.netprofit
// Define the variable "RealizedPnL" and assign it the value of "strategy.netprofit"
float RealizedPnL = strategy.netprofit
// Define the variable "Floating" and assign it the value of "strategy.openprofit"
float Floating = strategy.openprofit
// Calculate the percentage of "Floating" relative to "Balance" and assign it to "PFloating"
float PFloating = (Floating / Balance) * 100
// Calculate the percentage of "RealizedPnL" relative to "strategy.initial_capital" and assign it to "PRealizedPnL"
float PRealizedPnL = (RealizedPnL / strategy.initial_capital) * 100
// Calculate the sum of "Floating" and "RealizedPnL" and assign it to "URealizedPnL"
float URealizedPnL = Floating + RealizedPnL
// Calculate the percentage of "URealizedPnL" relative to "strategy.initial_capital" and assign it to "PURealizedPnL"
float PURealizedPnL = ((URealizedPnL) / strategy.initial_capital) * 100
// Calculate the profit factor by dividing "strategy.grossprofit" by "strategy.grossloss" and assign it to "ProfitFactor"
float ProfitFactor = strategy.grossprofit / strategy.grossloss
// Calculate the position size by multiplying "strategy.position_size" and "strategy.position_avg_price" and assign it to "PositionSize"
float PositionSize = strategy.position_size * strategy.position_avg_price
// Calculate the cash by subtracting the product of "nz(PositionSize)" and "marginRate" from "Balance" and assign it to "Cash"
float Cash = Balance
// Calculate the profitability by dividing "strategy.wintrades" by the sum of "strategy.wintrades" and "strategy.losstrades", multiplying by 100, and assign it to "Profitability"
float Profitability = (strategy.wintrades / (strategy.wintrades + strategy.losstrades)) * 100
// Calculate the leverage parameter by dividing the absolute value of "PositionSize" by "Balance" and assign it to "LeverageParameter"
float LeverageParameter = math.abs(nz(PositionSize / Balance))
// Calculate the trading time by subtracting "strategy.closedtrades.entry_time(0)" from "time_close" and assign it to "TradingTime"
int TradingTime = time_close - strategy.closedtrades.entry_time(0)
// ————— Creating the Table
// Create a table with a specific format and assign it to a variable
var InfoPanel = table.new(position.bottom_left, 2, 10, border_width = 1)
// Define a function for the table formatting
ftable(_table_id, _column, _row, _text, _bgcolor) =>
table.cell(_table_id, _column, _row, _text, 0, 0, color.black, text.align_left, text.align_center, size.tiny, _bgcolor)
// Function to convert time in milliseconds to string format
tfString(int timeInMs) =>
// convert to seconds
float s = timeInMs / 1000
// convert to minutes
float m = s / 60
// convert to hours
float h = m / 60
// convert to days
float d = h / 24
// convert to months
float mo = d / 30.416
// get minutes
int tm = math.floor(m % 60)
// get hours
int tr = math.floor(h % 24)
// get days
int td = math.floor(d % 30.416)
// get months
int tmo = math.floor(mo % 12)
// get years
int ys = math.floor(d / 365)
// Format the time in the appropriate string format
string result = switch
// if time interval is 1 month, return "1M"
d == 30 and tr == 10 and tm == 30 => "1M"
// if time interval is 1 week, return "1W"
d == 7 and tr == 0 and tm == 0 => "1W"
=>
// get the years string
string yStr = ys ? str.tostring(ys) + "Y " : ""
// get the months string
string moStr = tmo ? str.tostring(tmo) + "M " : ""
// get the days string
string dStr = td ? str.tostring(td) + "D " : ""
// get the hours string
string hStr = tr ? str.tostring(tr) + "H " : ""
// get the minutes string
string mStr = tm ? str.tostring(tm) + "min" : ""
// concatenate all the strings to get the final result string
yStr + moStr + dStr + hStr + mStr
// This code is using the ftable function to create a table of information in a panel.
// Display equity information in the info panel using the ftable function
ftable(InfoPanel, 0, 0, 'Equity: ', #9598a1)
// Display current position information in the info panel using the ftable function
ftable(InfoPanel, 0, 1, 'Position: ', #9598a1)
// Display available cash information in the info panel using the ftable function
ftable(InfoPanel, 0, 2, 'Cash: ', #9598a1)
// Display floating profit/loss information in the info panel using the ftable function
ftable(InfoPanel, 0, 3, 'Floating: ', #9598a1)
// Display realized profit/loss information in the info panel using the ftable function
ftable(InfoPanel, 0, 4, 'Realized PnL: ' , #9598a1)
// Display unrealized profit/loss information in the info panel using the ftable function
ftable(InfoPanel, 0, 5, 'Unrealized PnL: ' , #9598a1)
// Display leverage information in the info panel using the ftable function
ftable(InfoPanel, 0, 6, 'Leverage: ' , #9598a1)
// Display profitability information in the info panel using the ftable function
ftable(InfoPanel, 0, 7, 'Profitability: ' , #9598a1)
// Display profit factor information in the info panel using the ftable function
ftable(InfoPanel, 0, 8, 'Profit Factor: ' , #9598a1)
// Display trading time information in the info panel using the ftable function
ftable(InfoPanel, 0, 9, 'Time of Trading: ', #9598a1)
// Display equity value with currency information in the info panel using the ftable function
ftable(InfoPanel, 1, 0, str.tostring(Equity, '#.##') + ' ' + syminfo.currency, Equity >= 0 ? color.green : color.red)
// Display position size with base currency information in the info panel using the ftable function
ftable(InfoPanel, 1, 1, str.tostring(strategy.position_size, '#.#####') + ' ' + syminfo.basecurrency, strategy.position_size >= 0 ? color.green : color.red)
// Display available cash with currency information in the info panel using the ftable function
ftable(InfoPanel, 1, 2, str.tostring(Cash, '#.##') + ' ' + syminfo.currency, Cash >= 0 ? color.green : color.red)
// Display percentage of floating profit/loss information in the info panel using the ftable function
ftable(InfoPanel, 1, 3, str.tostring(PFloating, '#.##') + ' %', PFloating >= 0 ? color.green : color.red)
// Display percentage of realized profit/loss information in the info panel using the ftable function
ftable(InfoPanel, 1, 4, str.tostring(PRealizedPnL, '#.##') + ' %' , PRealizedPnL >= 0 ? color.green : color.red)
// Display percentage of unrealized profit/loss information in the info panel using the ftable function
ftable(InfoPanel, 1, 5, str.tostring(PURealizedPnL, '#.##') + ' %', PURealizedPnL >= 0 ? color.green : color.red)
// Show leverage parameter in the info panel
ftable(InfoPanel, 1, 6, str.tostring(LeverageParameter, '#.##') + ' x', math.round(LeverageParameter, 1) <= 1 ? color.green : color.red)
// Show profitability percentage in the info panel
ftable(InfoPanel, 1, 7, str.tostring(Profitability, '#.##') + ' %', Profitability >= 1 ? color.green : color.red)
// Show the profit factor in the info panel
ftable(InfoPanel, 1, 8, str.tostring(ProfitFactor, '#.###'), ProfitFactor >= 1 ? color.green : color.red)
// Show the time of trading in the info panel in human-readable format
ftable(InfoPanel, 1, 9, tfString(TradingTime), #9598a1)
// ————— Long / Short quantities according to risk
// Define a function that calculates the factor sum of a number
fSum(_Num)=>
(math.pow(_Num, 2) + _Num) / 2
// Calculate long and short quantities based on different scenarios
float QuantityLong = na
float QuantityShort = na
// The QuantityLong and QuantityShort variables represent the calculated position sizes based on different risk scenarios
if StepEntry == 'Normal'
QuantityLong := (1 / Pyr) * (Balance / close) * ((Risk / 100) / (slPercentLong / 100))
QuantityShort := (1 / Pyr) * (Balance / close) * ((Risk / 100) / (slPercentShort / 100))
else
QuantityLong := ((strategy.opentrades + 1) / (fSum(Pyr))) * (Balance / close) * ((Risk / 100) / (slPercentLong / 100))
QuantityShort := ((strategy.opentrades + 1) / (fSum(Pyr))) * (Balance / close) * ((Risk / 100) / (slPercentShort / 100))
// ————— Long alert message
// Define long alert messages with placeholders
string LongMessage = na
LongMessage := '{"code": "ENTER-LONG_OKEX-SWAP__Super-8_30M_1234567890", "qty":"' + str.tostring(QuantityLong) + '"}'
string XLongMessage = na
XLongMessage := '{"code": "EXIT-LONG_OKEX-SWAP__Super-8_30M_1234567890", "qty":"' + str.tostring(strategy.position_size) + '"}'
// ————— Short alert message
// Define short alert messages with placeholders
string ShortMessage = na
ShortMessage := '{"code": "ENTER-SHORT_OKEX-SWAP__Super-8_30M_1234567890", "qty":"' + str.tostring(QuantityShort) + '"}'
string XShortMessage = na
XShortMessage := '{"code": "EXIT-SHORT_OKEX-SWAP__Super-8_30M_1234567890", "qty":"' + str.tostring(math.abs(strategy.position_size)) + '"}'
// The LongMessage and ShortMessage variables are strings that define the alert messages for the long and short positions respectively,
// including placeholders for dynamic values like the current close price and the calculated position size
// The XLongMessage and XShortMessage variables represent messages to close out long and short positions respectively
// Copy and paste this message on the alert box:
// {{strategy.order.alert_message}}
// Copy and paste this url on the WebHook box:
// https://wundertrading.com/bot/exchange
// ————— Entering long positions
// Check if it's time to start the test period and if there are less open trades than the maximum allowed
if time >= testPeriodStart and strategy.opentrades < Pyr
// Main long entries
// Check if the long condition is met or if the upper Bollinger Band is crossed and if there are no open trades or a short position is already open or if the price is lower than the previous entry price minus the percentage allowed
// If the conditions are met, execute the long entry with the desired quantity and alert message
if (longCond or BB_long01) and strategy.opentrades == 0
or (longCond or BB_long01) and strategy.position_size < 0
or (longCond or BB_long01) and close < strategy.opentrades.entry_price(strategy.opentrades - 1) * (1 - (bbBetterPrice / 100))
strategy.order('Long', strategy.long, qty = QuantityLong, alert_message = LongMessage)
// BB long entries
// Check if the upper Bollinger Band is crossed and a long position is already open and if the price is lower than the previous entry price minus the percentage allowed
// If the conditions are met, execute the long entry with the desired quantity and alert message
if BB_long02 and strategy.position_size > 0
and close < strategy.opentrades.entry_price(strategy.opentrades - 1) * (1 - (bbBetterPrice / 100))
strategy.order('Long', strategy.long, qty = QuantityLong, alert_message = LongMessage)
// ————— Entering short positions
// Check if it's time to start the test period and if there are less open trades than the maximum allowed
if time >= testPeriodStart and strategy.opentrades < Pyr
// Main short entries
// Check if the short condition is met or if the lower Bollinger Band is crossed and if there are no open trades or a long position is already open or if the price is higher than the previous entry price plus the percentage allowed
// If the conditions are met, execute the short entry with the desired quantity and alert message
if (shortCond or BB_short01) and strategy.opentrades == 0
or (shortCond or BB_short01) and strategy.position_size > 0
or (shortCond or BB_short01) and close > strategy.opentrades.entry_price(strategy.opentrades - 1) * (1 + (bbBetterPrice / 100))
strategy.order('Short', strategy.short, qty = QuantityShort, alert_message = ShortMessage)
// BB short entries
// Check if the lower Bollinger Band is crossed and a short position is already open and if the price is higher than the previous entry price plus the percentage allowed
// If the conditions are met, execute the short entry with the desired quantity and alert message
if BB_short02 and strategy.position_size < 0
and close > strategy.opentrades.entry_price(strategy.opentrades - 1) * (1 + (bbBetterPrice / 100))
strategy.order('Short', strategy.short, qty = QuantityShort, alert_message = ShortMessage)
// ————— Closing positions with first long TP
// Check if there is a long position open
if strategy.position_size > 0
// If there is, check if a trailing offset is set
if trailOffset > 0
// If there is a trailing offset, execute the exit with a trailing stop
strategy.exit('TPl', 'Long', trail_price = longPriceProfit,
trail_offset = ((trailOffset / 100) * high) / syminfo.mintick,
stop = longPriceStop,
comment_profit = 'TPl',
comment_loss = 'SLl', alert_message = XLongMessage)
else
// If there is no trailing offset, execute the exit with a limit and stop loss
strategy.exit('TPl', 'Long', limit = longPriceProfit,
stop = longPriceStop,
comment_profit = 'TPl',
comment_loss = 'SLl',
alert_message = XLongMessage)
// ————— Canceling long exit orders to avoid simultaneity with re-entry
// This code block cancels any previously set long exit orders if the Bollinger Bands indicate a potential re-entry into the market
if BB_long02 and strategy.position_size > 0
strategy.cancel('TPl')
// ————— Closing positions with first short TP
// This code block checks if the strategy has a short position and if so, it closes it with a trailing stop loss or a take profit order
if strategy.position_size < 0
if trailOffset > 0
strategy.exit('TPs', 'Short', trail_price = shortPriceProfit,
trail_offset = ((trailOffset / 100) * low) / syminfo.mintick,
stop = shortPriceStop,
comment_profit = 'TPs',
comment_loss = 'SLs',
alert_message = XShortMessage)
else
strategy.exit('TPs', 'Short', limit = shortPriceProfit,
stop = shortPriceStop,
comment_profit = 'TPs',
comment_loss = 'SLs',
alert_message = XShortMessage)
// ————— Canceling short exit orders to avoid simultaneity with re-entry
// This code block cancels any previously set short exit orders if the Bollinger Bands indicate a potential re-entry into the market
if BB_short02 and strategy.position_size < 0
strategy.cancel('TPs') |
Hulk Grid Algorithm - The Quant Science | https://www.tradingview.com/script/XETXYwyp-Hulk-Grid-Algorithm-The-Quant-Science/ | thequantscience | https://www.tradingview.com/u/thequantscience/ | 320 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © thequantscience
// ██╗ ██╗██╗ ██╗██╗ ██╗ ██╗ ██████╗ ██████╗ ██╗██████╗ █████╗ ██╗ ██████╗ ██████╗ ██████╗ ██╗████████╗██╗ ██╗███╗ ███╗
// ██║ ██║██║ ██║██║ ██║ ██╔╝ ██╔════╝ ██╔══██╗██║██╔══██╗ ██╔══██╗██║ ██╔════╝ ██╔═══██╗██╔══██╗██║╚══██╔══╝██║ ██║████╗ ████║
// ███████║██║ ██║██║ █████╔╝ ██║ ███╗██████╔╝██║██║ ██║ ███████║██║ ██║ ███╗██║ ██║██████╔╝██║ ██║ ███████║██╔████╔██║
// ██╔══██║██║ ██║██║ ██╔═██╗ ██║ ██║██╔══██╗██║██║ ██║ ██╔══██║██║ ██║ ██║██║ ██║██╔══██╗██║ ██║ ██╔══██║██║╚██╔╝██║
// ██║ ██║╚██████╔╝███████╗██║ ██╗ ╚██████╔╝██║ ██║██║██████╔╝ ██║ ██║███████╗╚██████╔╝╚██████╔╝██║ ██║██║ ██║ ██║ ██║██║ ╚═╝ ██║
// ╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝╚═════╝ ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝
//@version=5
strategy(
title = 'Hulk Grid Algorithm - The Quant Science',
overlay = true,
initial_capital = 1000,
commission_type = strategy.commission.percent,
commission_value = 0.07,
pyramiding = 10,
default_qty_type = strategy.percent_of_equity
)
// #########################################################################################################
if not timeframe.isintraday
runtime.error("WRONG TIMEFRAME: Please select an intraday timeframe when use this strategy backtesting.")
// #########################################################################################################
startDate = input.int(title="Start Date", defval=1, minval=1, maxval=31, group = "DATE PERIOD CONFIGURATION")
startMonth = input.int(title="Start Month", defval=1, minval=1, maxval=12, group = "DATE PERIOD CONFIGURATION")
startYear = input.int(title="Start Year", defval=2018, minval=1800, maxval=2100, group = "DATE PERIOD CONFIGURATION")
endDate = input.int(title="End Date", defval=12, minval=1, maxval=31, group = "DATE PERIOD CONFIGURATION")
endMonth = input.int(title="End Month", defval=3, minval=1, maxval=12, group = "DATE PERIOD CONFIGURATION")
endYear = input.int(title="End Year", defval=2022, minval=1800, maxval=2100, group = "DATE PERIOD CONFIGURATION")
inDateRange = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0)) and (time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0))
// #########################################################################################################
requestpastweekclose = request.security(syminfo.tickerid, "D", close[1], gaps = barmerge.gaps_off)
requestpastweekopen = request.security(syminfo.tickerid, "D", open[1], gaps = barmerge.gaps_off)
newday = request.security(syminfo.tickerid, "D", close, gaps = barmerge.gaps_off)
// #########################################################################################################
ten_grid = input.bool(defval = false, title = "Enable Strategy", tooltip = "Create grid backtesting.", group = "STRATEGY CONFIGURATION")
stop_loss = input.float(defval = 2.00, step = 0.10, title = "Stop Loss: ", group = "STRATEGY CONFIGURATION")
take_profit = input.float(defval = 2.00, step = 0.10, title = "Take Profit: ", group = "STRATEGY CONFIGURATION")
period_num = input.int(defval = 3, step = 1, title = "Minimum Bars: ", group = "STRATEGY CONFIGURATION")
size_grid = input.float(defval = 200.00, step = 1.00, title = "Size Grid Range: ", group = "STRATEGY CONFIGURATION")
// #########################################################################################################
var float high_start = 0
var float high_end = 0
checking = requestpastweekclose > requestpastweekopen
if checking==true
high_start := requestpastweekclose
high_end := requestpastweekopen
grid_range = high_start - high_end
period = ta.barssince(ta.change(checking==true))==period_num
TriggerGrid() =>
trigger = checking==true and period and grid_range > size_grid and close
trigger
trigger_entry = TriggerGrid()
var float grid_1 = 0
var float grid_2 = 0
var float grid_3 = 0
var float grid_4 = 0
var float grid_5 = 0
var float grid_6 = 0
var float grid_7 = 0
var float grid_8 = 0
var float grid_9 = 0
var float grid_10 = 0
var float factor = 0
if ten_grid == true and trigger_entry==true and strategy.opentrades==0
factor := grid_range / 10
// UP GRID
grid_1 := (high_start)
grid_2 := (high_start + (factor * 1))
grid_3 := (high_start + (factor * 2))
grid_4 := (high_start + (factor * 3))
grid_5 := (high_start + (factor * 4))
// DOWN GRID
grid_6 := (high_start - (factor * 1))
grid_7 := (high_start - (factor * 2))
grid_8 := (high_start - (factor * 3))
grid_9 := (high_start - (factor * 4))
grid_10 := (high_start - (factor * 5))
// #########################################################################################################
var tb = table.new(position.bottom_left, 1, 1, bgcolor = color.new(#00ff08, 74))
if barstate.isfirst
table.cell(tb, 0, 0,
'Developed by The Quant Science™'
,text_size = size.normal
,text_color = color.new(#00ff08, 21))
// #########################################################################################################
var float new_ten_grid_1 = 0
var float new_ten_grid_2 = 0
var float new_ten_grid_3 = 0
var float new_ten_grid_4 = 0
var float new_ten_grid_5 = 0
var float new_ten_grid_6 = 0
var float new_ten_grid_7 = 0
var float new_ten_grid_8 = 0
var float new_ten_grid_9 = 0
var float new_ten_grid_10 = 0
if ten_grid == true
new_ten_grid_1 := grid_1
new_ten_grid_2 := grid_2
new_ten_grid_3 := grid_3
new_ten_grid_4 := grid_4
new_ten_grid_5 := grid_5
new_ten_grid_6 := grid_6
new_ten_grid_7 := grid_7
new_ten_grid_8 := grid_8
new_ten_grid_9 := grid_9
new_ten_grid_10 := grid_10
else if ten_grid == false
new_ten_grid_1 := na
new_ten_grid_2 := na
new_ten_grid_3 := na
new_ten_grid_4 := na
new_ten_grid_5 := na
new_ten_grid_6 := na
new_ten_grid_7 := na
new_ten_grid_8 := na
new_ten_grid_9 := na
new_ten_grid_10 := na
destroyall = new_ten_grid_10 - (new_ten_grid_10 * stop_loss / 100)
des_function = ta.crossunder(close, destroyall)
takeprofitlevel = new_ten_grid_5 + (new_ten_grid_5 * take_profit / 100)
var float lots = 0
if trigger_entry==true and ten_grid==true and period and inDateRange
lots := (strategy.equity / close) / 5
if close > new_ten_grid_1
strategy.entry(id = "O #1", direction = strategy.long, qty = lots, limit = new_ten_grid_1)
strategy.entry(id = "O #2", direction = strategy.long, qty = lots, limit = new_ten_grid_2)
strategy.entry(id = "O #3", direction = strategy.long, qty = lots, limit = new_ten_grid_3)
strategy.entry(id = "O #4", direction = strategy.long, qty = lots, limit = new_ten_grid_4)
strategy.entry(id = "O #5", direction = strategy.long, qty = lots, limit = new_ten_grid_5)
if close < new_ten_grid_1
strategy.entry(id = "O #6", direction = strategy.long, qty = lots, limit = new_ten_grid_6)
strategy.entry(id = "O #7", direction = strategy.long, qty = lots, limit = new_ten_grid_7)
strategy.entry(id = "O #8", direction = strategy.long, qty = lots, limit = new_ten_grid_8)
strategy.entry(id = "O #9", direction = strategy.long, qty = lots, limit = new_ten_grid_9)
strategy.entry(id = "O #10", direction = strategy.long, qty = lots, limit = new_ten_grid_10)
if close > takeprofitlevel
strategy.cancel_all()
if close < destroyall
strategy.cancel_all()
if new_ten_grid_2 and ten_grid == true
strategy.exit(id = "C #1", from_entry = "O #1", qty = 100, limit = new_ten_grid_2)
if new_ten_grid_3 and ten_grid == true
strategy.exit(id = "C #2", from_entry = "O #2", qty = 100, limit = new_ten_grid_3)
if new_ten_grid_4 and ten_grid == true
strategy.exit(id = "C #3", from_entry = "O #3", qty = 100, limit = new_ten_grid_4)
if new_ten_grid_5 and ten_grid == true
strategy.exit(id = "C #4", from_entry = "O #4", qty = 100, limit = new_ten_grid_5)
if takeprofitlevel and ten_grid == true
strategy.exit(id = "C #5", from_entry = "O #5", qty = 100, limit = takeprofitlevel)
if new_ten_grid_5 and ten_grid == true
strategy.exit(id = "C #6", from_entry = "O #6", qty = 100, limit = new_ten_grid_1)
if new_ten_grid_6 and ten_grid == true
strategy.exit(id = "C #7", from_entry = "O #7", qty = 100, limit = new_ten_grid_6)
if new_ten_grid_7 and ten_grid == true
strategy.exit(id = "C #8", from_entry = "O #8", qty = 100, limit = new_ten_grid_7)
if new_ten_grid_8 and ten_grid == true
strategy.exit(id = "C #9", from_entry = "O #9", qty = 100, limit = new_ten_grid_8)
if new_ten_grid_9 and ten_grid == true
strategy.exit(id = "C #10", from_entry = "O #10", qty = 100, limit = new_ten_grid_9)
if des_function
strategy.close_all("Destroyed Grid")
strategy.cancel_all()
if session.islastbar_regular
strategy.close_all("Dayli Session End")
if session.islastbar_regular
strategy.cancel_all()
// #########################################################################################################
fill(plot(grid_1, color = color.new(color.rgb(0, 255, 132), 95)),
plot(grid_2, color = color.new(color.rgb(0, 255, 132), 95)),
color = color.new(#00ff08, 80))
fill(plot(grid_2, color = color.new(color.rgb(0, 255, 132), 95)),
plot(grid_3, color = color.new(color.rgb(0, 255, 132), 95)),
color = color.new(#00ff08, 85))
fill(plot(grid_3, color = color.new(color.rgb(0, 255, 132), 95)),
plot(grid_4, color = color.new(color.rgb(0, 255, 132), 95)),
color = color.new(#00ff08, 85))
fill(plot(grid_4, color = color.new(color.rgb(0, 255, 132), 95)),
plot(grid_5, color = color.new(color.rgb(0, 255, 132), 95)),
color = color.new(#00ff08, 90))
fill(plot(grid_1, color = color.new(color.rgb(0, 255, 132), 95)),
plot(grid_6, color = color.new(color.rgb(0, 255, 132), 95)),
color = color.new(#00ff08, 80))
fill(plot(grid_6, color = color.new(color.rgb(0, 255, 132), 95)),
plot(grid_7, color = color.new(color.rgb(0, 255, 132), 95)),
color = color.new(#00ff08, 80))
fill(plot(grid_7, color = color.new(color.rgb(0, 255, 132), 95)),
plot(grid_8, color = color.new(color.rgb(0, 255, 132), 95)),
color = color.new(#00ff08, 85))
fill(plot(grid_8, color = color.new(color.rgb(0, 255, 132), 95)),
plot(grid_9, color = color.new(color.rgb(0, 255, 132), 95)),
color = color.new(#00ff08, 85))
fill(plot(grid_9, color = color.new(color.rgb(0, 255, 132), 95)),
plot(grid_10, color = color.new(color.rgb(0, 255, 132), 95)),
color = color.new(#00ff08, 90))
// ######################################################################################################### |
Strategy Myth-Busting #4 - LSMA+HULL Crossover - [MYN] | https://www.tradingview.com/script/8JJIgOHg-Strategy-Myth-Busting-4-LSMA-HULL-Crossover-MYN/ | myncrypto | https://www.tradingview.com/u/myncrypto/ | 97 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © myn
//@version=5
strategy('Strategy Myth-Busting #4 - LSMA+HULL Crossover - [MYN]', max_bars_back=5000, overlay=true, pyramiding=0, initial_capital=1000, currency='USD', default_qty_type=strategy.percent_of_equity, default_qty_value=1.0, commission_value=0.075, use_bar_magnifier = true)
///Derek-Multiple-Take-Profit-Strategy-Template-v5-2022-04-03.pine
// 04-03-2022 Added ADX
// 08-17-2022 Added Dashboard
f_security(_symbol, _res, _src, _repaint) => request.security(_symbol, _res, _src[_repaint ? 0 : barstate.isrealtime ? 1 : 0])[_repaint ? 0 : barstate.isrealtime ? 0 : 1]
/////////////////////////////////////
//* Put your strategy logic below *//
/////////////////////////////////////
//LSMA - Thicken Line and change to white
//Hull Suite by InSilico / Disable show as band. Make line bolder
//Trading Rules
// Enter Long
// LSMA cross above Red Hull Suite line
// Price has to be above Hull Suite Line
// 1:5 Risk Ratio.
// Stop Loss is recent swing low
// Take Profit is 5x the risk
// Enter Short
// LSMA crosses under green Hull Suite Line
// Price has to be below Hull Suite Line
// 1:5 Risk Ratio.
// Stop Loss is recent swing high
// Take Profit is 5x The risk
// Least Squares Moving Average
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
//@version=5
//indicator(title = "Least Squares Moving Average", shorttitle="LSMA", overlay=true, timeframe="", timeframe_gaps=true)
length = input(title="Length", defval=25, group="LSMA")
offset = input(title="Offset", defval=0)
src = input(close, title="Source")
lsma = ta.linreg(src, length, offset)
plot(lsma, color=color.white, linewidth=4)
// Hull Suite by InSilico
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
//@version=5
//Basic Hull Ma Pack tinkered by InSilico
//indicator('Hull Suite by InSilico', overlay=true)
//INPUT
srcHull = input(close, title='Source', group="Hull Suite")
modeSwitch = input.string('Hma', title='Hull Variation', options=['Hma', 'Thma', 'Ehma'])
lengthHull = input(55, title='Length(180-200 for floating S/R , 55 for swing entry)')
lengthMult = input(1.0, title='Length multiplier (Used to view higher timeframes with straight band)')
useHtf = input(false, title='Show Hull MA from X timeframe? (good for scalping)')
htf = input.timeframe('240', title='Higher timeframe')
switchColor = input(true, 'Color Hull according to trend?')
candleCol = input(false, title='Color candles based on Hull\'s Trend?')
visualSwitch = input(false, title='Show as a Band?')
thicknesSwitch = input(4, title='Line Thickness')
transpSwitch = input.int(40, title='Band Transparency', step=5)
//FUNCTIONS
//HMA
HMA(_src, _length) =>
ta.wma(2 * ta.wma(_src, _length / 2) - ta.wma(_src, _length), math.round(math.sqrt(_length)))
//EHMA
EHMA(_src, _length) =>
ta.ema(2 * ta.ema(_src, _length / 2) - ta.ema(_src, _length), math.round(math.sqrt(_length)))
//THMA
THMA(_src, _length) =>
ta.wma(ta.wma(_src, _length / 3) * 3 - ta.wma(_src, _length / 2) - ta.wma(_src, _length), _length)
//SWITCH
Mode(modeSwitch, srcHull, len) =>
modeSwitch == 'Hma' ? HMA(srcHull, len) : modeSwitch == 'Ehma' ? EHMA(srcHull, len) : modeSwitch == 'Thma' ? THMA(srcHull, len / 2) : na
//OUT
_hull = Mode(modeSwitch, srcHull, int(lengthHull * lengthMult))
HULL = useHtf ? f_security(syminfo.ticker, htf, _hull,false) : _hull
MHULL = HULL[0]
SHULL = HULL[2]
//COLOR
hullColor = switchColor ? HULL > HULL[2] ? #00ff00 : #ff0000 : #ff9800
//PLOT
///< Frame
Fi1 = plot(MHULL, title='MHULL', color=hullColor, linewidth=thicknesSwitch, transp=50)
Fi2 = plot(visualSwitch ? SHULL : na, title='SHULL', color=hullColor, linewidth=thicknesSwitch, transp=50)
alertcondition(ta.crossover(MHULL, SHULL), title='Hull trending up.', message='Hull trending up.')
alertcondition(ta.crossover(SHULL, MHULL), title='Hull trending down.', message='Hull trending down.')
///< Ending Filler
fill(Fi1, Fi2, title='Band Filler', color=hullColor, transp=transpSwitch)
///BARCOLOR
barcolor(color=candleCol ? switchColor ? hullColor : na : na)
//////////////////////////////////////
//* Put your strategy rules below *//
/////////////////////////////////////
//o0wqgXG6jgI
/// Enter Long
// LSMA cross above Red Hull Suite line
// Price has to be above Hull Suite Line
enterLong = ta.crossover(lsma, HULL) and hullColor == #ff0000 and srcHull > HULL
// Enter Short
// LSMA crosses under green Hull Suite Line
// Price has to be below Hull Suite Line
enterShort = ta.crossunder(lsma,HULL) and hullColor == #00ff00 and srcHull < HULL
longCondition = enterLong
shortCondition = enterShort
//define as 0 if do not want to use
closeLongCondition = 0
closeShortCondition = 0
// ADX
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
adxEnabled = input.bool(defval = false , title = "Average Directional Index (ADX)", tooltip = "", group ="ADX" )
adxlen = input(14, title="ADX Smoothing", group="ADX")
adxdilen = input(14, title="DI Length", group="ADX")
adxabove = input(25, title="ADX Threshold", group="ADX")
adxdirmov(len) =>
adxup = ta.change(high)
adxdown = -ta.change(low)
adxplusDM = na(adxup) ? na : (adxup > adxdown and adxup > 0 ? adxup : 0)
adxminusDM = na(adxdown) ? na : (adxdown > adxup and adxdown > 0 ? adxdown : 0)
adxtruerange = ta.rma(ta.tr, len)
adxplus = fixnan(100 * ta.rma(adxplusDM, len) / adxtruerange)
adxminus = fixnan(100 * ta.rma(adxminusDM, len) / adxtruerange)
[adxplus, adxminus]
adx(adxdilen, adxlen) =>
[adxplus, adxminus] = adxdirmov(adxdilen)
adxsum = adxplus + adxminus
adx = 100 * ta.rma(math.abs(adxplus - adxminus) / (adxsum == 0 ? 1 : adxsum), adxlen)
adxsig = adxEnabled ? adx(adxdilen, adxlen) : na
isADXEnabledAndAboveThreshold = adxEnabled ? (adxsig > adxabove) : true
//Backtesting Time Period (Input.time not working as expected as of 03/30/2021. Giving odd start/end dates
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
useStartPeriodTime = input.bool(true, 'Start', group='Date Range', inline='Start Period')
startPeriodTime = input.time(timestamp('1 Jan 2019'), '', group='Date Range', inline='Start Period')
useEndPeriodTime = input.bool(true, 'End', group='Date Range', inline='End Period')
endPeriodTime = input.time(timestamp('31 Dec 2030'), '', group='Date Range', inline='End Period')
start = useStartPeriodTime ? startPeriodTime >= time : false
end = useEndPeriodTime ? endPeriodTime <= time : false
calcPeriod = not start and not end
// Trade Direction
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tradeDirection = input.string('Long and Short', title='Trade Direction', options=['Long and Short', 'Long Only', 'Short Only'], group='Trade Direction')
// Percent as Points
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
per(pcnt) =>
strategy.position_size != 0 ? math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na)
// Take profit 1
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp1 = input.float(title='Take Profit 1 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 1')
q1 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 1')
// Take profit 2
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp2 = input.float(title='Take Profit 2 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 2')
q2 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 2')
// Take profit 3
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp3 = input.float(title='Take Profit 3 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 3')
q3 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 3')
// Take profit 4
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp4 = input.float(title='Take Profit 4 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit')
/// Stop Loss
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
stoplossPercent = input.float(title='Stop Loss (%)', defval=999, minval=0.01, group='Stop Loss') * 0.01
slLongClose = close < strategy.position_avg_price * (1 - stoplossPercent)
slShortClose = close > strategy.position_avg_price * (1 + stoplossPercent)
/// Leverage
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
leverage = input.float(1, 'Leverage', step=.5, group='Leverage')
contracts = math.min(math.max(.000001, strategy.equity / close * leverage), 1000000000)
/// Trade State Management
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
isInLongPosition = strategy.position_size > 0
isInShortPosition = strategy.position_size < 0
/// ProfitView Alert Syntax String Generation
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
alertSyntaxPrefix = input.string(defval='CRYPTANEX_99FTX_Strategy-Name-Here', title='Alert Syntax Prefix', group='ProfitView Alert Syntax')
alertSyntaxBase = alertSyntaxPrefix + '\n#' + str.tostring(open) + ',' + str.tostring(high) + ',' + str.tostring(low) + ',' + str.tostring(close) + ',' + str.tostring(volume) + ','
/// Trade Execution
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
longConditionCalc = (longCondition and isADXEnabledAndAboveThreshold)
shortConditionCalc = (shortCondition and isADXEnabledAndAboveThreshold)
if calcPeriod
if longConditionCalc and tradeDirection != 'Short Only' and isInLongPosition == false
strategy.entry('Long', strategy.long, qty=contracts)
alert(message=alertSyntaxBase + 'side:long', freq=alert.freq_once_per_bar_close)
if shortConditionCalc and tradeDirection != 'Long Only' and isInShortPosition == false
strategy.entry('Short', strategy.short, qty=contracts)
alert(message=alertSyntaxBase + 'side:short', freq=alert.freq_once_per_bar_close)
//Inspired from Multiple %% profit exits example by adolgo https://www.tradingview.com/script/kHhCik9f-Multiple-profit-exits-example/
strategy.exit('TP1', qty_percent=q1, profit=per(tp1))
strategy.exit('TP2', qty_percent=q2, profit=per(tp2))
strategy.exit('TP3', qty_percent=q3, profit=per(tp3))
strategy.exit('TP4', profit=per(tp4))
strategy.close('Long', qty_percent=100, comment='SL Long', when=slLongClose)
strategy.close('Short', qty_percent=100, comment='SL Short', when=slShortClose)
strategy.close_all(when=closeLongCondition or closeShortCondition, comment='Close Postion')
/// Dashboard
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Inspired by https://www.tradingview.com/script/uWqKX6A2/ - Thanks VertMT
showDashboard = input.bool(group="Dashboard", title="Show Dashboard", defval=true)
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
_cellText = _title + "\n" + _value
table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=size.auto)
// Draw dashboard table
if showDashboard
var bgcolor = color.new(color.black,0)
// Keep track of Wins/Losses streaks
newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
varip int winRow = 0
varip int lossRow = 0
varip int maxWinRow = 0
varip int maxLossRow = 0
if newWin
lossRow := 0
winRow := winRow + 1
if winRow > maxWinRow
maxWinRow := winRow
if newLoss
winRow := 0
lossRow := lossRow + 1
if lossRow > maxLossRow
maxLossRow := lossRow
// Prepare stats table
var table dashTable = table.new(position.bottom_right, 1, 15, border_width=1)
if barstate.islastconfirmedhistory
// Update table
dollarReturn = strategy.netprofit
f_fillCell(dashTable, 0, 0, "Start:", str.format("{0,date,long}", strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.closedtrades.entry_time(0))
f_fillCell(dashTable, 0, 1, "End:", str.format("{0,date,long}", strategy.opentrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.opentrades.entry_time(0))
_profit = (strategy.netprofit / strategy.initial_capital) * 100
f_fillCell(dashTable, 0, 2, "Net Profit:", str.tostring(_profit, '##.##') + "%", _profit > 0 ? color.green : color.red, color.white)
_numOfDaysInStrategy = (strategy.opentrades.entry_time(0) - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24)
f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit / _numOfDaysInStrategy, '#########################.#####')+"%", _profit > 0 ? color.green : color.red, color.white)
_winRate = ( strategy.wintrades / strategy.closedtrades ) * 100
f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? color.red : _winRate < 75 ? #999900 : color.green, color.white)
f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? color.green : color.red, color.white)
f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white)
f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white)
f_fillCell(dashTable, 0, 9, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white) |
Flying Dragon Trend Strategy | https://www.tradingview.com/script/PdZVLGJC-Flying-Dragon-Trend-Strategy/ | MarkoP010 | https://www.tradingview.com/u/MarkoP010/ | 248 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MarkoP010 2023
//@version=5
//The basic idea of the strategy is to select the best set of MAs, types, lenghts and offsets, which draws red trend bands for downtrend (and green for uptrend).
//Strategy executes by selected risk level either when there is MA crossover with price (Leading MA Offset1 on Highest risk level, Lagging MA on Low risk level) or three bands with the same color at the same time (on Lowest risk level, Leading MA Offset1 crossover with Lagging MA).
//Strategy plots user selectable Moving Average lines, a colored trend band between the MA lines and pivot indicators. The trend bands can be turned off individually if required. Also pivot indicators can be turned off if required.
//The Offset option shifts the selected MA with the set number of steps to the right. That is where the Magic happens and the Dragon roars!
//Strategy version history:
//Version 1 - Initial script
//Version 2 - Bug fix for Lowest risk level to show the indicator
//Version 3 - Updated graph picture
//Version 4 - Alert function and pivot indicators added, alerts are enabled when indicators are on. Inlining the code with the corresponding indicator.
strategy("Flying Dragon Trend Strategy", shorttitle="Flying Dragon Trend Strategy", overlay=true, pyramiding=3, initial_capital=100000, default_qty_type=strategy.percent_of_equity, default_qty_value=5, commission_type=strategy.commission.cash_per_order, commission_value=10, calc_on_order_fills=false, process_orders_on_close=true)
//Moving Averages function
MA(source, length, type) =>
type == "EMA" ? ta.ema(source, length) :
type == "HMA" ? ta.hma(source, length) :
type == "RMA" ? ta.rma(source, length) :
type == "SMA" ? ta.sma(source, length) :
type == "SWMA" ? ta.swma(source) :
type == "VWMA" ? ta.vwma(source, length) :
type == "WMA" ? ta.wma(source, length) :
na
//Strategy options
strDirection = input.string(defval="Both", title="Strategy Direction", options=["Both", "Long", "Short"], group="Strategy Options") //Strategy direction selector by DashTrader
strSelection = strDirection == "Long" ? strategy.direction.long : strDirection == "Short" ? strategy.direction.short : strategy.direction.all //Strategy direction selector by DashTrader
strategy.risk.allow_entry_in(strSelection)
riskLevel = input.string(defval="Medium", title="Risk Level", options=["Highest", "High", "Medium", "Low", "Lowest"], inline="Options", group="Strategy Options")
indicatorsOn = input(defval=true, title="Indicators", inline="Options", tooltip="Turn on or off pivot indicators. Strategy execution criteria. When risk level Highest then Leading MA Offset1 crossover with price triggers the indicator and executes the strategy, when Low then Lagging MA crossover with price, when Lowest then all the Bands are the same color (Leading MA Offset1 crossover with Lagging MA). Alerts are enabled when indicators are on. Create Alert on selected equity and timeframe, select on Condition this strategy and alert criteria (for example: Alert () function calls only), Create.", group="Strategy Options")
useStop = input(defval=false, title="Use Stop Loss", inline="SL", group="Strategy Options")
stopPrct = input.int(defval=10, title=" %", minval=0, maxval=100, step=1, inline="SL", group="Strategy Options") / 100
//Inputs
ma1Type = input.string(defval="HMA", title="", inline="MA1", options=["EMA", "HMA", "RMA", "SMA","SWMA", "VWMA", "WMA"], group="Leading Moving Average")
ma1Length = input.int(defval=35, title="",minval=1, inline="MA1", group="Leading Moving Average")
ma1Source = input(defval=close, title="", tooltip="For short timeframes, minutes to hours, instead of Default values try Lowest risk level and HMA75 with Offsets 0,1,4 and SMA12 with Offset 6.", inline="MA1", group="Leading Moving Average")
ma1Color = input(defval=color.purple, title="", inline="MA-1", group="Leading Moving Average")
ma1Offset = input.int(defval=0, title="Offset1 Steps", minval=0, maxval=10, step=1, tooltip="The Magic happens here! The offset to move the line to the right.", inline="MA-1", group="Leading Moving Average")
ma1 = MA(ma1Source, ma1Length, ma1Type)[ma1Offset]
ma2Color = input(defval=color.lime, title="", inline="MA-2", group="Leading Moving Average")
ma2Offset = input.int(defval=4, title="Offset2 Steps", minval=0, maxval=10, step=1, tooltip="The Magic happens here! The offset to move the line to the right.", inline="MA-2", group="Leading Moving Average")
ma2 = ma1[ma2Offset]
ma3Color = input(defval=color.aqua, title="", inline="MA-3", group="Leading Moving Average")
ma3Offset = input.int(defval=6, title="Offset3 Steps", minval=0, maxval=10, step=1, tooltip="The Magic happens here! The offset to move the line to the right.", inline="MA-3", group="Leading Moving Average")
ma3 = ma1[ma3Offset]
ma4Type = input.string(defval="SMA", title="", inline="MA4", options=["EMA", "HMA", "RMA", "SMA","SWMA", "VWMA", "WMA"], group="Lagging Moving Average")
ma4Length = input.int(defval=22, title="",minval=1, inline="MA4", group="Lagging Moving Average")
ma4Source = input(defval=close, title="", inline="MA4", group="Lagging Moving Average")
ma4Color = input(defval=color.yellow, title="", inline="MA-4", group="Lagging Moving Average")
ma4Offset = input.int(defval=2, title="Offset Steps", minval=0, maxval=10, step=1, tooltip="The Magic happens here! The offset to move the line to the right.", inline="MA-4", group="Lagging Moving Average")
ma4 = MA(ma4Source, ma4Length, ma4Type)[ma4Offset]
bandTransp = input.int(defval=60, title="Band Transparency", minval=20, maxval=80, step=10, group="Banding")
useBand1 = input(defval=true, title="Band 1", inline="Band", group="Banding")
band1Transp = useBand1 ? bandTransp : 100
band1clr = ma1 > ma2 ? color.new(#00ff00, transp=band1Transp) : color.new(#ff0000, transp=band1Transp)
useBand2 = input(defval=true, title="Band 2", inline="Band", group="Banding")
band2Transp = useBand2 ? bandTransp : 100
band2clr = ma1 > ma3 ? color.new(#00ff00, transp=band2Transp) : color.new(#ff0000, transp=band2Transp)
useBand3 = input(defval=true, title="Band 3", tooltip="Up trend green, down trend red. Colors get reversed if MA1 lenght is greater than MA2 lenght, or they are different type and MA2 quicker. In that case, just reverse your selections for MA1 and MA2, or let it be as is.", inline="Band", group="Banding")
band3Transp = useBand3 ? bandTransp : 100
band3clr = ma1 > ma4 ? color.new(#00ff00, transp=band3Transp) : color.new(#ff0000, transp=band3Transp)
//Graphs
piirto1 = plot(ma1, color = ma1Color, title="MA1")
piirto2 = plot(ma2, color = ma2Color, title="MA2")
piirto3 = plot(ma3, color = ma3Color, title="MA3")
piirto4 = plot(ma4, color = ma4Color, title="MA4")
fill(piirto1, piirto2, color=band1clr)
fill(piirto1, piirto3, color=band2clr)
fill(piirto1, piirto4, color=band3clr)
//Strategy entry and stop conditions, indicator plot conditions
longCondition = riskLevel == "Highest" ? ma1Source > ma1 : riskLevel == "High" ? ma1Source > ma2 : riskLevel == "Medium" ? ma1Source > ma3 : riskLevel == "Low" ? ma4Source > ma4 : riskLevel == "Lowest" ? ma1 > ma4 : na
shortCondition = riskLevel == "Highest" ? ma1Source < ma1 : riskLevel == "High" ? ma1Source < ma2 : riskLevel == "Medium" ? ma1Source < ma3 : riskLevel == "Low" ? ma4Source < ma4 : riskLevel == "Lowest" ? ma1 < ma4 : na
pivotUp = longCondition and shortCondition[1] and indicatorsOn ? true : na
pivotDown = shortCondition and longCondition[1] and indicatorsOn ? true : na
plotshape(pivotUp, title="Up", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small)
plotshape(pivotDown, title="Down", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small)
stopLprice = useStop == true ? strategy.position_avg_price * (1-stopPrct) : na
stopSprice = useStop == true ? strategy.position_avg_price * (1+stopPrct) : na
if longCondition
strategy.entry("Long",strategy.long)
strategy.exit("Long Stop", "Long", stop=stopLprice)
if shortCondition
strategy.entry("Short",strategy.short)
strategy.exit("Short Stop", "Short", stop=stopSprice)
//Alerts
if pivotUp
alertMessage = syminfo.ticker + ' - ' + timeframe.period + ": Pivot Up!"
alert(alertMessage, alert.freq_once_per_bar_close)
if pivotDown
alertMessage = syminfo.ticker + ' - ' + timeframe.period + ": Pivot Down!"
alert(alertMessage, alert.freq_once_per_bar_close)
//End
|
Strategy Myth-Busting #5 - POKI+GTREND+ADX - [MYN] | https://www.tradingview.com/script/B3J5Ledg-Strategy-Myth-Busting-5-POKI-GTREND-ADX-MYN/ | myncrypto | https://www.tradingview.com/u/myncrypto/ | 391 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © myn
//@version=5
strategy('Strategy Myth-Busting #5 - POKI+GTREND+ADX - [MYN]', max_bars_back=5000, overlay=true, pyramiding=0, initial_capital=1000, currency='USD', default_qty_type=strategy.percent_of_equity, default_qty_value=1.0, commission_value=0.075, use_bar_magnifier = false)
/////////////////////////////////////
//* Put your strategy logic below *//
/////////////////////////////////////
// Q0txMfU623Y
// Trading Rules
// 15m - 4 hours. Ideal 1 hour
// Poki
// Remove color plots
// Change ATR to 30
// Use Buy/Sell indicators as confirmation
// G-TREND
// Use color to confirm signal with POKI buy/sell indicators
// To get better results had to:
// Add an ADX confirmation
// Changed G-Trend to use OHLC4
// TP at 2% / SL 15%
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
//@version=5
//indicator('poki', shorttitle='poki', overlay=true)
// Parabolic SAR
startMult = input.int(3, minval=0, maxval=10, title='Start - Default = 2 - Multiplied by .01', group="POKI")
increment = input.int(3, minval=0, maxval=10, title='Step Setting (Sensitivity) - Default = 2 - Multiplied by .01')
maximum = input.int(3, minval=1, maxval=10, title='Maximum Step (Sensitivity) - Default = 2 - Multiplied by .10')
sus = input(true, 'Show Up Trending Parabolic Sar')
sds = input(true, 'Show Down Trending Parabolic Sar')
disc = input(false, title='Start and Step settings are *.01 so 2 = .02 etc, Maximum Step is *.10 so 2 = .2')
startCalc = startMult * .01
incrementCalc = increment * .01
maximumCalc = maximum * .10
sarUp = ta.sar(startCalc, incrementCalc, maximumCalc)
sarDown = ta.sar(startCalc, incrementCalc, maximumCalc)
colUp = close >= sarDown ? color.blue : na
colDown = close <= sarUp ? color.red : na
//plot(sus and sarUp ? sarUp : na, title='Up Trending SAR', style=plot.style_circles, linewidth=2, color=colUp)
//plot(sds and sarDown ? sarDown : na, title='Up Trending SAR', style=plot.style_circles, linewidth=2, color=colDown)
// Input
close_price = close[0]
len = input.int(defval=50, minval=1, title='Linear Regression length')
linear_reg = ta.linreg(close_price, len, 0)
linear_reg_prev = ta.linreg(close[1], len, 0)
slope = (linear_reg - linear_reg_prev) / timeframe.multiplier
length = input.int(title='Bollinger Length', defval=20, minval=1)
multiplier = input.float(title='Bollinger Deviation', defval=2, minval=1)
overbought = input.int(title='Overbought', defval=1, minval=1)
oversold = input.int(title='Oversold', defval=0, minval=0)
custom_timeframe = input(title='Use another Timeframe?', defval=false)
highTimeFrame = input.timeframe(title='Select The Timeframe', defval='60')
res1 = custom_timeframe ? highTimeFrame : timeframe.period
smabasis = ta.sma(close, length)
stdev = ta.stdev(close, length)
cierre = request.security(syminfo.tickerid, res1, close, barmerge.gaps_off)
alta = request.security(syminfo.tickerid, res1, high, barmerge.gaps_off)
baja = request.security(syminfo.tickerid, res1, low, barmerge.gaps_off)
basis1 = request.security(syminfo.tickerid, res1, smabasis, barmerge.gaps_off)
stdevb = request.security(syminfo.tickerid, res1, stdev, barmerge.gaps_off)
dev = multiplier * stdevb // stdev(cierre, length)
upper = basis1 + dev
lower = basis1 - dev
bbr = (cierre - lower) / (upper - lower)
// plot(bbr)
// // MARCA LAS RESISTENCIAS
pintarojo = 0.0
pintarojo := nz(pintarojo[1])
pintarojo := bbr[1] > overbought and bbr < overbought ? alta[1] : nz(pintarojo[1])
//p = plot(pintarojo, color=color.new(color.red, 0), style=plot.style_circles, linewidth=2)
// // MARCA LOS SOPORTES
pintaverde = 0.0
pintaverde := nz(pintaverde[1])
pintaverde := bbr[1] < oversold and bbr > oversold ? baja[1] : nz(pintaverde[1])
//g = plot(pintaverde, color=color.new(color.blue, 0), style=plot.style_circles, linewidth=2)
//
method = input.string(defval='Traditional', options=['ATR', 'Traditional', 'Part of Price'], title='Renko Assignment Method')
methodvalue = input.float(defval=29, minval=0, title='Value')
pricesource = input.string(defval='Close', options=['Close', 'Open / Close', 'High / Low'], title='Price Source')
useClose = pricesource == 'Close'
useOpenClose = pricesource == 'Open / Close' or useClose
useTrueRange = input.string(defval='Auto', options=['Always', 'Auto', 'Never'], title='Use True Range instead of Volume')
isOscillating = input(defval=true, title='Oscillating')
normalize = input(defval=false, title='Normalize')
vol = useTrueRange == 'Always' or useTrueRange == 'Auto' and na(volume) ? ta.tr : volume
op = useClose ? close : open
hi = useOpenClose ? close >= op ? close : op : high
lo = useOpenClose ? close <= op ? close : op : low
if method == 'ATR'
methodvalue := ta.atr(math.round(methodvalue))
methodvalue
if method == 'Part of Price'
methodvalue := close / methodvalue
methodvalue
currclose = float(na)
prevclose = nz(currclose[1])
prevhigh = prevclose + methodvalue
prevlow = prevclose - methodvalue
currclose := hi > prevhigh ? hi : lo < prevlow ? lo : prevclose
direction = int(na)
direction := currclose > prevclose ? 1 : currclose < prevclose ? -1 : nz(direction[1])
directionHasChanged = ta.change(direction) != 0
directionIsUp = direction > 0
directionIsDown = direction < 0
barcount = 1
barcount := not directionHasChanged and normalize ? barcount[1] + barcount : barcount
vol := not directionHasChanged ? vol[1] + vol : vol
res = barcount > 1 ? vol / barcount : vol
x = isOscillating and directionIsDown ? -res : res
//
z = input(title='period', defval=32)
n2ma = 2 * ta.wma(close, math.round(z / 2))
nma = ta.wma(close, z)
diff = n2ma - nma
sqn = math.round(math.sqrt(z))
n2ma1 = 2 * ta.wma(close[1], math.round(z / 2))
nma1 = ta.wma(close[1], z)
diff1 = n2ma1 - nma1
sqn1 = math.round(math.sqrt(z))
n1 = ta.wma(diff, sqn)
n2 = ta.wma(diff1, sqn)
c = n1 > n2 ? color.green : color.red
// Conditions
longCondPOKI = bool(na)
shortCondPOKI = bool(na)
longCondPOKI := ta.crossover(x, 0)
shortCondPOKI := ta.crossunder(x, 0)
// Count your long short conditions for more control with Pyramiding
// sectionLongs = 0
// sectionLongs := nz(sectionLongs[1])
// sectionShorts = 0
// sectionShorts := nz(sectionShorts[1])
// if longCond
// sectionLongs += 1
// sectionShorts := 0
// sectionShorts
// if shortCond
// sectionLongs := 0
// sectionShorts += 1
// sectionShorts
// Pyramiding
// pyrl = 1
// These check to see your signal and cross references it against the pyramiding settings above
// longCondition = longCond and sectionLongs <= pyrl
// shortCondition = shortCond and sectionShorts <= pyrl
// Get the price of the last opened long or short
// last_open_longCondition = float(na)
// last_open_shortCondition = float(na)
// last_open_longCondition := longCondition ? open : nz(last_open_longCondition[1])
// last_open_shortCondition := shortCondition ? open : nz(last_open_shortCondition[1])
// // Check if your last postion was a long or a short
// last_longCondition = float(na)
// last_shortCondition = float(na)
// last_longCondition := longCondition ? time : nz(last_longCondition[1])
// last_shortCondition := shortCondition ? time : nz(last_shortCondition[1])
// in_longCondition = last_longCondition > last_shortCondition
// in_shortCondition = last_shortCondition > last_longCondition
// // Take profit
// isTPl = input(false, 'Take Profit Long')
// isTPs = input(false, 'Take Profit Short')
// tp = input.float(2, 'Take Profit %')
// long_tp = isTPl and ta.crossover(high, (1 + tp / 100) * last_open_longCondition) and longCondition == 0 and in_longCondition == 1
// short_tp = isTPs and ta.crossunder(low, (1 - tp / 100) * last_open_shortCondition) and shortCondition == 0 and in_shortCondition == 1
// // Stop Loss
// isSLl = input(false, 'Stop Loss Long')
// isSLs = input(false, 'Stop Loss Short')
// sl = 0.0
// sl := input.float(3, 'Stop Loss %')
// long_sl = isSLl and ta.crossunder(low, (1 - sl / 100) * last_open_longCondition) and longCondition == 0 and in_longCondition == 1
// short_sl = isSLs and ta.crossover(high, (1 + sl / 100) * last_open_shortCondition) and shortCondition == 0 and in_shortCondition == 1
// // Create a single close for all the different closing conditions.
// long_close = long_tp or long_sl ? 1 : 0
// short_close = short_tp or short_sl ? 1 : 0
// // Get the time of the last close
// last_long_close = float(na)
// last_short_close = float(na)
// last_long_close := long_close ? time : nz(last_long_close[1])
// last_short_close := short_close ? time : nz(last_short_close[1])
//
showZones = input(true, title='Show Bullish/Bearish Zones')
// bullish signal rule:
bullishRule = n1 > linear_reg
// bearish signal rule:
bearishRule = n1 <= linear_reg
// current trading State
ruleState = 0
ruleState := bullishRule ? 1 : bearishRule ? -1 : nz(ruleState[1])
//bgcolor(showZones ? ruleState == 1 ? color.blue : ruleState == -1 ? color.red : color.gray : na, title=' Bullish/Bearish Zones', transp=90)
// Alerts & Signals
// bton(b) =>
// b ? 1 : 0
plotshape(longCondPOKI, title='Buy Signal', text='B', style=shape.triangleup, location=location.belowbar, color=color.new(color.green, 0), editable=false)
plotshape(shortCondPOKI, title='Sell Signal', text='S', style=shape.triangledown, location=location.abovebar, color=color.new(color.red, 0), editable=false)
//plotshape(long_tp and last_longCondition > nz(last_long_close[1]), text='TP', title='Take Profit Long', style=shape.triangledown, location=location.abovebar, color=color.new(color.red, 0), editable=false)
//plotshape(short_tp and last_shortCondition > nz(last_short_close[1]), text='TP', title='Take Profit Short', style=shape.triangleup, location=location.belowbar, color=color.new(color.lime, 0), editable=false)
//ltp = long_tp and last_longCondition > nz(last_long_close[1]) ? (1 + tp / 100) * last_open_longCondition : na
//plot(ltp, style=plot.style_cross, linewidth=3, color=color.new(color.white, 0), editable=false)
//stp = short_tp and last_shortCondition > nz(last_short_close[1]) ? (1 - tp / 100) * last_open_shortCondition : na
//plot(stp, style=plot.style_cross, linewidth=3, color=color.new(color.white, 0), editable=false)
//plotshape(long_sl and last_longCondition > nz(last_long_close[1]), text='SL', title='Stop Loss Long', style=shape.triangledown, location=location.abovebar, color=color.new(color.red, 0), editable=false)
//plotshape(short_sl and last_shortCondition > nz(last_short_close[1]), text='SL', title='Stop Loss Short', style=shape.triangleup, location=location.belowbar, color=color.new(color.lime, 0), editable=false)
//lsl = long_sl and last_longCondition > nz(last_long_close[1]) ? (1 - sl / 100) * last_open_longCondition : na
//plot(lsl, style=plot.style_cross, linewidth=3, color=color.new(color.white, 0), editable=false)
//ssl = short_sl and last_shortCondition > nz(last_short_close[1]) ? (1 + sl / 100) * last_open_shortCondition : na
//plot(ssl, style=plot.style_cross, linewidth=3, color=color.new(color.white, 0), editable=false)
// alertcondition(bton(longCondition), title='Buy Alert')
// alertcondition(bton(shortCondition), title='Sell Alert')
// alertcondition(bton(long_tp and last_longCondition > nz(last_long_close[1])), title='Take Profit Long')
// alertcondition(bton(short_tp and last_shortCondition > nz(last_short_close[1])), title='Take Profit Short')
// alertcondition(bton(long_sl and last_longCondition > nz(last_long_close[1])), title='Stop Loss Long')
// alertcondition(bton(short_sl and last_shortCondition > nz(last_short_close[1])), title='Stop Loss Short')
/// G-Channel Trend Detection
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
//@version=5
//Full credit to AlexGrover: https://www.tradingview.com/script/fIvlS64B-G-Channels-Efficient-Calculation-Of-Upper-Lower-Extremities/
//indicator('G-Channel Trend Detection', shorttitle='G-Trend', overlay=true)
lengthG = input(100, group="G-Channel Trend Detection")
src = input(ohlc4)
//----
a = 0.
b = 0.
a := math.max(src, nz(a[1])) - nz(a[1] - b[1]) / lengthG
b := math.min(src, nz(b[1])) + nz(a[1] - b[1]) / lengthG
avg = math.avg(a, b)
//----
crossup = b[1] < close[1] and b > close
crossdn = a[1] < close[1] and a > close
bullish = ta.barssince(crossdn) <= ta.barssince(crossup)
cG = bullish ? color.lime : color.red
//plot(a,"Upper",color=color.blue,linewidth=2,transp=100)
//plot(b,"Lower",color=color.blue,linewidth=2,transp=100)
p1 = plot(avg, 'Average', color=cG, linewidth=1, transp=100)
p2 = plot(close, 'Close price', color=cG, linewidth=1, transp=100)
fill(p1, p2, color=cG, transp=90)
//showcross = input(true)
//plotshape(showcross and not bullish and bullish[1] ? avg : na, location=location.absolute, style=shape.labeldown, color=color.new(color.red, 0), size=size.tiny, text='Sell', textcolor=color.new(#ffffff, 0), offset=-1)
//plotshape(showcross and bullish and not bullish[1] ? avg : na, location=location.absolute, style=shape.labelup, color=color.new(color.lime, 0), size=size.tiny, text='Buy', textcolor=color.new(#ffffff, 0), offset=-1)
longCondGTrend = bullish
shortCondGTrend = not bullish
//////////////////////////////////////
//* Put your strategy rules below *//
/////////////////////////////////////
longCondition = longCondPOKI and longCondGTrend
shortCondition = shortCondPOKI and shortCondGTrend
//define as 0 if do not want to use
closeLongCondition = 0
closeShortCondition = 0
// ADX
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
adxEnabled = input.bool(defval = true , title = "Average Directional Index (ADX)", tooltip = "", group ="ADX" )
adxlen = input(14, title="ADX Smoothing", group="ADX")
adxdilen = input(14, title="DI Length", group="ADX")
adxabove = input(25, title="ADX Threshold", group="ADX")
adxdirmov(len) =>
adxup = ta.change(high)
adxdown = -ta.change(low)
adxplusDM = na(adxup) ? na : (adxup > adxdown and adxup > 0 ? adxup : 0)
adxminusDM = na(adxdown) ? na : (adxdown > adxup and adxdown > 0 ? adxdown : 0)
adxtruerange = ta.rma(ta.tr, len)
adxplus = fixnan(100 * ta.rma(adxplusDM, len) / adxtruerange)
adxminus = fixnan(100 * ta.rma(adxminusDM, len) / adxtruerange)
[adxplus, adxminus]
adx(adxdilen, adxlen) =>
[adxplus, adxminus] = adxdirmov(adxdilen)
adxsum = adxplus + adxminus
adx = 100 * ta.rma(math.abs(adxplus - adxminus) / (adxsum == 0 ? 1 : adxsum), adxlen)
adxsig = adxEnabled ? adx(adxdilen, adxlen) : na
isADXEnabledAndAboveThreshold = adxEnabled ? (adxsig > adxabove) : true
//Backtesting Time Period (Input.time not working as expected as of 03/30/2021. Giving odd start/end dates
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
useStartPeriodTime = input.bool(true, 'Start', group='Date Range', inline='Start Period')
startPeriodTime = input.time(timestamp('1 Jan 2019'), '', group='Date Range', inline='Start Period')
useEndPeriodTime = input.bool(true, 'End', group='Date Range', inline='End Period')
endPeriodTime = input.time(timestamp('31 Dec 2030'), '', group='Date Range', inline='End Period')
start = useStartPeriodTime ? startPeriodTime >= time : false
end = useEndPeriodTime ? endPeriodTime <= time : false
calcPeriod = not start and not end
// Trade Direction
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tradeDirection = input.string('Long and Short', title='Trade Direction', options=['Long and Short', 'Long Only', 'Short Only'], group='Trade Direction')
// Percent as Points
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
per(pcnt) =>
strategy.position_size != 0 ? math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na)
// Take profit 1
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp1 = input.float(title='Take Profit 1 - Target %', defval=2, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 1')
q1 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 1')
// Take profit 2
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp2 = input.float(title='Take Profit 2 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 2')
q2 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 2')
// Take profit 3
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp3 = input.float(title='Take Profit 3 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 3')
q3 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 3')
// Take profit 4
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp4 = input.float(title='Take Profit 4 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit')
/// Stop Loss
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
stoplossPercent = input.float(title='Stop Loss (%)', defval=9, minval=0.01, group='Stop Loss') * 0.01
slLongClose = close < strategy.position_avg_price * (1 - stoplossPercent)
slShortClose = close > strategy.position_avg_price * (1 + stoplossPercent)
/// Leverage
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
leverage = input.float(1, 'Leverage', step=.5, group='Leverage')
contracts = math.min(math.max(.000001, strategy.equity / close * leverage), 1000000000)
/// Trade State Management
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
isInLongPosition = strategy.position_size > 0
isInShortPosition = strategy.position_size < 0
/// ProfitView Alert Syntax String Generation
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
alertSyntaxPrefix = input.string(defval='CRYPTANEX_99FTX_Strategy-Name-Here', title='Alert Syntax Prefix', group='ProfitView Alert Syntax')
alertSyntaxBase = alertSyntaxPrefix + '\n#' + str.tostring(open) + ',' + str.tostring(high) + ',' + str.tostring(low) + ',' + str.tostring(close) + ',' + str.tostring(volume) + ','
/// Trade Execution
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
longConditionCalc = (longCondition and isADXEnabledAndAboveThreshold)
shortConditionCalc = (shortCondition and isADXEnabledAndAboveThreshold)
if calcPeriod
if longConditionCalc and tradeDirection != 'Short Only' and isInLongPosition == false
strategy.entry('Long', strategy.long, qty=contracts)
alert(message=alertSyntaxBase + 'side:long', freq=alert.freq_once_per_bar_close)
if shortConditionCalc and tradeDirection != 'Long Only' and isInShortPosition == false
strategy.entry('Short', strategy.short, qty=contracts)
alert(message=alertSyntaxBase + 'side:short', freq=alert.freq_once_per_bar_close)
//Inspired from Multiple %% profit exits example by adolgo https://www.tradingview.com/script/kHhCik9f-Multiple-profit-exits-example/
strategy.exit('TP1', qty_percent=q1, profit=per(tp1))
strategy.exit('TP2', qty_percent=q2, profit=per(tp2))
strategy.exit('TP3', qty_percent=q3, profit=per(tp3))
strategy.exit('TP4', profit=per(tp4))
strategy.close('Long', qty_percent=100, comment='SL Long', when=slLongClose)
strategy.close('Short', qty_percent=100, comment='SL Short', when=slShortClose)
strategy.close_all(when=closeLongCondition or closeShortCondition, comment='Close Postion')
/// Dashboard
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Inspired by https://www.tradingview.com/script/uWqKX6A2/ - Thanks VertMT
showDashboard = input.bool(group="Dashboard", title="Show Dashboard", defval=true)
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
_cellText = _title + "\n" + _value
table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=size.auto)
// Draw dashboard table
if showDashboard
var bgcolor = color.new(color.black,0)
// Keep track of Wins/Losses streaks
newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
varip int winRow = 0
varip int lossRow = 0
varip int maxWinRow = 0
varip int maxLossRow = 0
if newWin
lossRow := 0
winRow := winRow + 1
if winRow > maxWinRow
maxWinRow := winRow
if newLoss
winRow := 0
lossRow := lossRow + 1
if lossRow > maxLossRow
maxLossRow := lossRow
// Prepare stats table
var table dashTable = table.new(position.bottom_right, 1, 15, border_width=1)
if barstate.islastconfirmedhistory
// Update table
dollarReturn = strategy.netprofit
f_fillCell(dashTable, 0, 0, "Start:", str.format("{0,date,long}", strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.closedtrades.entry_time(0))
f_fillCell(dashTable, 0, 1, "End:", str.format("{0,date,long}", strategy.opentrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.opentrades.entry_time(0))
_profit = (strategy.netprofit / strategy.initial_capital) * 100
f_fillCell(dashTable, 0, 2, "Net Profit:", str.tostring(_profit, '##.##') + "%", _profit > 0 ? color.green : color.red, color.white)
_numOfDaysInStrategy = (strategy.opentrades.entry_time(0) - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24)
f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit / _numOfDaysInStrategy, '#########################.#####')+"%", _profit > 0 ? color.green : color.red, color.white)
_winRate = ( strategy.wintrades / strategy.closedtrades ) * 100
f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? color.red : _winRate < 75 ? #999900 : color.green, color.white)
f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? color.green : color.red, color.white)
f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white)
f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white)
f_fillCell(dashTable, 0, 9, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white) |
supertrend with multiple filter strategy | https://www.tradingview.com/script/QVqti4l2-supertrend-with-multiple-filter-strategy/ | mathlabel | https://www.tradingview.com/u/mathlabel/ | 394 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mathlabel
//@version=5
strategy("My strategy", overlay=true, default_qty_type = strategy.percent_of_equity, default_qty_value=100,margin_long= 50, margin_short=50)
//
////////////////////////////////////////////////////////////////////////////////
// BACKTESTING RANGE
// From Date Inputs
fromDay = input.int(defval=1, title='From Day', minval=1, maxval=31)
fromMonth = input.int(defval=1, title='From Month', minval=1, maxval=12)
fromYear = input.int(defval=2019, title='From Year', minval=1970)
fromHour =input.int(defval = 1, title = 'from hour',minval = 0 ,maxval =24 )
fromMinute=input.int(defval = 1, title = 'from minute',minval = 0 ,maxval =60 )
fromSecond=input.int(defval = 1, title = 'from second',minval = 0 ,maxval =60 )
// To Date Inputs
toDay = input.int(defval=1, title='To Day', minval=1, maxval=31)
toMonth = input.int(defval=1, title='To Month', minval=1, maxval=12)
toYear = input.int(defval=2100, title='To Year', minval=1970)
// Calculate start/end date and time condition
startDate = timestamp(fromYear, fromMonth, fromDay,fromHour, fromMinute,fromSecond)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
time_cond = time >= startDate and time <= finishDate
//////////////////////////////////////////////////
long_only=input.bool(false)
short_only=input.bool(false)
longLossPerc = input.float(title='Long Stop Loss (%)', minval=0.0, step=0.01, defval=1) * 0.01
shortLossPerc = input.float(title='Short Stop Loss (%)', minval=0.0, step=0.01, defval=1) * 0.01
use_supertrend_filter=input.bool(true)
atrPeriod = input(10, "supertrend ATR Length")
factor = input.float(3.0, "supertrend Factor", step = 0.01)
use_stochastic_filter = input.bool(false)
stochlenght= input(14,'stochlenght')
oversold_level = input(title = ' stoch Oversold', defval = 20)
overbought_level = input(title = 'stoch Overbought', defval = 80)
use_supertrend2_filter=input.bool(false)
atrPeriod2 = input(7, "supertrend2 ATR Length")
factor2 = input.float(3, "supertrend2 Factor", step = 0.01)
use_supertrend3_filter=input.bool(false)
atrPeriod3 = input(11, "supertrend3 ATR Length")
factor3 = input.float(2, "supertrend3 Factor", step = 0.01)
use_cci_filter=input.bool(false)
cci_l = input(50, title='CCI Period Length')
atr_l = input(5, title=' CCI ATR Length')
use_vwap_filter=input.bool(false)
var anchor = input.string(defval = "Session", title="Anchor Period",
options=["Session", "Week", "Month", "Quarter", "Year", "Decade", "Century", "Earnings", "Dividends", "Splits"], group="VWAP Settings")
use_chaikin_money_flow_filter=input.bool(false)
length = input(20, title='chaikin lenght')
use_ema_cross_filter=input.bool(false)
shortlen = input.int(9, "Short MA Length for cross filter", minval=1)
longlen = input.int(21, "Long MA Length for cross filter", minval=1)
use_ichimoku_filter=input.bool(false)
conversionPeriods = input.int(9, minval=1, title='ichimoku convertion periods')
basePeriods = input.int(26, minval=1, title = 'ichimoku base periods')
use_luxcandlepatternchannel_filter=input.bool(false)
lengthw = input.int(14, 'lux candlestick pattern Trend Length'
, minval = 0)
alpha = input.float(50, 'lux candlestick pattern Convergence'
, minval = 0
, maxval = 100)
smooth = input.int(7, 'lux candlestick pattern Smooth'
, minval = 1)
use_support_an_dresistance_break_filter=input.bool(false)
leftBars = input(15, title='support and resistance Left Bars ')
rightBars = input(15, title='support and resistance Right Bars')
use_mavilimw_filter=input.bool(false)
fmal = input(3,title = 'mavilimw fast ma')
smal = input(5,title = 'mavilimw slow ma')
use_mfi_filter=input.bool(false)
length1 = input.int(title="mfi Length", defval=14, minval=1, maxval=2000)
signalLength = input(title='mfi Signal Length', defval=9)
use_ift_cci_filter=input.bool(false)
ccilength = input(5, title = 'cci lenght')
wmalength =input(9, title = 'cci WMA lenght')
plottrama=input.bool(false, title="Show Lux TRAMA")
use_LUX_trama_filter=input.bool(false)
lengths = input(99,title='Trama lenght')
use_macd_filter=input.bool(false)
ma_fast=ta.sma(close,input(14,title='ma fast for macd filter'))
ma_slow=ta.sma(close,input(28, title='ma slowfor macd filter'))
use_ema200_filter= input.bool(false)
plotAverage = input.bool(true, title="Plot EMA200")
//exits
use_trailing_stop_loss=input.bool( false,title = 'use indicator exits (atr band, trailing atr or bollinger)?')
use_atr_bands_exits=input.bool(false)
stopLossFactor = input(2.0, "ATR Stop Loss Factor")
takeProfitFactor = input(1.5, "ATR Take Profit Factor")
atr = ta.atr(input(10, 'atr band period'))
use_trailing_atr_exits=input.bool(false)
Atr1 = input.int(defval=5, title='trailing Atr exit Period', minval=1, maxval=500)
Hhv1 = input.int(defval=10, title='trailing ATR exit HHV Period', minval=1, maxval=500)
Mult1 = input.float(defval=2.5, title='trailing exit ATR Multiplier', minval=0.1)
use_bollinger_exits=input.bool(false)
lengthss = input(20, title='bollinger lenght')
mult = input.float(2.0, minval=0.001, maxval=50, title="bollinger StdDev")
offset = input.int(0, "bollinger Offset", minval = -500, maxval = 500)
use_percent_base_trailing_stop_exits=input.bool(false,group = '% trailing stop loss')
trailStop = input.float(title=' traling Stop Loss (%)', minval=0.0, step=0.01, defval=1,group = '% trailing stop loss') * 0.01
enableTrailing = input.bool(false, 'Enable % take profit Trailing',group = '% trailing Take Profit')
longTakeProfitPerc2 = input.float(0.5, 'Long trailing Take Profit %', minval=0.01, step=0.01,group = '% trailing Take Profit') * 0.01
shortTakeProfitPerc2 = input.float(0.5, 'Short trailing Take Profit %', minval=0.01, step=0.01,group = '% trailing Take Profit') * 0.01
LtrailingTakeProfitDeviationPerc = input.float(defval = 1.0, title = 'long Trailing Take Profit Deviation %', minval = 0.01, maxval = 100, step = 0.01, tooltip = 'The step to follow the price when the take profit limit is reached.', group = '% trailing Take Profit') / 100
StrailingTakeProfitDeviationPerc = input.float(defval = 1.0, title = 'Short Trailing Take Profit Deviation %', minval = 0.01, maxval = 100, step = 0.01, tooltip = 'The step to follow the price when the take profit limit is reached.', group ='% trailing Take Profit') / 100
use_fix_perc_take_profit=input.bool(false, 'use a fix % take profit ',group = ' fixed % Take Profit')
longprofitPerc = input.float(title='fixed Long profit (%) if not using indicator exits', minval=0.0, step=0.01, defval=1,group = ' fixed % Take Profit') * 0.01
shortprofitPerc = input.float(title='fixed Short profit (%) if not using indicator exits', minval=0.0, step=0.01, defval=1,group = ' fixed % Take Profit') * 0.01
close_position_when_oposite_signal=input.bool(false)
// Calculate supertrend
[supertrend, direction] = ta.supertrend(factor, atrPeriod)
upTrend = plot(use_supertrend_filter? (direction < 0 ? supertrend : na) : na, "Up Trend", color = color.green, style=plot.style_linebr)
downTrend = plot(use_supertrend_filter ? (direction < 0? na : supertrend):na, "Down Trend", color = color.red, style=plot.style_linebr)
long_supertrend_filter= (direction < 0 ? supertrend : na)
short_supertrend_filter= (direction < 0? na : supertrend)
// Calculate supertrend 2
[supertrend2, direction2] = ta.supertrend(factor2, atrPeriod2)
upTrend2 = plot(use_supertrend2_filter? (direction2 < 0 ? supertrend2 : na) : na, "Up Trend", color = color.green, style=plot.style_linebr)
downTrend2 = plot(use_supertrend2_filter ? (direction2 < 0? na : supertrend2):na, "Down Trend", color = color.red, style=plot.style_linebr)
long_supertrend2_filter= (direction2 < 0 ? supertrend2 : na)
short_supertrend2_filter= (direction2 < 0? na : supertrend2)
// Calculate supertrend 3
[supertrend3, direction3] = ta.supertrend(factor3, atrPeriod3)
upTrend3 = plot(use_supertrend2_filter? (direction3 < 0 ? supertrend3 : na) : na, "Up Trend", color = color.green, style=plot.style_linebr)
downTrend3 = plot(use_supertrend2_filter ? (direction3 < 0? na : supertrend3):na, "Down Trend", color = color.red, style=plot.style_linebr)
long_supertrend3_filter= (direction3 < 0 ? supertrend3 : na)
short_supertrend3_filter= (direction3 < 0? na : supertrend3)
//--trama--
src =(close)
ama = 0.
hh = math.max(math.sign(ta.change(ta.highest(lengths))), 0)
ll = math.max(math.sign(ta.change(ta.lowest(lengths)) * -1), 0)
tc = math.pow(ta.sma(hh or ll ? 1 : 0, lengths), 2)
ama := nz(ama[1] + tc * (src - ama[1]), src)
plot(plottrama?ama : na, 'Plot', color.new(#ff1100, 0), 2)
long_LUX_trama_filter= (close > ama)
short_LUX_trama_filter= (close < ama)
// highest high
highest = ta.highest(high, stochlenght)
// lowest low
lowest = ta.lowest(low, stochlenght)
// stochastic oscillator
stochastic_K = ((close - lowest) / (highest - lowest)) * 100
stochastic_D = ta.sma(stochastic_K, 3)
long_stoch_filter =ta.crossover( stochastic_K , oversold_level) and stochastic_K[1] < oversold_level
short_stoch_filter = ta.crossunder(stochastic_K , overbought_level) and stochastic_K[1] > overbought_level
//ATR band upline and bottome line.
upline = open + (atr* takeProfitFactor)
bottomline = open -(atr*stopLossFactor)
plot(use_atr_bands_exits ? upline : na, color=color.white)
plot(use_atr_bands_exits ? bottomline:na, color=color.white)
// Calculate stop loss and take profit levels
stopLoss = stopLossFactor * atr
takeProfit = takeProfitFactor * atr
//input macd
[macdLine, signalLine, histLine]= ta.macd(close,12,26,9)
long_macd_filter= (macdLine > signalLine) and ta.crossover(ma_fast,ma_slow)
short_macd_filter= (macdLine < signalLine) and ta.crossunder(ma_fast,ma_slow)
// ema 200
ema1= ta.ema(close,1)
ema2= ta.ema(close,200)
barsincecrossup =ta.barssince(close >ema2)
barsincecrossdw=ta.barssince(close <ema2)
long_ema_filter = (close > ema2 and close[1] > ema2 )
short_ema_filter= (close<ema2 and close[1]<ema2)
plot(plotAverage ? ta.ema(close, 200) : na, title="Exponential Average")
// mfi
src1 = hlc3
mf = ta.mfi(src1, length1)
signal = ta.ema(mf, signalLength)
long_mfi_filter= ta.crossover(mf, signal) ? mf : na
short_mfi_filter= ta.crossunder(mf, signal) ? mf : na
//cci
level = 0
sd_length = 20
cci = ta.cci(src, cci_l)
atr2 = ta.atr(atr_l)
var st = 0.
if cci >= level
st := low - atr
st
if cci <= level
st := high + atr
st
var tu = 0.
var td = 0.
var optimal_line = 0.
if cci >= level and cci[1] < level
tu := td[1]
tu
if cci <= level and cci[1] > level
td := tu[1]
td
if cci > level
tu := low - atr2
if tu < tu[1] and cci[1] >= level
tu := tu[1]
tu
if cci < level
td := high + atr2
if td > td[1] and cci[1] <= level
td := td[1]
td
optimal_line := math.max(tu, td)
// Creating a Price Channel,
avg_st8 = ta.ema(st, 8)
avg_st13 = ta.ema(st, 13)
avg_st21 = ta.ema(st, 21)
avg_st34 = ta.ema(st, 21)
avg_st55 = ta.ema(st, 55)
avg_st89 = ta.ema(st, 89)
avg_st144 = ta.ema(st, 144)
avg_st233 = ta.ema(st, 233)
average_weighting = (optimal_line + avg_st8 + avg_st13 + avg_st21 + avg_st34 + avg_st55 + avg_st89 + avg_st144 + avg_st233) / 9
basis = ta.sma(average_weighting, sd_length)
devs = ta.stdev(average_weighting, sd_length)
upperS = basis + devs
lowerS = basis - devs
plot(use_cci_filter ? basis: na, 'Basis', color=color.new(#872323, 0))
p3 = plot(use_cci_filter ? upperS : na, 'UpperS', color=color.new(color.teal, 0))
p4 = plot(use_cci_filter ? lowerS: na ,'LowerS', color=color.new(color.teal, 0))
long_cci_filter= ta.crossover(close,upperS)
short_cci_filter= ta.crossunder(close,lowerS)
//wvap
srcv = hlc3
stdevMult_1 = (0)
if barstate.islast and ta.cum(volume) == 0
runtime.error("No volume is provided by the data vendor.")
new_earnings = request.earnings(syminfo.tickerid, earnings.actual, barmerge.gaps_on, barmerge.lookahead_on, ignore_invalid_symbol=true)
new_dividends = request.dividends(syminfo.tickerid, dividends.gross, barmerge.gaps_on, barmerge.lookahead_on, ignore_invalid_symbol=true)
new_split = request.splits(syminfo.tickerid, splits.denominator, barmerge.gaps_on, barmerge.lookahead_on, ignore_invalid_symbol=true)
isNewPeriod = switch anchor
"Earnings" => not na(new_earnings)
"Dividends" => not na(new_dividends)
"Splits" => not na(new_split)
"Session" => timeframe.change("D")
"Week" => timeframe.change("W")
"Month" => timeframe.change("M")
"Quarter" => timeframe.change("3M")
"Year" => timeframe.change("12M")
"Decade" => timeframe.change("12M") and year % 10 == 0
"Century" => timeframe.change("12M") and year % 100 == 0
=> false
isEsdAnchor = anchor == "Earnings" or anchor == "Dividends" or anchor == "Splits"
if na(src[1]) and not isEsdAnchor
isNewPeriod := true
float vwapValue = na
float upperBandValue1 = na
float lowerBandValue1 = na
float upperBandValue2 = na
float lowerBandValue2 = na
float upperBandValue3 = na
float lowerBandValue3 = na
if not (timeframe.isdwm)
[_vwap, _stdevUpper, _] = ta.vwap(src, isNewPeriod, 1)
vwapValue := _vwap
stdevAbs = _stdevUpper - _vwap
upperBandValue1 := _vwap + stdevAbs * stdevMult_1
lowerBandValue1 := _vwap - stdevAbs * stdevMult_1
plot(use_vwap_filter ?vwapValue : na, title="VWAP", color=#2962FF)
long_vwap_filter= close > vwapValue
short_vwap_filter = close < vwapValue
//chaikin money flow
var cumVol = 0.
cumVol += nz(volume)
if barstate.islast and cumVol == 0
runtime.error("No volume is provided by the data vendor.")
ad = close==high and close==low or high==low ? 0 : ((2*close-low-high)/(high-low))*volume
mf2 = math.sum(ad, length) / math.sum(volume, length)
long_chaikin_money_flow_filter= mf2> 0
short_chaikin_money_flow_filter = mf2<0
// ema cross
ema4=ta.ema(close,shortlen)
ema5=ta.ema(close,longlen)
long_ema_cross_filter= ta.crossover(ema4,ema5)
short_ema_cross_filter=ta.crossunder(ema4,ema5)
plot(use_ema_cross_filter? ema4 : na)
plot(use_ema_cross_filter ? ema5 : na)
//ichimku cloud
middleDonchian(Length) =>
lower = ta.lowest(Length)
upper = ta.highest(Length)
math.avg(upper, lower)
laggingSpan2Periods = 52
displacement = 26
Tenkan = middleDonchian(conversionPeriods)
Kijun = middleDonchian(basePeriods)
xChikou = close
SenkouA = middleDonchian(laggingSpan2Periods)
SenkouB = (Tenkan[basePeriods] + Kijun[basePeriods]) / 2
plot(use_ichimoku_filter ? Tenkan : na, color=color.new(color.red, 0), title='Tenkan')
plot(use_ichimoku_filter ? Kijun : na, color=color.new(color.blue, 0), title='Kijun')
plot(use_ichimoku_filter ? xChikou : na, color=color.new(color.teal, 0), title='Chikou', offset=-displacement)
A = plot(use_ichimoku_filter ? SenkouA[displacement]: na, color=color.new(color.purple, 0), title='SenkouA')
B = plot(use_ichimoku_filter ? SenkouB : na, color=color.new(color.green, 0), title='SenkouB')
long_ichimoku_filter= close > SenkouA[displacement] and close> SenkouB
short_ichimoku_filter= close < SenkouA[displacement] and close< SenkouB
// lux candlestick pattern
//Settings
//-----------------------------------------------------------------------------{
//Patterns
enable_hammer = true
enable_ihammer = true
enable_shooting =true
enable_hanging = true
enable_bulleng = false
enable_beareng = false
enable_wm = true
enable_bm = true
//Style
bull_css = #0cb51a
avg_css =#ff5d00
bear_css = #ff1100
fade = 200
//-----------------------------------------------------------------------------}
//Variables/Functions
//-----------------------------------------------------------------------------{
n = bar_index
o = open,h = high,l = low,c = close
atrw = ta.atr(20) / 2
stw = ta.stoch(c, c, c, lengthw)
downtrendw = stw < 50
uptrendw = stw > 50
d = math.abs(c - o)
lbl(y, txt, direction, tlt)=>
label.new( n, y, txt
, size = size.tiny
, style = direction == 1 ? label.style_cross : label.style_cross
, color = direction == 1 ? bull_css : bear_css
, textcolor = color.white
, tooltip = tlt )
//-----------------------------------------------------------------------------}
//Tooltips
//-----------------------------------------------------------------------------{
var hammer_tlt = "The hammer candlestick pattern is formed of a short body with a long lower wick, and is found at the bottom of a downward trend."
+ "\n" + "\nA hammer shows that although there were selling pressures during the day, ultimately a strong buying pressure drove the price back up."
var ihammer_tlt = "The inverted hammer is a similar pattern than the hammer pattern. The only difference being that the upper wick is long, while the lower wick is short."
+ "\n" + "\nIt indicates a buying pressure, followed by a selling pressure that was not strong enough to drive the market price down. The inverse hammer suggests that buyers will soon have control of the market."
var bulleng_tlt = "The bullish engulfing pattern is formed of two candlesticks. The first candle is a short red body that is completely engulfed by a larger green candle"
+ "\n" + "\nThough the second day opens lower than the first, the bullish market pushes the price up, culminating in an obvious win for buyers"
var wm_tlt = "The white marubozu is a single candles formation formed after a downtrend and indicating a bullish reversal."
+ "\n" + "\nThis candlestick has a long bullish body with no upper or lower shadows, reflecting a strong buying pressure."
var shooting_tlt = "The shooting star is the same shape as the inverted hammer, but is formed in an uptrend: it has a small lower body, and a long upper wick."
+ "\n" + "\nUsually, the market will gap slightly higher on opening and rally to an intra-day high before closing at a price just above the open – like a star falling to the ground."
var hanging_tlt = "The hanging man is the bearish equivalent of a hammer; it has the same shape but forms at the end of an uptrend."
+ "\n" + "\nIt indicates that there was a significant sell-off during the day, but that buyers were able to push the price up again. The large sell-off is often seen as an indication that the bulls are losing control of the market."
var beareng_tlt = "A bearish engulfing pattern occurs at the end of an uptrend. The first candle has a small green body that is engulfed by a subsequent long red candle."
+ "\n" + "\nIt signifies a peak or slowdown of price movement, and is a sign of an impending market downturn. The lower the second candle goes, the more significant the trend is likely to be."
var bm_tlt = "The black marubozu is a single candles formation formed after an uptrend and indicating a bearish reversal."
+ "\n" + "\nThis candlestick has a long bearish body with no upper or lower shadows, reflecting a strong selling pressure."
//-----------------------------------------------------------------------------}
//Pattern Rules
//-----------------------------------------------------------------------------{
hammer = downtrendw and math.min(o, c) - l > 2 * d and h - math.max(c, o) < d / 4
ihammer = downtrendw and h - math.max(o, c) > 2 * d and math.min(c, o) - l < d / 4
shooting = uptrendw and h - math.max(o, c) > 2 * d and math.min(c, o) - l < d / 4
hanging = uptrendw and math.min(o, c) - l > 2 * d and h - math.max(c, o) < d / 4
bulleng = downtrendw and c > o and c[1] < o[1] and c > o[1] and d > atr
beareng = uptrendw and c < o and c[1] > o[1] and c < o[1] and d > atr
wm = c > o and h - math.max(o, c) + math.min(o, c) - l < d / 10 and d > atr and downtrendw[1]
bm = c < o and h - math.max(o, c) + math.min(o, c) - l < d / 10 and d > atr and uptrendw[1]
//-----------------------------------------------------------------------------}
//Channel
//-----------------------------------------------------------------------------{
var max = h
var min = l
//Bullish Patterns
if hammer and use_luxcandlepatternchannel_filter
max += alpha / 100 * (c - max)
lbl(low, 'H', 1, hammer_tlt)
if ihammer and use_luxcandlepatternchannel_filter
max += alpha / 100 * (c - max)
lbl(low, 'IH', 1, ihammer_tlt)
if bulleng and enable_bulleng
max += alpha / 100 * (c - max)
lbl(low, 'BE', 1, bulleng_tlt)
if wm and use_luxcandlepatternchannel_filter
max += alpha / 100 * (c - max)
lbl(low, 'WM', 1, wm_tlt)
//Bearish Patterns
if shooting and use_luxcandlepatternchannel_filter
min += alpha / 100 * (c - min)
lbl(high, 'SS', 0, shooting_tlt)
if hanging and use_luxcandlepatternchannel_filter
min += alpha / 100 * (c - min)
lbl(high, 'HM', 0, hanging_tlt)
if beareng and enable_beareng
min += alpha / 100 * (c - min)
lbl(high, 'BE', 0, beareng_tlt)
if bm and use_luxcandlepatternchannel_filter
min += alpha / 100 * (c - min)
lbl(high, 'BM', 0, bm_tlt)
max := math.max(c, max)
min := math.min(c, min)
smooth_max = ta.ema(max, smooth)
smooth_min = ta.ema(min, smooth)
avg = math.avg(smooth_max, smooth_min)
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
var os = 0
os := c > smooth_max ? 1 : c < smooth_min ? 0 : os
var fade_max = 0
fade_max := os == 0 ? fade_max + 1 : 0
var fade_min = 0
fade_min := os == 1 ? fade_min + 1 : 0
plot_0 = plot(use_luxcandlepatternchannel_filter? smooth_max : na, 'Upper', bull_css)
plot_1 = plot(use_luxcandlepatternchannel_filter? avg : na, 'Average', avg_css)
plot_2 = plot(use_luxcandlepatternchannel_filter? smooth_min : na, 'Lower', bear_css)
css1 = color.from_gradient(use_luxcandlepatternchannel_filter? fade_max : na, 0, fade, color.new(bull_css, 80), color.new(bull_css, 100))
css2 = color.from_gradient(use_luxcandlepatternchannel_filter? fade_min : na, 0, fade, color.new(bear_css, 80), color.new(bear_css, 100))
long_luxcandlepatternchannel_filter=hammer or ihammer or wm
short_luxcandlepatternchannel_filter= shooting or hanging or bm
//support and resistance lux
volumeThresh = 20
highUsePivot = fixnan(ta.pivothigh(leftBars, rightBars)[1])
lowUsePivot = fixnan(ta.pivotlow(leftBars, rightBars)[1])
r1 = plot(use_support_an_dresistance_break_filter? highUsePivot : na, color=ta.change(highUsePivot) ? na : #FF0000, linewidth=3, offset=-(rightBars + 1), title='Resistance')
s1 = plot(use_support_an_dresistance_break_filter? lowUsePivot : na, color=ta.change(lowUsePivot) ? na : #233dee, linewidth=3, offset=-(rightBars + 1), title='Support')
//Volume %
shorts = ta.ema(volume, 5)
longs = ta.ema(volume, 10)
osc = 100 * (shorts - longs) / longs
short_support_an_dresistance_break_filter=close[1] < lowUsePivot and close < lowUsePivot
long_support_an_dresistance_break_filter=close[1]> highUsePivot and close > highUsePivot
//mavilimw
tmal = fmal + smal
Fmal = smal + tmal
Ftmal = tmal + Fmal
Smal = Fmal + Ftmal
M1 = ta.wma(close, fmal)
M2 = ta.wma(M1, smal)
M3 = ta.wma(M2, tmal)
M4 = ta.wma(M3, Fmal)
M5 = ta.wma(M4, Ftmal)
MAVW = ta.wma(M5, Smal)
col1 = MAVW > MAVW[1]
col3 = MAVW < MAVW[1]
colorM = col1 ? color.blue : col3 ? color.red : color.yellow
plot(use_mavilimw_filter? MAVW : na, color=colorM, linewidth=2, title='MAVW')
M12 = ta.wma(close, 3)
M22 = ta.wma(M12, 5)
M32 = ta.wma(M22, 8)
M42 = ta.wma(M32, 13)
M52 = ta.wma(M42, 21)
MAVW2 = ta.wma(M52, 34)
long_mavilimw_filter= ta.crossover(MAVW, MAVW[1])
short_mavilimw_filter=ta.crossunder(MAVW, MAVW[1])
//ift-cc1
CCI = true
v11 = 0.1 * (ta.cci(close, ccilength) / 4)
v21 = ta.wma(v11, wmalength)
INV1 = (math.exp(2 * v21) - 1) / (math.exp(2 * v21) + 1)
rsilength = 5
v12 = 0.1 * (ta.rsi(close, rsilength) - 50)
v22 = ta.wma(v12, wmalength)
INV2 = (math.exp(2 * v22) - 1) / (math.exp(2 * v22) + 1)
stochlength = 5
v1 = 0.1 * (ta.stoch(close, high, low, stochlength) - 50)
v2 = ta.wma(v1, wmalength)
INVLine = (math.exp(2 * v2) - 1) / (math.exp(2 * v2) + 1)
long_ift_cci_filter=CCI and INV1 > 0.5
short_ift_cci_filter=CCI and INV1 < -0.5
//MFI
mfilength = 5
sourcse = hlc3
up = math.sum(volume * (ta.change(sourcse) <= 0 ? 0 : sourcse), mfilength)
lo = math.sum(volume * (ta.change(sourcse) >= 0 ? 0 : sourcse), mfilength)
mfii = 100.0 - 100.0 / (1.0 + up / lo)
v13 = 0.1 * (mfii - 50)
v23 = ta.wma(v13, wmalength)
INV3 = (math.exp(2 * v23) - 1) / (math.exp(2 * v23) + 1)
AVINV = (INV1 + INV2 + INVLine + INV3) / 4
var isLong = false
var isShort= false
long = ((not use_ema_cross_filter or long_ema_cross_filter) and (not use_LUX_trama_filter or long_LUX_trama_filter) and ( not use_supertrend_filter or long_supertrend_filter) and (not use_ema200_filter or long_ema_filter) and (not isLong) and (not use_stochastic_filter or long_stoch_filter) and (not use_macd_filter or long_macd_filter) and (not use_mfi_filter or long_mfi_filter) and (not use_cci_filter or long_cci_filter) and ( not use_vwap_filter or long_vwap_filter) and (not use_chaikin_money_flow_filter or long_chaikin_money_flow_filter)and (not use_ichimoku_filter or long_ichimoku_filter)and (not use_luxcandlepatternchannel_filter or long_luxcandlepatternchannel_filter) and ( not use_support_an_dresistance_break_filter or long_support_an_dresistance_break_filter) and (not use_mavilimw_filter or long_mavilimw_filter) and (not use_ift_cci_filter or long_ift_cci_filter) and (not use_supertrend2_filter or long_supertrend2_filter) and (not use_supertrend3_filter or long_supertrend3_filter) )
short= ((not use_ema_cross_filter or short_ema_cross_filter) and (not use_LUX_trama_filter or short_LUX_trama_filter) and (not use_supertrend_filter or short_supertrend_filter) and (not use_ema200_filter or short_ema_filter) and (not isShort) and ( not use_stochastic_filter or short_stoch_filter) and (not use_macd_filter or long_macd_filter) and (not use_mfi_filter or short_mfi_filter) and (not use_cci_filter or short_cci_filter) and (not use_vwap_filter or short_vwap_filter)and (not use_chaikin_money_flow_filter or short_chaikin_money_flow_filter) and (not use_ichimoku_filter or short_ichimoku_filter) and ( not use_luxcandlepatternchannel_filter or short_luxcandlepatternchannel_filter)and (not use_support_an_dresistance_break_filter or short_support_an_dresistance_break_filter)and ( not use_mavilimw_filter or short_mavilimw_filter)and (not use_ift_cci_filter or short_ift_cci_filter)and (not use_supertrend2_filter or short_supertrend2_filter) and ( not use_supertrend3_filter or short_supertrend3_filter))
if long
isLong := true
isShort := false
if short
isLong := false
isShort := true
plotshape(long, title='Buy', text='Buy', style=shape.labelup, location=location.belowbar, color=color.new(color.green, 0), textcolor=color.new(color.white, 0), size=size.tiny)
plotshape(short, title='Sell', text='Sell', style=shape.labeldown, location=location.abovebar, color=color.new(color.red, 0), textcolor=color.new(color.white, 0), size=size.tiny)
// trailing atr exits
Prev = ta.highest(high - Mult1 * ta.atr(Atr1), Hhv1)
ta.barssince(close > ta.highest(high - Mult1 * ta.atr(Atr1), Hhv1) and close > close[1])
cum_1 = ta.cum(1)
highest_1 = ta.highest(high - Mult1 * ta.atr(Atr1), Hhv1)
highest_2 = ta.highest(high - Mult1 * ta.atr(Atr1), Hhv1)
iff_1 = close > highest_1 and close > close[1] ? highest_2 : Prev
TS = cum_1 < 16 ? close : iff_1
iff_2 = close < TS ? color.red : color.black
Color = close > TS ? color.green : iff_2
plot(use_trailing_atr_exits? TS : na, color=Color, linewidth=3, title='ATR Trailing Stoploss')
short_trailing_atr_exits = ta.crossover(close, TS)
long_trailing_atr_exits = ta.crossunder(close, TS)
//trail
longStopPricess = 0.0
shortStopPricess = 0.0
longStopPricess := if strategy.position_size > 0
stopValue = close * (1 - trailStop)
math.max(stopValue, longStopPricess[1])
else
0
shortStopPricess := if strategy.position_size < 0
stopValue = close * (1 + trailStop)
math.min(stopValue, shortStopPricess[1])
else
999999
//PLOT TSL LINES
plot(series=strategy.position_size > 0 and use_percent_base_trailing_stop_exits ? longStopPricess : na, color=color.red, style=plot.style_linebr, linewidth=1, title="Long Trail Stop", offset=1, title="Long Trail Stop")
plot(series=strategy.position_size < 0 and use_percent_base_trailing_stop_exits? shortStopPricess : na, color=color.red, style=plot.style_linebr, linewidth=1, title="Short Trail Stop", offset=1, title="Short Trail Stop")
//bollinger
basiss = ta.sma(src, lengthss)
dev = mult * ta.stdev(src, lengthss)
upper = basiss + dev
lower = basiss - dev
plot(use_bollinger_exits ? basiss : na, "Basis", color=#FF6D00, offset = offset)
p1 = plot(use_bollinger_exits ? upper : na, "Upper", color=#2962FF, offset = offset)
p2 = plot(use_bollinger_exits ? lower: na, "Lower", color=#2962FF, offset = offset)
long_atr_bands_exits = close > upline
short_atr_bands_exits = close < bottomline
long_bollinger_exits= close > upper
short_bollinger_exits=close < lower
long_atr_exits = close > upline
short_atr_exits = close < bottomline
takelong = (not use_atr_bands_exits or long_atr_bands_exits) and (not use_bollinger_exits or long_bollinger_exits) and ( not use_trailing_atr_exits or long_trailing_atr_exits )
takeshort = (not use_atr_bands_exits or short_atr_bands_exits) and (not use_bollinger_exits or short_bollinger_exits) and (not use_trailing_atr_exits or short_trailing_atr_exits)
plotshape(use_atr_bands_exits? takelong : na,title = 'take profit',text='high SL/TP',style=shape.cross,location = location.abovebar, color=color.new(color.green,0) , size=size.tiny)
plotshape(use_atr_bands_exits ? takeshort : na,title = 'take profit',text='low SL/TP',style=shape.cross,location = location.belowbar, color=color.new(color.green,0), size=size.tiny)
plotshape(use_bollinger_exits ? takelong: na,title = 'take profit',text='high SL/TP',style=shape.cross,location = location.abovebar, color=color.new(color.green,0) , size=size.tiny)
plotshape(use_bollinger_exits ? takeshort: na,title = 'take profit',text='low SL/TP',style=shape.cross,location = location.belowbar, color=color.new(color.green,0), size=size.tiny)
// Determine stop loss price
longStopPrice = strategy.position_avg_price * (1 - longLossPerc)
shortStopPrice = strategy.position_avg_price * (1 + shortLossPerc)
// Determine take profit price
longprofitPrice = strategy.position_avg_price * (1 + longprofitPerc)
shortprofitPrice = strategy.position_avg_price * (1 - shortprofitPerc)
// Plot stop loss values for confirmation
plot(series=strategy.position_size > 0 ? longStopPrice : na, color=color.new(color.red, 0), style=plot.style_cross, linewidth=1, title='Long Stop Loss')
plot(series=strategy.position_size < 0 ? shortStopPrice : na, color=color.new(color.red, 0), style=plot.style_cross, linewidth=1, title='Short Stop Loss')
plot(use_fix_perc_take_profit and strategy.position_size > 0 ? longprofitPrice : na, color=color.new(color.green, 0), style=plot.style_cross, linewidth=1, title='Long profit')
plot(use_fix_perc_take_profit and strategy.position_size < 0 ? shortprofitPrice : na, color=color.new(color.green, 0), style=plot.style_cross, linewidth=1, title='Short profit')
// trailing tp
bool openLongPosition = long
bool openShortPosition = short
bool longIsActive = openLongPosition or strategy.position_size > 0
bool shortIsActive = openShortPosition or strategy.position_size < 0
float longTakeProfitPrice2 = na
longTakeProfitPrice2 := if longIsActive
if openLongPosition and not (strategy.position_size > 0)
close * (1 + longTakeProfitPerc2)
else
nz(longTakeProfitPrice2[1], close * (1 + longTakeProfitPerc2))
else
na
float shortTakeProfitPrice2 = na
shortTakeProfitPrice2 := if shortIsActive
if openShortPosition and not (strategy.position_size < 0)
close * (1 - shortTakeProfitPerc2)
else
nz(shortTakeProfitPrice2[1], close * (1 - shortTakeProfitPrice2))
else
na
float longTrailingTakeProfitStepTicks = longTakeProfitPrice2 * LtrailingTakeProfitDeviationPerc / syminfo.mintick
float shortTrailingTakeProfitStepTicks = shortTakeProfitPrice2 * StrailingTakeProfitDeviationPerc / syminfo.mintick
plot(enableTrailing? longTakeProfitPrice2:na, title='Long Take Profit', color = color.green, linewidth = 1, style = plot.style_cross, offset = 1)
plot(enableTrailing? shortTakeProfitPrice2 :na, title='Short Take Profit', color = color.red, linewidth = 1, style = plot.style_cross, offset = 1)
longstoploss= close <longStopPrice
shortstoploss=close >shortStopPrice
if longstoploss
strategy.close("Long Entry")
if shortstoploss
strategy.close("Short Entry")
longCondition = long and not short_only
if (longCondition and time_cond)
strategy.entry("Long Entry", strategy.long)
shortCondition = short and not long_only
if (shortCondition and time_cond)
strategy.entry("Short Entry", strategy.short)
if use_trailing_stop_loss
if takelong and strategy.position_size > 0 and time_cond or time_cond and close < longStopPrice
strategy.close("Long Entry")
if takeshort and strategy.position_size < 0 and time_cond or time_cond and close >shortStopPrice
strategy.close("Short Entry")
else
if time_cond and close < longStopPrice or time_cond and close > longprofitPrice and use_fix_perc_take_profit
strategy.close("Long Entry")
if time_cond and close < shortprofitPrice or time_cond and close > shortStopPrice and use_fix_perc_take_profit
strategy.close("Short Entry")
if isLong and use_percent_base_trailing_stop_exits
strategy.exit(id="Close Long", stop=longStopPricess)
if isShort and use_percent_base_trailing_stop_exits
strategy.exit(id="Close Short", stop=shortStopPricess)
if isLong and enableTrailing
strategy.exit(id = 'Long Take Profit', from_entry = 'Long Entry', limit = close < longStopPrice or enableTrailing ? na : longTakeProfitPrice2, trail_price = enableTrailing ? longTakeProfitPrice2 : na, trail_offset = enableTrailing ? longTrailingTakeProfitStepTicks : na, when = longIsActive, alert_message = 'Long(' + syminfo.ticker + '): Take Profit activated')
if isShort and enableTrailing
strategy.exit(id = 'Short Take Profit', from_entry = 'Short Entry', limit = close > shortStopPrice or enableTrailing ? na : shortTakeProfitPrice2, trail_price = enableTrailing ? shortTakeProfitPrice2 : na, trail_offset = enableTrailing ? shortTrailingTakeProfitStepTicks : na, when = shortIsActive, alert_message = 'Short(' + syminfo.ticker + '): Take Profit activated')
|
I11L - Meanreverter 4h | https://www.tradingview.com/script/sLoJqFHI/ | I11L | https://www.tradingview.com/u/I11L/ | 147 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © I11L
//@version=5
strategy("I11L - Meanreverter 4h", overlay=false, pyramiding=3, default_qty_value=10000, initial_capital=10000, default_qty_type=strategy.cash,process_orders_on_close=false, calc_on_every_tick=false)
frequency = input.int(10)
rsiFrequency = input.int(40)
buyZoneDistance = input.int(5)
avgDownATRSum = input.int(3)
useAbsoluteRSIBarrier = input.bool(true)
barrierLevel = 50//input.int(50)
momentumRSI = ta.rsi(close,rsiFrequency)
momentumRSI_slow = ta.sma(momentumRSI,frequency)
isBuy = momentumRSI < momentumRSI_slow*(1-buyZoneDistance/100) and (strategy.position_avg_price - math.sum(ta.atr(20),avgDownATRSum)*strategy.opentrades > close or strategy.opentrades == 0 ) //and (momentumRSI < barrierLevel or not(useAbsoluteRSIBarrier))
isShort = momentumRSI > momentumRSI_slow*(1+buyZoneDistance/100) and (strategy.position_avg_price - math.sum(ta.atr(20),avgDownATRSum)*strategy.opentrades > close or strategy.opentrades == 0 ) and (momentumRSI > barrierLevel or not(useAbsoluteRSIBarrier))
momentumRSISoftClose = (momentumRSI > momentumRSI_slow) and (momentumRSI > barrierLevel or not(useAbsoluteRSIBarrier))
isClose = momentumRSISoftClose
plot(momentumRSI,color=isClose ? color.red : momentumRSI < momentumRSI_slow*(1-buyZoneDistance/100) ? color.green : color.white)
plot(momentumRSI_slow,color=color.gray)
plot(barrierLevel,color=useAbsoluteRSIBarrier ? color.white : color.rgb(0,0,0,0))
plot(momentumRSI_slow*(1-buyZoneDistance/100),color=color.gray)
plot(momentumRSI_slow*(1+buyZoneDistance/100),color=color.gray)
plot(momentumRSI_slow*(1+(buyZoneDistance*2)/100),color=color.gray)
// plot(strategy.wintrades - strategy.losstrades)
if(isBuy)
strategy.entry("Buy",strategy.long, comment="#"+str.tostring(strategy.opentrades+1))
// if(isShort)
// strategy.entry("Sell",strategy.short, comment="#"+str.tostring(strategy.opentrades+1))
if(isClose)
strategy.exit("Close",limit=close)
|
Time Based Crypto DayTrade Strategy | https://www.tradingview.com/script/qQlE2in7-Time-Based-Crypto-DayTrade-Strategy/ | exlux99 | https://www.tradingview.com/u/exlux99/ | 293 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © exlux99
//@version=5
strategy("Time Based Crypto DayTrade Strategy",overlay=true, pyramiding=1, initial_capital=1000000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, calc_on_order_fills=false, slippage=0, commission_type=strategy.commission.percent, commission_value=0.05)
atr= ta.atr(input(13))
atr2=ta.atr(input(7))
atr_filter = false
if(atr > atr2)
atr_filter:=true
monday=input.bool(false)
tuesday=input.bool(true)
wednesday=input.bool(false)
thursday=input.bool(true)
friday=input.bool(false)
saturday=input.bool(false)
sunday=input.bool(false)
hour_entry=input(1)
hour_exit=input(0)
if(monday)
strategy.entry("long", strategy.long, when= hour==hour_entry and dayofweek==1 and atr_filter)
strategy.close("long", when= hour==hour_exit)
if(tuesday)
strategy.entry("long", strategy.long, when= hour==hour_entry and dayofweek==2 and atr_filter)
strategy.close("long", when= hour==hour_exit )
if(wednesday)
strategy.entry("long", strategy.long, when= hour==hour_entry and dayofweek==3 and atr_filter)
strategy.close("long", when= hour==hour_exit )
if(thursday)
strategy.entry("long", strategy.long, when= hour==hour_entry and dayofweek==4 and atr_filter)
strategy.close("long", when= hour==hour_exit )
if(friday)
strategy.entry("long", strategy.long, when= hour==hour_entry and dayofweek==5 and atr_filter)
strategy.close("long", when= hour==hour_exit )
if(saturday)
strategy.entry("long", strategy.long, when= hour==hour_entry and dayofweek==6 and atr_filter)
strategy.close("long", when= hour==hour_exit )
if(sunday)
strategy.entry("long", strategy.long, when= hour==hour_entry and dayofweek==7 and atr_filter)
strategy.close("long", when= hour==hour_exit ) |
EURUSD COT Trend Strategy | https://www.tradingview.com/script/h7tByovH-EURUSD-COT-Trend-Strategy/ | exlux99 | https://www.tradingview.com/u/exlux99/ | 208 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © exlux99
//@version=5
strategy("EURUSD COT Strategy",overlay=true)
long_noncom = request.security("QUANDL:CFTC/"+'099741'+'_F_L_ALL|1', "W", close)
short_noncom = request.security("QUANDL:CFTC/"+'099741'+'_F_L_ALL|2', "W", close)
net_noncomercial = long_noncom-short_noncom
long = net_noncomercial > 0
short = net_noncomercial < 0
strategy.entry("long",strategy.long,when=long)
strategy.entry("short",strategy.short,when=short)
|
RSI Divergence Strategy | https://www.tradingview.com/script/ASVRhqFM/ | faytterro | https://www.tradingview.com/u/faytterro/ | 769 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © faytterro
//@version=5
strategy("RSI Divergence Strategy", overlay=true, scale = scale.none)
rsilen=input.int(14, title="rsi length")
rsisrc=input(close, title="source")
x=ta.rsi(rsisrc,rsilen)
len=input.int(14, title="RSI Divergence length", maxval=500)
tpb = input.float(25, title="take profit", group = "buy", step = 0.5)
sb = input.float(5, title="stop", group = "buy", step = 0.5)
tsb = input.float(0.25, title="trailing stop", group = "buy", step = 0.5)
tps = input.float(25, title="take profit", group = "sell", step = 0.5)
ss =input.float(5, title="stop", group = "sell", step = 0.5)
tss = input.float(0.25, title="trailing stop", group = "sell", step = 0.5)
src=close
extrapolation=0
zoom=input.int(0, title="zoom", maxval=27, minval=-27)
hline(300-zoom*10, color=color.rgb(54, 58, 69, 100))
hline(10, color=color.rgb(54, 58, 69, 100))
// for ax+b
xo=0.0
yo=0.0
xyo=0.0
xxo=0.0
for i=0 to len-1
xo:= xo + i/(len)
yo:= yo + x[len-1-i]/(len)
xyo:= xyo + i*x[len-1-i]/(len)
xxo:= xxo + i*i/(len)
dnm=ta.lowest(low,200)
dizi=array.new_float(len*2+1+extrapolation)
linedizi=array.new_line()
a=(xo*yo-xyo)/(xo*xo-xxo)
b=yo-a*xo
for i=0 to len-1+extrapolation
array.set(dizi,i,a*i+b)
//// for src
// for ax+b
xo2=0.0
yo2=0.0
xyo2=0.0
xxo2=0.0
for i=0 to len-1
xo2:= xo2 + i/(len)
yo2:= yo2 + src[len-1-i]/(len)
xyo2:= xyo2 + i*src[len-1-i]/(len)
xxo2:= xxo2 + i*i/(len)
dizi2=array.new_float(len*2+1+extrapolation)
linedizi2=array.new_line()
a2=(xo2*yo2-xyo2)/(xo2*xo2-xxo2)
b2=yo2-a*xo2
for i=0 to len-1+extrapolation
array.set(dizi2,i,a2*i+b2)
ttk=((array.get(dizi,0)<array.get(dizi,1)) and (array.get(dizi2,0)>array.get(dizi2,1)))? 1 :
((array.get(dizi,0)>array.get(dizi,1)) and (array.get(dizi2,0)<array.get(dizi2,1)))? -1 : 0
cg=((array.get(dizi,0)<array.get(dizi,1)) and (array.get(dizi2,0)>array.get(dizi2,1)))// and ta.highest(ttk[1],len/2)<1)
cr=((array.get(dizi,0)>array.get(dizi,1)) and (array.get(dizi2,0)<array.get(dizi2,1)))// and ta.lowest(ttk[1],len/2)>-1)
bgcolor(color=(cg and ta.highest(ttk[1],len/2)<1)? color.rgb(76, 175, 79, 50) :
(cr and ta.lowest(ttk[1],len/2)>-1)? color.rgb(255, 82, 82, 50) : na, offset=0, display=display.none)
plot(x)
// for ax+b
xo3=0.0
yo3=0.0
xyo3=0.0
xxo3=0.0
for i=0 to len-1
xo3:= xo3 + i/(len)
yo3:= yo3 + x[len-1-i+(ta.barssince(cg))]/(len)
xyo3:= xyo3 + i*x[len-1-i+(ta.barssince(cg))]/(len)
xxo3:= xxo3 + i*i/(len)
dizi3=array.new_float(len*2+1+extrapolation)
linedizi3=array.new_line()
a3=(xo3*yo3-xyo3)/(xo3*xo3-xxo3)
b3=yo3-a3*xo3
for i=0 to len-1+extrapolation
array.set(dizi3,i,a3*i+b3)
// for ax+b
xo4=0.0
yo4=0.0
xyo4=0.0
xxo4=0.0
for i=0 to len-1
xo4:= xo4 + i/(len)
yo4:= yo4 + x[len-1-i+(ta.barssince(cr))]/(len)
xyo4:= xyo4 + i*x[len-1-i+(ta.barssince(cr))]/(len)
xxo4:= xxo4 + i*i/(len)
dizi4=array.new_float(len*2+1+extrapolation)
linedizi4=array.new_line()
a4=(xo4*yo4-xyo4)/(xo4*xo4-xxo4)
b4=yo4-a4*xo4
for i=0 to len-1+extrapolation
array.set(dizi4,i,a4*i+b4)
line=line.new((last_bar_index-ta.barssince(cg)-len),
array.get(dizi3,0),
last_bar_index-ta.barssince(cg),
array.get(dizi3,len-1), color=color.rgb(0,255,0), width=2)
line2=line.new((last_bar_index-ta.barssince(cr)-len),
array.get(dizi4,0),
last_bar_index-ta.barssince(cr),
array.get(dizi4,len-1), color=color.rgb(255, 0, 0, 0), width=2)
line.delete(line[1])
line.delete(line2[1])
alert=((array.get(dizi,0)<array.get(dizi,1)) and (array.get(dizi2,0)>array.get(dizi2,1)) and ta.highest(ttk[1],len/2)<1)
or ((array.get(dizi,0)>array.get(dizi,1)) and (array.get(dizi2,0)<array.get(dizi2,1)) and ta.lowest(ttk[1],len/2)>-1)
alertcondition(alert)
hline(50)
rs=hline(30)
rss=hline(70)
fill(rs, rss, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill")
longCondition = cg and ta.highest(ttk[1],len/2)<1
if (longCondition)
strategy.entry("Long", strategy.long, qty = math.round(x))
strategy.exit("exit long", "Long", limit = close*(100+tpb)/100 , stop =close*(100-sb)/100 , trail_price = close , trail_offset = close*tsb)
shortCondition = cr and ta.lowest(ttk[1],len/2)>-1
if (shortCondition)
strategy.entry("Short", strategy.short, qty = math.round(100-x))
strategy.exit("exit short", "Short", limit = close*(100-tps)/100, stop = close*(100+ss)/100, trail_price = close , trail_offset = close*tss)
|
BankNifty_Bearish_Intraday | https://www.tradingview.com/script/eJF7Jzzm-BankNifty-Bearish-Intraday/ | makarandpatil | https://www.tradingview.com/u/makarandpatil/ | 95 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © makarandpatil
// This strategy is for Bank Nifty instrument and for intraday purpose only
// It checks for various indicators and gives a sell signal when all conditions are met
// Bank Nifty when in momentum gives 100-200 points in spot in 5-15 min which is how long the trade duration should be
// Issues - The custom script as per TradingView Pinescripting has an issue of repaint
// More information on repainting issue in this link - https://www.tradingview.com/pine-script-docs/en/v5/concepts/Repainting.html
// Use the script alert only to get notified, however check all the parameters individually before taking the trade
// Also, please perform a backtesting and deep backtesting of this strategy to see if the strategy gave correct buy signals in the past
// The script is made for testing purposes only and is in beta mode. Please use at own risk.
//@version=5
strategy("BankNifty_Bearish_Intraday", overlay=true, margin_long=100, margin_short=100)
// Variables
StochLength = input(14, title="Stochastic Length")
smoothK = input(3, title="%K Smoothing")
smoothD = input(3, title="%D Smoothing")
//INDICATOR CALCULATIONS
// 1. MACD
[macdLine, signalLine, histLine] = ta.macd(close[0],12,26,9)
macd5 = request.security(syminfo.tickerid, "5", macdLine)
macd15 = request.security(syminfo.tickerid,"15",macdLine)
macd60 = request.security(syminfo.tickerid,"60",macdLine)
// 2. RSI Calculation
xRSI = ta.rsi(close, 14)
// 3. ADX calculation
[diplus, diminus, adx] = ta.dmi(14,14)
// 4. Stochastic Calculation
k = ta.sma(ta.stoch(close, high, low, StochLength), smoothK)
d = ta.sma(k, smoothD)
// 5. Bollinger Band calculation
[middle, upper, lower] = ta.bb(close, 20, 2)
//CONDITIONS
// 1. Conditions for MACD
macd5Downtick = macd5[0] < macd5[1]
macd15Downtick = macd15[0] < macd15[1]
macd60Downtick = macd60[0] <= macd60[1]
// 2. Condition for xRSI
RSIWeak = xRSI < 40
// 3. Condition for ADX
ADXUngali = adx >= 12
// 4. Condition for Stochastic
StochNCO = k < d
// 5. Condition for Bollinger Band
BBCD = lower < lower [1]
//Evaluate the short condition
shortCondition = macd5[0] < 0 and macd5Downtick and macd15Downtick and macd60Downtick and RSIWeak and ADXUngali and StochNCO and BBCD
// shortCondition = macd5Downtick and macd15Downtick and RSIWeak and ADXUngali and StochNCO
if (shortCondition)
strategy.entry("Short", strategy.short, alert_message = "BankNifty_Sell_Momentum")
longCondition = close > ta.ema(close,5)
if (longCondition)
strategy.entry("ShortSquareoff", strategy.long, alert_message = "BankNifty_Closed_Above_5EMA")
|
12/26-IT strategy | https://www.tradingview.com/script/00meSQ1R-12-26-IT-strategy/ | Abdul-Rahim | https://www.tradingview.com/u/Abdul-Rahim/ | 275 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © AbdulRahimShama
//@version=5
strategy('12/26-IT strategy', overlay=true,initial_capital = 100000, calc_on_order_fills = true, pyramiding = 10)
Show_Only_12_26_Crossover_Entry = input.bool(true, group = "Entry_Exit Criteria")
Show_12_26_Crossover_and_resistance_Entry = input.bool(false, group = "Entry_Exit Criteria")
Show_MA_StopLoss = input.bool(false, group = "Entry_Exit Criteria", tooltip = "update values as per your requirement in MA section")
Show_TSL_StopLoss = input.bool(false, group = "Entry_Exit Criteria")
Show_Crossdown_StopLoss = input.bool(true, group = "Entry_Exit Criteria")
////////////////////////////////////////////////
////////////////TARGETS INPUT
////////////////////////////////////////////////
////////Target1
TargetPerc1 = input.float(title="Target (%)", minval=0,defval=5, group="Target-1") / 100
TargetPrice1 = strategy.position_avg_price * (1 + TargetPerc1)
Target1_exit_qty = input.int(50, group="Target-1",tooltip = "% qty to sell when Target1 is reached")
////////Target2
TargetPerc2 = input.float(title="Target (%)", minval=0,defval=10, group="Target-2") / 100
TargetPrice2 = strategy.position_avg_price * (1 + TargetPerc2)
Target2_exit_qty = input.int(100, group="Target-2",tooltip = "% qty to sell when Target2 is reached")
////////////////////////////////////////////////
////////////////TRAILING STOP LOSS
////////////////////////////////////////////////
TSLsource = input(low, title="TSL Source", group="Trailing StopLoss")
longTrailPerc = input.float(title='Trail Long Loss (%)', minval=0.0, step=0.1, defval=1, group="Trailing StopLoss") * 0.01
TrailStopPrice = 0.0
TrailStopPrice := if strategy.position_size > 0
sPIVOT_highValue = TSLsource * (1 - longTrailPerc)
math.max(sPIVOT_highValue, TrailStopPrice[1])
else
0
TSL = close < TrailStopPrice
plot(series=strategy.position_size > 0 and Show_TSL_StopLoss ? TrailStopPrice : na, color=color.new(color.fuchsia, 0), style=plot.style_linebr, linewidth=2, title='Trailing StopLoss')
////////////////////////////////////////////////
////////////////Moving Averages
////////////////////////////////////////////////
SLmaLength = input.int(21, group="StopLoss MA")
SLmaSource = input(low, group="StopLoss MA")
ma(SLmaSource, length, type) =>
switch type
"SMA" => ta.sma(SLmaSource, SLmaLength)
"EMA" => ta.ema(SLmaSource, SLmaLength)
SLmaType = input.string("EMA", title="StopLoss MA", options=["SMA", "EMA"], group="StopLoss MA")
SL_MA = ma(SLmaSource, SLmaLength, SLmaType)
plot(Show_MA_StopLoss ? SL_MA : na, "StopLoss for MA", color=color.rgb(255, 0, 0))
EMA_12 =ta.ema(close, 12)
EMA_26 =ta.ema(close, 26)
EMA_21 =ta.ema(close,21)
plot(EMA_12, title="EMA_12", color=color.rgb(0, 255, 0), offset=0, linewidth=1)
plot(EMA_26, title="EMA_26", color=color.rgb(0, 0, 255), offset=0, linewidth=2)
plot(Show_MA_StopLoss ? SL_MA : na, "StopLoss for MA", color=color.rgb(255, 0, 0))
////////////////////////////////////////////////
////////////////RESISTANCE INPUT and PLOTTING
////////////////////////////////////////////////
CrossOverLookbackCandles = input.int(10, group= "RESISTANCE")
resistanceSRC = input(high, group= "RESISTANCE")
resistanceLEFT = input(10, group= "RESISTANCE")
resistanceRIGHT = input(10, group= "RESISTANCE")
hih = ta.pivothigh(resistanceSRC, resistanceLEFT, resistanceRIGHT)
top = ta.valuewhen(hih, resistanceSRC[resistanceRIGHT], 0)
res = plot(top, color=top != top[1] ? na : color.new(#00ff00, 50), offset=-resistanceLEFT, linewidth=2, title="Resistance Line")
EMA_12_Low = ta.lowest(EMA_12, CrossOverLookbackCandles)
EMA_26_Low = ta.lowest(EMA_26, CrossOverLookbackCandles)
////////////////////////////////////////////////
////////////////RSI INPUT and PLOTTING
////////////////////////////////////////////////
RSI = ta.rsi(close, 14)
RSILowerRange = input.int(45, tooltip = "RSI value should be ABOVE this value for entry", group = "RSI")
RSIUpperRange = input.int(70, tooltip = "RSI value should be BELOW this value for entry", group = "RSI")
////////////////////////////////////////////////
////////////////MACD
////////////////////////////////////////////////
fast_length = 12
slow_length = 26
MACD_src = close
signal_length = 9
fast_ma = ta.ema(MACD_src, fast_length)
slow_ma = ta.ema(MACD_src, slow_length)
macd = fast_ma - slow_ma
signal = ta.ema(macd, signal_length)
hist = macd - signal
////////////////////////////////////////////////
////////////////ENTRY CRITERIA
////////////////////////////////////////////////
BUYVALUE = input(100000, tooltip = "Buy qty displayed on chart will be based on this value")
BASEENTRY = macd > signal and RSI > RSILowerRange and RSI < RSIUpperRange and close > EMA_21 and close > ta.sma(close, 7)
Entry = ta.crossover(EMA_12, EMA_26) and BASEENTRY
Entry2 = ta.crossover(close, top) and EMA_12_Low < EMA_26_Low and EMA_12 > EMA_26 and RSI < 80
////////////////////////////////////////////////
////////////////BUY SELL STRATEGY
////////////////////////////////////////////////
if ((Entry and Show_Only_12_26_Crossover_Entry))
strategy.entry("buy", strategy.long, qty=BUYVALUE/close)
if (Entry2 and Show_12_26_Crossover_and_resistance_Entry)
strategy.entry("buy", strategy.long, qty=BUYVALUE/close)
strategy.exit("Tg1", "buy", limit=TargetPrice1, qty_percent = Target1_exit_qty)
strategy.exit("Tg2", "buy", limit=TargetPrice2, qty_percent = Target2_exit_qty)
if TSL and Show_TSL_StopLoss and close < EMA_12
strategy.close_all ("sl")
if ta.crossunder(EMA_12, EMA_26) and Show_Crossdown_StopLoss
strategy.close_all ("sl")
if ta.crossunder(close, SL_MA) and Show_MA_StopLoss
strategy.close_all ("sl")
bgcolor(color=((Entry and Show_Only_12_26_Crossover_Entry)) ? color.new(color.blue, 0) : na) |
Wolfe Strategy [Trendoscope] | https://www.tradingview.com/script/EGvQ2nLb-Wolfe-Strategy-Trendoscope/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 1,875 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
// ░▒
// ▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒
// ▒▒▒▒▒▒▒░ ▒ ▒▒
// ▒▒▒▒▒▒ ▒ ▒▒
// ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒
// ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒ ▒▒▒▒▒
// ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
// ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗
// ▒▒ ▒
//@version=5
maxPatternsLive = 10
capital = 1000.0
strategy("Wolfe Strategy [Trendoscope]", shorttitle='WS[Trendoscope]', overlay=true, initial_capital=capital, default_qty_type=strategy.percent_of_equity,
default_qty_value=10, commission_type=strategy.commission.percent, pyramiding=10,
commission_value=0.05, close_entries_rule="ANY", max_lines_count=500, max_labels_count=500, max_boxes_count=500, use_bar_magnifier=false,
margin_long=100, margin_short=100)
import HeWhoMustNotBeNamed/rzigzag/10 as zigzag
import HeWhoMustNotBeNamed/_matrix/5 as ma
import HeWhoMustNotBeNamed/arrays/1 as pa
import HeWhoMustNotBeNamed/strategy/3 as st
var idArray = array.from(1)
tradeDirection = input.string(strategy.direction.long, "Trade Direction", options=[strategy.direction.long, strategy.direction.short],
group="Trade Settings", tooltip='Use this to filter only long or short trades')
minRiskReward = input.float(1.0, 'Minimum RR', group='Trade Settings', minval=0.5, step=0.1, tooltip='Minimum RR to place trade')
theme = input.string('Dark', title='Theme', options=['Light', 'Dark'], group='Generic',
tooltip='Chart theme settings. Line and label colors are generted based on the theme settings. If dark theme is selected, '+
'lighter colors are used and if light theme is selected, darker colors are used.')
avoidOverlap = input.bool(false, 'Suppress Overlap', group='Generic',
tooltip='Avoids plotting wedge if there is an existing wedge at starting point. This does not avoid nesting wedges (Wedge within wedge)')
drawZigzag = input.bool(true, 'Draw Zigzag', group='Generic', tooltip='Draw zigzag lines and mark pivots within wedge')
zigzagLength = input.int(8, step=5, minval=3, title='Length', group='Zigzag', tooltip='Zigzag length')
zigzagDepth = input.int(250, step=50, minval=50, title='Depth', group='Zigzag', tooltip='Zigzag depth for recursive search')
minLevel = input.int(0, "Min Level", group='Zigzag', minval =0, tooltip = 'Min Level on recursive zigzag to calculate Wolfe')
var themeColors = theme=="Dark"? array.from(
color.rgb(251, 244, 109),
color.rgb(141, 186, 81),
color.rgb(74, 159, 245),
color.rgb(255, 153, 140),
color.rgb(255, 149, 0),
color.rgb(0, 234, 211),
color.rgb(167, 153, 183),
color.rgb(255, 210, 113),
color.rgb(119, 217, 112),
color.rgb(95, 129, 228),
color.rgb(235, 146, 190),
color.rgb(198, 139, 89),
color.rgb(200, 149, 149),
color.rgb(196, 182, 182),
color.rgb(255, 190, 15),
color.rgb(192, 226, 24),
color.rgb(153, 140, 235),
color.rgb(206, 31, 107),
color.rgb(251, 54, 64),
color.rgb(194, 255, 217),
color.rgb(255, 219, 197),
color.rgb(121, 180, 183)
) : array.from(
color.rgb(61, 86, 178),
color.rgb(57, 163, 136),
color.rgb(250, 30, 14),
color.rgb(169, 51, 58),
color.rgb(225, 87, 138),
color.rgb(62, 124, 23),
color.rgb(244, 164, 66),
color.rgb(134, 72, 121),
color.rgb(113, 159, 176),
color.rgb(170, 46, 230),
color.rgb(161, 37, 104),
color.rgb(189, 32, 0),
color.rgb(16, 86, 82),
color.rgb(200, 92, 92),
color.rgb(63, 51, 81),
color.rgb(114, 106, 149),
color.rgb(171, 109, 35),
color.rgb(247, 136, 18),
color.rgb(51, 71, 86),
color.rgb(12, 123, 147),
color.rgb(195, 43, 173)
)
maxPatternsReference = 10
var pivotBarMatrix = matrix.new<int>()
var patternIdArray = array.new<int>()
var patternProjections = matrix.new<line>()
var patternTradeMatrix = matrix.new<float>()
wedgeLine(l1StartX, l1StartY, l1EndX, l1EndY, l2StartX, l2StartY, l2EndX, l2EndY, zgColor, lastDir)=>
l1t = line.new(l1StartX, l1StartY, l1EndX, l1EndY, color=zgColor, extend=extend.both)
l2t = line.new(l2StartX, l2StartY, l2EndX, l2EndY, color=zgColor, extend=extend.both)
startBar = l1StartX
endBar = l1EndX
l2Start = line.get_price(l2t,startBar)
l2End = line.get_price(l2t, endBar)
line.set_x1(l2t, startBar)
line.set_y1(l2t, l2Start)
line.set_x2(l2t, endBar)
line.set_y2(l2t, l2End)
l1Diff = l1StartY-l1EndY
l2Diff = l2Start-l2End
width = math.abs(endBar-startBar)
closingEndBar = endBar
closingEndPrice = l2End
closingSoon = false
isContracting = math.abs(l1StartY-l2Start) > math.abs(l1EndY-l2End)
isNotTriangle = math.sign(l1StartY-l1EndY) == math.sign(l2Start-l2End)
isWolfeWedge = isContracting and isNotTriangle
if(isWolfeWedge)
for i =endBar to endBar+math.min(500, 2*width)
l1Price = line.get_price(l1t, i)
l2Price = line.get_price(l2t, i)
if(lastDir* (l1Price-l2Price) <= 0)
closingEndBar := i
closingSoon := true
closingEndPrice := (l1Price + l2Price)/2
break
if(closingSoon)
line.set_x2(l2t, closingEndBar)
line.set_y2(l2t, closingEndPrice)
line.set_x2(l1t, closingEndBar)
line.set_y2(l1t, closingEndPrice)
line.set_extend(l1t, extend.none)
line.set_extend(l2t, extend.none)
[l1t, l2t, closingEndBar, closingEndPrice, isWolfeWedge and closingSoon]
find_wedge(zigzagmatrix, startIndex)=>
_5 = matrix.get(zigzagmatrix, startIndex, 0)
_5Bar = int(matrix.get(zigzagmatrix, startIndex, 1))
lastDir = matrix.get(zigzagmatrix, startIndex, 3)
_4 = matrix.get(zigzagmatrix, startIndex+1, 0)
_4Bar = int(matrix.get(zigzagmatrix, startIndex+1, 1))
_3 = matrix.get(zigzagmatrix, startIndex+2, 0)
_3Bar = int(matrix.get(zigzagmatrix, startIndex+2, 1))
_2 = matrix.get(zigzagmatrix, startIndex+3, 0)
_2Bar = int(matrix.get(zigzagmatrix, startIndex+3, 1))
_1 = matrix.get(zigzagmatrix, startIndex+4, 0)
_1Bar = int(matrix.get(zigzagmatrix, startIndex+4, 1))
isValidDirection = (tradeDirection == strategy.direction.long and lastDir < 0) or (tradeDirection == strategy.direction.short and lastDir > 0)
if(isValidDirection)
existingPattern = false
for i=0 to matrix.rows(pivotBarMatrix) > 0? matrix.rows(pivotBarMatrix)-1 : na
commonPivotsCount = (_1Bar == matrix.get(pivotBarMatrix, i, 0) ? 1 : 0) +
(_2Bar == matrix.get(pivotBarMatrix, i, 1) ? 1 : 0) +
(_3Bar == matrix.get(pivotBarMatrix, i, 2) ? 1 : 0) +
(_4Bar == matrix.get(pivotBarMatrix, i, 3) ? 1 : 0) +
(_5Bar == matrix.get(pivotBarMatrix, i, 4) ? 1 : 0)
if ( commonPivotsCount >=3 ) or (avoidOverlap and _1Bar >= matrix.get(pivotBarMatrix, i, 0) and _1Bar <= matrix.get(pivotBarMatrix, i, 4))
existingPattern := true
break
if(not existingPattern)
basicCondition = lastDir > 0? _2 < math.min(_1, _3, _4, _5) and _5 > math.max(_1, _2, _3, _4) and _1 < _3 and _1 > _4 :
_2 > math.max(_1, _3, _4, _5) and _5 < math.min(_1, _2, _3, _4) and _1 > _3 and _1 < _4
if(basicCondition)
zgColor = array.pop(themeColors)
[l1t, l2t, closingEndBar, closingEndPrice, isWolfeWedge] = wedgeLine(_1Bar, _1, _5Bar, _5, _2Bar, _2, _4Bar, _4, zgColor, lastDir)
array.unshift(themeColors, zgColor)
delete = true
if(isWolfeWedge)
id = array.get(idArray, 0)
array.set(idArray, 0, id+1)
ma.unshift(pivotBarMatrix, array.from(_1Bar, _2Bar, _3Bar, _4Bar, _5Bar), maxPatternsReference)
pa.unshift(patternIdArray, id, maxPatternsReference)
delete := false
if(drawZigzag)
line.new(_1Bar, _1, _2Bar, _2, color=zgColor, extend=extend.none, width=0, style=line.style_dotted)
line.new(_2Bar, _2, _3Bar, _3, color=zgColor, extend=extend.none, width=0, style=line.style_dotted)
line.new(_3Bar, _3, _4Bar, _4, color=zgColor, extend=extend.none, width=0, style=line.style_dotted)
line.new(_4Bar, _4, _5Bar, _5, color=zgColor, extend=extend.none, width=0, style=line.style_dotted)
lproj = line.new(_1Bar, _1, _4Bar, _4, color=zgColor, extend=extend.right, width=0, style=line.style_dashed)
lProjEndPrice = line.get_price(lproj, closingEndBar)
line.set_x2(lproj, closingEndBar)
line.set_y2(lproj, lProjEndPrice)
line.set_extend(lproj, extend.none)
lclose = line.new(closingEndBar, lProjEndPrice, closingEndBar, closingEndPrice, color=zgColor, extend=extend.none, width=0, style=line.style_dashed)
ma.unshift(patternProjections, array.from(lproj, lclose, l2t), maxPatternsReference)
entry = line.get_price(l2t, bar_index+1)
target = lProjEndPrice
stop = closingEndPrice
ma.unshift(patternTradeMatrix, array.from(entry, stop, target, 0), maxPatternsReference)
rr = math.abs(entry-target)/math.abs(entry-stop)
dir = entry > stop? 1 : -1
if(rr >= minRiskReward)
st.bracketOrderWithoutLeverage(str.tostring(id), entry, stop, target, close*dir > entry*dir)
if(delete)
line.delete(l1t)
line.delete(l2t)
scan_patterns(startIndex, newPivot, zigzagmatrix)=>
length = matrix.rows(zigzagmatrix)
numberOfPivots=5
if(length >= startIndex+5 and newPivot)
find_wedge(zigzagmatrix, startIndex)
setup(zigzagLength, zigzagDepth)=>
[zigzagmatrix, flags] = zigzag.zigzag(zigzagLength, array.from(high, low), numberOfPivots= zigzagDepth)
newPivot = array.get(flags, 1)
doublePivot = array.get(flags, 2)
if(newPivot)
mlzigzag = zigzagmatrix
level = 1
while(matrix.rows(mlzigzag) >= 5)
if(level >= minLevel)
scan_patterns(1, doublePivot, zigzagmatrix)
scan_patterns(0, newPivot,zigzagmatrix)
mlzigzag := zigzag.nextlevel(mlzigzag, zigzagDepth)
level := level+1
evaluate()=>
for i=array.size(patternIdArray) > 0? array.size(patternIdArray)-1: na to 0
id = array.get(patternIdArray, i)
l2t = matrix.get(patternProjections, i, 2)
entry = matrix.get(patternTradeMatrix, i, 0)
stop = matrix.get(patternTradeMatrix, i, 1)
target = matrix.get(patternTradeMatrix, i, 2)
status = matrix.get(patternTradeMatrix, i, 3)
rr = math.abs(entry-target)/math.abs(entry-stop)
dir = entry > stop? 1 : -1
targetValue = dir > 0? high : low
stopValue = dir >0? low : high
newStatus = status == 0 and targetValue*dir > entry*dir and rr >=minRiskReward ? 1 : status
if(targetValue*dir > target*dir) or (newStatus == 1 and close*dir < stop) or (newStatus == 0 and bar_index > line.get_x2(l2t))
strategy.cancel(str.tostring(id))
array.remove(patternIdArray, i)
matrix.remove_row(pivotBarMatrix, i)
matrix.remove_row(patternProjections, i)
matrix.remove_row(patternTradeMatrix, i)
false
else if (newStatus == 0)
newEntry = line.get_price(l2t, bar_index+1)
newRR = math.abs(entry-target)/math.abs(entry-stop)
if(newRR >= minRiskReward)
strategy.cancel(str.tostring(id))
st.bracketOrderWithoutLeverage(str.tostring(id), newEntry, stop, target, close*dir > newEntry*dir)
matrix.set(patternTradeMatrix, i, 0, newEntry)
matrix.set(patternTradeMatrix, i, 3, newStatus)
true
setup(zigzagLength, zigzagDepth)
evaluate() |
M0PB (Momentum Pullback) | https://www.tradingview.com/script/GnsUpEsB-M0PB-Momentum-Pullback/ | Marcn5_ | https://www.tradingview.com/u/Marcn5_/ | 195 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Marcns_
//@version=5
strategy("M0PB", commission_value = 0.0004, slippage = 1, initial_capital=30000)
// commision is equal to approx $3.8 per round trip which is accurate for ES1! futures and slippage per trade is conservatively 1 tick in and 1 tick out.
// *momentum pull back* //
// long / short strategy that identifies extreme readings on the rsi as a *momentum signal*
//Strategy buys/ sells a pullback to the 5ema(low)/ 5ema(high) and exits at rolling 12 bar high/ low. The rolling high/ low feature means that
//if price enters into a pronlonged consolidation the profit target will begin to reduce with each new bar. The best trades tend to work within 2-6 bars
// hard stop is X atr's from postion average price. This can be adjusted in user inputs.
// built for use on 5 min & 1min intervals on: FX, Indexes, Crypto
// there is a lot of slack left in entries and exits but the overall strategy is fairly robust across timeframes and markets and has between 60%-70% winrate with larger winners.
// signals that occur from economic news volatility are best avoided.
// define rsi
r = ta.rsi(close,6)
// find rsi > 90
b = 0.0
if r >= 90
b := 1.0
else
na
// find rsi < 10
s = 0.0
if r <= 10
s := -1.0
else
na
// plot rsi extreme as painted background color
bgcolor(b ? color.rgb(255, 82, 82, 49): na)
bgcolor(s? color.rgb(76, 175, 79, 51): na)
// exponential moving averages for entries. note that source is high and low (normally close is def input) this creates entry bands
//entry short price using high as a source ta.ema(high,5)
es = ta.ema(high,5)
//entry long price using low as a source ta.ema(low,5)
el = ta.ema(low,5)
// long pullback entry trigger: last period above ema and current low below target ema entry
let = 0.0
if low[1] > el[1] and low <= el
let := 1.0
else
na
//short entry trigger ""
set = 0.0
if high[1] < es[1] and high >= es
set := -1.0
else
na
// create signal "trade_l" if RSI > 90 and price pulls back to 5ema(low) within 6 bars
trade_l = 0.0
if ta.barssince(b == 1.0) < 6 and let == 1.0
trade_l := 1.0
else
na
plot(trade_l, "l_entry", color.green)
//create short signal "trade_s" if rsi < 10 and prices pullback to 5em(high) wihthin 6 bars
trade_s = 0.0
if ta.barssince(s == -1.0) < 6 and set == -1.0
trade_s := -1.0
else
na
plot(trade_s, "s_entry", color.purple)
// define price at time of trade_l signal and input value into trade_p to use for stop parems later
trade_p = strategy.position_avg_price
//indentify previous 12 bar high as part of long exit strat
// this creates a rolling 12 bar high target... a quick move back up will exit at previous swing high but if a consolidation occurs system will exit on a new 12 bar high which may be below prev local high
ph = ta.highest(12)
// inverse of above for short exit strat - previous lowest low of 12 bars as exit (rolling)
pl = ta.lowest(12)
// 1.5 atr stop below entry price (trade_p defined earlier) as part of exit strat
atr_inp = input.float(2.75, "atr stop", minval = 0.1, maxval = 6.0)
atr = ta.atr(10)
stop_l = trade_p - (atr* atr_inp)
stop_s = trade_p + (atr* atr_inp)
//strat entry long
strategy.entry("EL", strategy.long, 2, when = trade_l == 1.0)
//strat entry short
strategy.entry("ES", strategy.short, 2, when = trade_s == -1.0)
//strat long exit
if strategy.position_size == 2
strategy.exit(id = "ph", from_entry = "EL", qty = 2, limit = ph)
if strategy.position_size == 2
strategy.close_all(when = low[1] > stop_l[1] and low <= stop_l)
// strat short exit
if strategy.position_size == -2
strategy.exit(id = "pl", from_entry = "ES", qty = 2, limit =pl)
if strategy.position_size == -2
strategy.close_all(when = high[1] < stop_s[1] and high >= stop_s)
// code below to trail remaining 50% of position //
//if strategy.position_size == 1
//strategy.exit(id ="trail", from_entry = "EL", qty = 1, stop = el)
|
Simple Momentum and Trend, Fixed PnL Strategy for SPY 1D [SR] | https://www.tradingview.com/script/82er3iVb-Simple-Momentum-and-Trend-Fixed-PnL-Strategy-for-SPY-1D-SR/ | ShayanRastgou | https://www.tradingview.com/u/ShayanRastgou/ | 58 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ShayanRastgou
//@version=5
strategy("Simple Momentum and Trend, Fixed PnL Strategy for SPY 1D", overlay=false, margin_long=20, margin_short=20, pyramiding = 25, default_qty_type = strategy.percent_of_equity, default_qty_value = 5, initial_capital = 10000)
// Set stop loss and take profit levels
stopLoss = 50
takeProfit = 300
// Set order size and pyramiding
orderSize = 2
maxPositions = 25
// Define long entry condition
longCondition = ta.atr(5) > ta.atr(20) and ta.tsi(close, 13, 25) > 0
if (longCondition and strategy.position_size < maxPositions)
strategy.entry("My Long Entry Id" + str.tostring(bar_index), strategy.long, stop=stopLoss, limit=takeProfit)
// Define short entry condition
shortCondition = ta.atr(5) > ta.atr(20) and ta.tsi(close, 13, 25) < 0
if (shortCondition and strategy.position_size < maxPositions)
strategy.entry("My Short Entry Id" + str.tostring(bar_index), strategy.short, stop=stopLoss, limit=takeProfit)
// Plot the 5-period ATR
plot(ta.atr(5), color=color.red, linewidth=2, title="5-Period ATR")
// Plot the 20-period ATR
plot(ta.atr(20), color=color.orange, linewidth=2, title="20-Period ATR")
// Plot the TSI
plot(ta.tsi(close, 13, 25), color=color.green, linewidth=2, title="TSI") |
BankNifty_Bullish_Intraday | https://www.tradingview.com/script/cxZcTwnv-BankNifty-Bullish-Intraday/ | makarandpatil | https://www.tradingview.com/u/makarandpatil/ | 250 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © makarandpatil
// This strategy is for Bank Nifty instrument and for intraday purpose only
// It checks for various indicators and gives a buy signal when all conditions are met
// Bank Nifty when in momentum gives 100-200 points in spot in 5-15 min which is how long the trade duration should be
// Issues - The custom script as per TradingView Pinescripting has an issue of repaint
// More information on repainting issue in this link - https://www.tradingview.com/pine-script-docs/en/v5/concepts/Repainting.html
// Use the script alert only to get notified, however check all the parameters individually before taking the trade
// Also, please perform a backtesting and deep backtesting of this strategy to see if the strategy gave correct buy signals in the past
// The script is made for testing purposes only and is in beta mode. Please use at own risk.
//@version=5
strategy("BankNifty_Bullish_Intraday", overlay=true, margin_long = 100, margin_short = 100)
// Variables
StochLength = input(14, title="Stochastic Length")
smoothK = input(3, title="%K Smoothing")
smoothD = input(3, title="%D Smoothing")
//INDICATOR CALCULATIONS
// 1. MACD
[macdLine, signalLine, histLine] = ta.macd(close[0],12,26,9)
macd5 = request.security(syminfo.tickerid, "5", macdLine)
macd15 = request.security(syminfo.tickerid,"15",macdLine)
macd60 = request.security(syminfo.tickerid,"60",macdLine)
// 2. RSI Calculation
xRSI = ta.rsi(close, 14)
// 3. ADX calculation
[diplus, diminus, adx] = ta.dmi(14,14)
// plot(adx,color = color.black)
// 4. Stochastic Calculation
k = ta.sma(ta.stoch(close, high, low, StochLength), smoothK)
d = ta.sma(k, smoothD)
// 5. Bollinger Band calculation
[middle, upper, lower] = ta.bb(close, 20, 2)
//CONDITIONS
// 1. Conditions for MACD
macd5Uptick = macd5[0] > macd5[1]
macd15Uptick = macd15[0] > macd15[1]
macd60Uptick = macd60[0] >= macd60[1]
// 2. Condition for xRSI
RSIStrong = xRSI > 60
// 3. Condition for ADX
ADXUngali = adx >= 12
// 4. Condition for Stochastic
StochPCO = k > d
// 5. Condition for Bollinger Band
BBCU = upper > upper [1]
//Evaluate the long condition
// longCondition = macd5Uptick and macd15Uptick and RSIStrong and ADXUngali and StochPCO and BBCU
longCondition = macd5[0] > 0 and macd5Uptick and macd15Uptick and macd60Uptick and RSIStrong and ADXUngali and StochPCO and BBCU
// longCondition = macd5Uptick and macd15Uptick and RSIStrong and ADXUngali and StochPCO and BBCU
if (longCondition)
strategy.entry("Buy", strategy.long,alert_message = "BankNifty_Buy_Momentum")
shortCondition = close < ta.ema(close,5)
if (shortCondition)
strategy.entry("BuySquareoff", strategy.short, alert_message = "BankNifty_Closed_Below_5EMA")
|
Strategy Myth-Busting #20 - HalfTrend+HullButterfly - [MYN] | https://www.tradingview.com/script/lL04fUNr-Strategy-Myth-Busting-20-HalfTrend-HullButterfly-MYN/ | myncrypto | https://www.tradingview.com/u/myncrypto/ | 1,163 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © myn
//@version=5
strategy('Strategy Myth-Busting #20 - HalfTrend+HullButterfly - [MYN]', max_bars_back=5000, overlay=true, pyramiding=0, initial_capital=10000, currency='NONE', default_qty_type=strategy.percent_of_equity, default_qty_value=1.0, commission_value=0.075, use_bar_magnifier = false)
/////////////////////////////////////
//* Put your strategy logic below *//
/////////////////////////////////////
// Hull Butterfly gives us green column, Wait for HalfTrend to present an up arrow and enter trade.
// Hull Butterfly gives us a red column , Wait for HalfTrend present a down arrow and enter trade.
// SL at swing high/low with TP 1.5 risk
// Hull Butterfly Oscillator [LuxAlgo]
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
//-----------------------------------------------------------------------------}
//Settings
//----------------------------------------------------a-------------------------{
length = input(11, group="Hull Butterfly Oscillator")
mult = input(2., 'Levels Multiplier')
src = input(close)
//Style
bull_css_0 = input.color(color.new(#0cb51a, 50), 'Bullish Gradient'
, inline = 'inline0'
, group = 'Style')
bull_css_1 = input.color(#0cb51a, ''
, inline = 'inline0'
, group = 'Style')
bear_css_0 = input.color(color.new(#ff1100, 50), 'Bearish Gradient'
, inline = 'inline1'
, group = 'Style')
bear_css_1 = input.color(#ff1100, ''
, inline = 'inline1'
, group = 'Style')
//-----------------------------------------------------------------------------}
//Normalization variables
//-----------------------------------------------------------------------------{
var short_len = int(length / 2)
var hull_len = int(math.sqrt(length))
var den1 = short_len * (short_len + 1) / 2
var den2 = length * (length + 1) / 2
var den3 = hull_len * (hull_len + 1) / 2
//-----------------------------------------------------------------------------}
//Hull coefficients
//-----------------------------------------------------------------------------{
var lcwa_coeffs = array.new_float(hull_len, 0)
var hull_coeffs = array.new_float(0)
if barstate.isfirst
//Linearly combined WMA coeffs
for i = 0 to length-1
sum1 = math.max(short_len - i, 0)
sum2 = length - i
array.unshift(lcwa_coeffs, 2 * (sum1 / den1) - (sum2 / den2))
//Zero padding of linearly combined WMA coeffs
for i = 0 to hull_len-2
array.unshift(lcwa_coeffs, 0)
//WMA convolution of linearly combined WMA coeffs
for i = hull_len to array.size(lcwa_coeffs)-1
sum3 = 0.
for j = i-hull_len to i-1
sum3 += array.get(lcwa_coeffs, j) * (i - j)
array.unshift(hull_coeffs, sum3 / den3)
//-----------------------------------------------------------------------------}
//Hull squeeze oscillator
//-----------------------------------------------------------------------------{
var os = 0
var len = array.size(hull_coeffs)-1
hma = 0.
inv_hma = 0.
for i = 0 to len
hma += src[i] * array.get(hull_coeffs, i)
inv_hma += src[len-i] * array.get(hull_coeffs, i)
hso = hma - inv_hma
cmean = ta.cum(math.abs(hso)) / bar_index * mult
os := ta.cross(hso, cmean) or ta.cross(hso, -cmean) ? 0
: hso < hso[1] and hso > cmean ? -1
: hso > hso[1] and hso < -cmean ? 1
: os
//-----------------------------------------------------------------------------}
//Plot
//-----------------------------------------------------------------------------{
//Colors
css0 = color.from_gradient(hso, 0, cmean, bull_css_0, bull_css_1)
css1 = color.from_gradient(hso, -cmean, 0, bear_css_1, bear_css_0)
css = hso > 0 ? css0 : css1
plotshape(os > os[1] and os == 1 , title='Arrow Up', style=shape.circle, location=location.belowbar, size=size.tiny, color=color.new(color.green, 0))
plotshape(os < os[1] and os == -1, title='Arrow Down', style=shape.circle, location=location.abovebar, size=size.tiny, color=color.new(color.red, 0))
hullLongEntry = os > os[1] and os == 1
hullShortEntry = os < os[1] and os == -1
// HalfTrend - Everget
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Copyright (c) 2021-present, Alex Orekhov (everget)
amplitude = input(title='Amplitude', defval=2, group="HalfTrend")
channelDeviation = input(title='Channel Deviation', defval=2)
showArrows = input(title='Show Arrows', defval=true)
showChannels = input(title='Show Channels', defval=false)
var int trend = 0
var int nextTrend = 0
var float maxLowPrice = nz(low[1], low)
var float minHighPrice = nz(high[1], high)
var float up = 0.0
var float down = 0.0
float atrHigh = 0.0
float atrLow = 0.0
float arrowUp = na
float arrowDown = na
atr2 = ta.atr(100) / 2
dev = channelDeviation * atr2
highPrice = high[math.abs(ta.highestbars(amplitude))]
lowPrice = low[math.abs(ta.lowestbars(amplitude))]
highma = ta.sma(high, amplitude)
lowma = ta.sma(low, amplitude)
if nextTrend == 1
maxLowPrice := math.max(lowPrice, maxLowPrice)
if highma < maxLowPrice and close < nz(low[1], low)
trend := 1
nextTrend := 0
minHighPrice := highPrice
minHighPrice
else
minHighPrice := math.min(highPrice, minHighPrice)
if lowma > minHighPrice and close > nz(high[1], high)
trend := 0
nextTrend := 1
maxLowPrice := lowPrice
maxLowPrice
if trend == 0
if not na(trend[1]) and trend[1] != 0
up := na(down[1]) ? down : down[1]
arrowUp := up - atr2
arrowUp
else
up := na(up[1]) ? maxLowPrice : math.max(maxLowPrice, up[1])
up
atrHigh := up + dev
atrLow := up - dev
atrLow
else
if not na(trend[1]) and trend[1] != 1
down := na(up[1]) ? up : up[1]
arrowDown := down + atr2
arrowDown
else
down := na(down[1]) ? minHighPrice : math.min(minHighPrice, down[1])
down
atrHigh := down + dev
atrLow := down - dev
atrLow
ht = trend == 0 ? up : down
var color buyColor = color.blue
var color sellColor = color.red
htColor = trend == 0 ? buyColor : sellColor
htPlot = plot(ht, title='HalfTrend', linewidth=2, color=htColor)
atrHighPlot = plot(showChannels ? atrHigh : na, title='ATR High', style=plot.style_circles, color=color.new(sellColor, 0))
atrLowPlot = plot(showChannels ? atrLow : na, title='ATR Low', style=plot.style_circles, color=color.new(buyColor, 0))
fill(htPlot, atrHighPlot, title='ATR High Ribbon', color=color.new(sellColor, 90))
fill(htPlot, atrLowPlot, title='ATR Low Ribbon', color=color.new(buyColor, 90))
buySignal = not na(arrowUp) and trend == 0 and trend[1] == 1
sellSignal = not na(arrowDown) and trend == 1 and trend[1] == 0
plotshape(showArrows and buySignal ? atrLow : na, title='Arrow Up', style=shape.triangleup, location=location.absolute, size=size.tiny, color=color.new(buyColor, 0))
plotshape(showArrows and sellSignal ? atrHigh : na, title='Arrow Down', style=shape.triangledown, location=location.absolute, size=size.tiny, color=color.new(sellColor, 0))
alertcondition(buySignal, title='Alert: HalfTrend Buy', message='HalfTrend Buy')
alertcondition(sellSignal, title='Alert: HalfTrend Sell', message='HalfTrend Sell')
halfTrendLongEntry = buySignal
halfTrendShortEntry = sellSignal
//////////////////////////////////////
//* Put your strategy rules below *//
/////////////////////////////////////
i_numLookbackBarsHull = input(3,title="Max Number Of Bars Between Hull and HalfTrend Trigger", group="Global")
longCondition = halfTrendLongEntry and ta.barssince(hullLongEntry) <= i_numLookbackBarsHull
shortCondition = halfTrendShortEntry and ta.barssince(hullShortEntry) <= i_numLookbackBarsHull
//define as 0 if do not want to use
closeLongCondition = 0
closeShortCondition = 0
// EMA Filter
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_emaFilterEnabled = input.bool(defval = false , title = "Enable EMA Filter", tooltip = "Enable if you would like to conditionally have entries incorporate EMA as a filter where source is above/below the EMA line", group ="EMA Filter" )
i_emaLength = input.int(200, title="EMA Length", minval=1, group ="EMA Filter")
i_emaSource = input.source(close,"EMA Source" , group ="EMA Filter")
emaValue = i_emaFilterEnabled ? ta.ema(i_emaSource, i_emaLength) : na
bool isEMAFilterEnabledAndCloseAboveMA = i_emaFilterEnabled ? i_emaSource > emaValue : true
bool isEMAFilterEnabledAndCloseBelowMA = i_emaFilterEnabled ? i_emaSource < emaValue : true
// ADX Filter
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_adxFilterEnabled = input.bool(defval = false , title = "Enable ADX Filter", tooltip = "Enable if you would like to conditionally have entries incorporate ADX as a filter", group ="ADX Filter" )
i_adxVariant = input.string('ORIGINAL', title='ADX Variant', options=['ORIGINAL', 'MASANAKAMURA'], group ="ADX Filter" )
i_adxSmoothing = input.int(14, title="ADX Smoothing", group="ADX Filter")
i_adxDILength = input.int(14, title="DI Length", group="ADX Filter")
i_adxLowerThreshold = input.float(25, title="ADX Threshold", step=.5, group="ADX Filter")
calcADX_Masanakamura(int _len) =>
_smoothedTrueRange = 0.0
_smoothedDirectionalMovementPlus = 0.0
_smoothed_directionalMovementMinus = 0.0
_trueRange = math.max(math.max(high - low, math.abs(high - nz(close[1]))), math.abs(low - nz(close[1])))
_directionalMovementPlus = high - nz(high[1]) > nz(low[1]) - low ? math.max(high - nz(high[1]), 0) : 0
_directionalMovementMinus = nz(low[1]) - low > high - nz(high[1]) ? math.max(nz(low[1]) - low, 0) : 0
_smoothedTrueRange := nz(_smoothedTrueRange[1]) - nz(_smoothedTrueRange[1]) / _len + _trueRange
_smoothedDirectionalMovementPlus := nz(_smoothedDirectionalMovementPlus[1]) - nz(_smoothedDirectionalMovementPlus[1]) / _len + _directionalMovementPlus
_smoothed_directionalMovementMinus := nz(_smoothed_directionalMovementMinus[1]) - nz(_smoothed_directionalMovementMinus[1]) / _len + _directionalMovementMinus
DIP = _smoothedDirectionalMovementPlus / _smoothedTrueRange * 100
DIM = _smoothed_directionalMovementMinus / _smoothedTrueRange * 100
_DX = math.abs(DIP - DIM) / (DIP + DIM) * 100
adx = ta.sma(_DX, _len)
[DIP, DIM, adx]
[DIPlusO, DIMinusO, ADXO] = ta.dmi(i_adxDILength, i_adxSmoothing)
[DIPlusM, DIMinusM, ADXM] = calcADX_Masanakamura(i_adxDILength)
adx = i_adxFilterEnabled and i_adxVariant == "ORIGINAL" ? ADXO : ADXM
bool isADXFilterEnabledAndAboveThreshold = i_adxFilterEnabled ? adx > i_adxLowerThreshold : true
///Start / End Time Periods
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_startPeriodEnabled = input.bool(true, 'Start', group='Date Range', inline='Start Period')
i_startPeriodTime = input.time(timestamp('1 Jan 2019'), '', group='Date Range', inline='Start Period')
i_endPeriodEnabled = input.bool(true, 'End', group='Date Range', inline='End Period')
i_endPeriodTime = input.time(timestamp('31 Dec 2030'), '', group='Date Range', inline='End Period')
isStartPeriodEnabledAndInRange = i_startPeriodEnabled ? i_startPeriodTime <= time : true
isEndPeriodEnabledAndInRange = i_endPeriodEnabled ? i_endPeriodTime >= time : true
// Time-Of-Day Window
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Inspired from https://www.tradingview.com/script/3BmID7aW-Highlight-Trading-Window-Simple-Hours-Time-of-Day-Filter/
i_timeFilterEnabled = input.bool(defval = false , title = "Enable Time-Of-Day Window", tooltip = "Limit the time of day for trade execution", group ="Time Window" )
i_timeZone = input.string(title="Select Local Time Zone", defval="GMT-5", options=["GMT-8","GMT-7", "GMT-6", "GMT-5", "GMT-4", "GMT-3", "GMT-2", "GMT-1", "GMT", "GMT+1", "GMT+2", "GMT+3","GMT+4","GMT+5","GMT+6","GMT+7","GMT+8","GMT+9","GMT+10","GMT+11","GMT+12","GMT+13"], group="Time Window")
i_betweenTime = input.session('0700-0900', title = "Time Filter", group="Time Window") // '0000-0000' is anytime to enter
isWithinWindowOfTime(_position) =>
currentTimeIsWithinWindowOfTime = not na(time(timeframe.period, _position + ':1234567', i_timeZone))
bool isTimeFilterEnabledAndInRange = i_timeFilterEnabled ? isWithinWindowOfTime(i_betweenTime) : true
isStartEndPeriodsAndTimeInRange = isStartPeriodEnabledAndInRange and isEndPeriodEnabledAndInRange and isTimeFilterEnabledAndInRange
// Trade Direction
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_tradeDirection = input.string('Long and Short', title='Trade Direction', options=['Long and Short', 'Long Only', 'Short Only'], group='Trade Direction')
// Percent as Points
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
per(pcnt) =>
strategy.position_size != 0 ? math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na)
// Take profit 1
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_takeProfitTargetPercent1 = input.float(title='Take Profit 1 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 1')
i_takeProfitQuantityPercent1 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 1')
// Take profit 2
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_takeProfitTargetPercent2 = input.float(title='Take Profit 2 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 2')
i_takeProfitQuantityPercent2 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 2')
// Take profit 3
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_takeProfitTargetPercent3 = input.float(title='Take Profit 3 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 3')
i_takeProfitQuantityPercent3 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 3')
// Take profit 4
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_takeProfitTargetPercent4 = input.float(title='Take Profit 4 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit')
/// Stop Loss
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_stopLossPercent = input.float(title='Stop Loss (%)', defval=999, minval=0.01, step=0.5, group='Stop Loss') * 0.01
slLongClose = close < strategy.position_avg_price * (1 - i_stopLossPercent)
slShortClose = close > strategy.position_avg_price * (1 + i_stopLossPercent)
/// Leverage
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_leverage = input.float(1, 'Leverage', step=.5, group='Leverage')
contracts = math.min(math.max(.000001, strategy.equity / close * i_leverage), 1000000000)
/// Trade State Management
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
isInLongPosition = strategy.position_size > 0
isInShortPosition = strategy.position_size < 0
/// ProfitView Alert Syntax String Generation
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_alertSyntaxPrefix = input.string(defval='CRYPTANEX_99FTX_Strategy-Name-Here', title='Alert Syntax Prefix', group='ProfitView Alert Syntax')
alertSyntaxBase = i_alertSyntaxPrefix + '\n#' + str.tostring(open) + ',' + str.tostring(high) + ',' + str.tostring(low) + ',' + str.tostring(close) + ',' + str.tostring(volume) + ','
/// Trade Execution
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
longConditionCalc = (longCondition and isADXFilterEnabledAndAboveThreshold and isEMAFilterEnabledAndCloseAboveMA)
shortConditionCalc = (shortCondition and isADXFilterEnabledAndAboveThreshold and isEMAFilterEnabledAndCloseBelowMA)
if isStartEndPeriodsAndTimeInRange
if longConditionCalc and i_tradeDirection != 'Short Only' and isInLongPosition == false
strategy.entry('Long', strategy.long, qty=contracts)
alert(message=alertSyntaxBase + 'side:long', freq=alert.freq_once_per_bar_close)
if shortConditionCalc and i_tradeDirection != 'Long Only' and isInShortPosition == false
strategy.entry('Short', strategy.short, qty=contracts)
alert(message=alertSyntaxBase + 'side:short', freq=alert.freq_once_per_bar_close)
//Inspired from Multiple %% profit exits example by adolgo https://www.tradingview.com/script/kHhCik9f-Multiple-profit-exits-example/
strategy.exit('TP1', qty_percent=i_takeProfitQuantityPercent1, profit=per(i_takeProfitTargetPercent1))
strategy.exit('TP2', qty_percent=i_takeProfitQuantityPercent2, profit=per(i_takeProfitTargetPercent2))
strategy.exit('TP3', qty_percent=i_takeProfitQuantityPercent3, profit=per(i_takeProfitTargetPercent3))
strategy.exit('i_takeProfitTargetPercent4', profit=per(i_takeProfitTargetPercent4))
// Stop Loss
strategy.close('Long', qty_percent=100, comment='SL Long', when=slLongClose)
strategy.close('Short', qty_percent=100, comment='SL Short', when=slShortClose)
// Conditional Closes
strategy.close('Long', qty_percent=100, comment='Close Long', when=closeLongCondition)
strategy.close('Short', qty_percent=100, comment='Close Short', when=closeShortCondition)
/// Dashboard
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Inspired by https://www.tradingview.com/script/uWqKX6A2/ - Thanks VertMT
showDashboard = input.bool(group="Dashboard", title="Show Dashboard", defval=true)
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
_cellText = _title + "\n" + _value
table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=size.auto)
// Draw dashboard table
if showDashboard
var bgcolor = color.new(color.black,0)
// Keep track of Wins/Losses streaks
newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
varip int winRow = 0
varip int lossRow = 0
varip int maxWinRow = 0
varip int maxLossRow = 0
if newWin
lossRow := 0
winRow := winRow + 1
if winRow > maxWinRow
maxWinRow := winRow
if newLoss
winRow := 0
lossRow := lossRow + 1
if lossRow > maxLossRow
maxLossRow := lossRow
// Prepare stats table
var table dashTable = table.new(position.bottom_right, 1, 15, border_width=1)
if barstate.islastconfirmedhistory
// Update table
dollarReturn = strategy.netprofit
f_fillCell(dashTable, 0, 0, "Start:", str.format("{0,date,long}", strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.closedtrades.entry_time(0))
f_fillCell(dashTable, 0, 1, "End:", str.format("{0,date,long}", strategy.opentrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.opentrades.entry_time(0))
_profit = (strategy.netprofit / strategy.initial_capital) * 100
f_fillCell(dashTable, 0, 2, "Net Profit:", str.tostring(_profit, '##.##') + "%", _profit > 0 ? color.green : color.red, color.white)
_numOfDaysInStrategy = (strategy.opentrades.entry_time(0) - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24)
f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit / _numOfDaysInStrategy, '#########################.#####')+"%", _profit > 0 ? color.green : color.red, color.white)
_winRate = ( strategy.wintrades / strategy.closedtrades ) * 100
f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? color.red : _winRate < 75 ? #999900 : color.green, color.white)
f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? color.green : color.red, color.white)
f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white)
f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white)
f_fillCell(dashTable, 0, 9, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white) |
Open Drive | https://www.tradingview.com/script/nyTw4KmR-Open-Drive/ | Marcn5_ | https://www.tradingview.com/u/Marcn5_/ | 158 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Marcns_
//@version=5
// a script that highlights open drives around cash market opens throughout the day
// this indicator identifies the following cash open, open drives 0700 - 0715 / 0800 - 0815 / 1300 - 1315 / 1430 - 1445
// an open drive is when a cash market opens and price runs either up or down away from the opening price, often this will be the high or the low the remainer of the session or day
// and often identify a trend session
strategy("Open Drive", commission_type = strategy.commission.cash_per_contract, commission_value = 3.8, initial_capital = 40000 )
// open drive filter times - all times GMT
eu_sev = time(timeframe.period, "0700-0715", "GB")
eu_eig = time(timeframe.period, "0800-0815", "GB")
us_one = time(timeframe.period, "1300-1315", "GB")
us_two = time(timeframe.period, "1430-1445", "GB")
// identify bar that opens at low and closes at high + vice versa
// bar needs to open at one extreme and close at another
TrndExThreshold_Open = 0.15
TrndExThreshold_Close = 0.15
// add a bar range expansion filter - range of bar correlates to volume, high volume = wider range. This script will be able to filter for a break of a 5 bar range +100% or -100%
fbhi = ta.highest(5)
fblo = ta.lowest(5)
fbr = (fbhi - fblo)
RangeEx_up = 0.0
if high >= (fbhi[1] + fbr[1])
RangeEx_up := 1.0
else
na
// range ex down
RangeEx_do = 0.0
if low <= (fblo[1] - fbr[1])
RangeEx_do := 1.0
else
na
//#1 open within 5% of low
OpenAtLow = 0.0
if (close > open) and (open-low) / (high-low) < TrndExThreshold_Open
OpenAtLow := 1.0
else
na
//#2 close within 5% of high
CloseAtHigh = 0.0
if (close > open) and (high-close) / (high-low) < TrndExThreshold_Close
CloseAtHigh := 1.0
else
na
OD_Up = 0.0
if (OpenAtLow + CloseAtHigh + RangeEx_up == 3.0) and ( eu_sev or eu_eig or us_one or us_two)
OD_Up := 1
else
na
plot(OD_Up, title = "OD_up")
OpenAtHigh = 0.0
if (close < open) and (high-open) / (high-low) < TrndExThreshold_Open
OpenAtHigh := 1.0
else
na
//#2 close within 5% of high
CloseAtLow = 0.0
if (close < open) and (close-low) / (high-low) < TrndExThreshold_Close
CloseAtLow := 1.0
else
na
OD_Down = 0.0
if (OpenAtHigh + CloseAtLow + RangeEx_do == 3.0) and ( eu_sev or eu_eig or us_one or us_two)
OD_Down := -1
else
na
plot(OD_Down, title = "OD_down", color = color.red)
//3sma
ma = ta.sma(close,3)
// one time framing - highlight bars the make a series of lower highs or higher lows to identify trend
// one time frame up
otf_u = 0.0
if close > ma and close[1] > ma[1]
otf_u := 1
else
na
// one time frame down
otf_d = 0.0
if close < ma and close[1] < ma[1]
otf_d := 1
else
na
//bgcolor(otf_u ? color.rgb(76, 175, 79, 70) : na)
//bgcolor(otf_d ? color.rgb(255, 82, 82, 66) : na)
// record high and low of entry bar into variable for absolute stop
// buy stop
bs = 0.0
if OD_Up
bs := low[1]
else
na
// sell stop
ss = 0.0
if OD_Down
ss := high[1]
else
na
// strategy entry and exits
// long
if OD_Up
strategy.entry("el", strategy.long, 2)
if ta.barssince(OD_Up)> 3
strategy.exit(id = "ex" , from_entry = "el", limit = close)
// short
if OD_Down
strategy.entry("es", strategy.short, 2)
if ta.barssince(OD_Down)> 3
strategy.exit(id = "ex" , from_entry = "es", limit = close)
|
iMoku (Ichimoku Complete Tool) - The Quant Science | https://www.tradingview.com/script/aKBYGQpf-iMoku-Ichimoku-Complete-Tool-The-Quant-Science/ | thequantscience | https://www.tradingview.com/u/thequantscience/ | 404 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © thequantscience
/////////////////////////////// Design by The Quant Science ™ ////////////////////////////////////
start = 1000
//@version=5
strategy(" iMoku - The Quant Science ™ ",
overlay = true,
default_qty_type = strategy.percent_of_equity,
default_qty_value = 100,
currency = currency.EUR,
initial_capital = start,
commission_type = strategy.commission.percent,
commission_value = 0.10,
slippage = 1)
conversionPeriods = input.int(
9,
minval=1,
title="Tenkan Sen Length",
group = "Indicator configuration"
)
basePeriods = input.int(
26, minval=1,
title="Kjun Sen Length",
group = "Indicator configuration"
)
laggingSpan2Periods = input.int(
52,
minval=1,
title="Leading Span B Length",
group = "Indicator configuration"
)
displacement = input.int(
26, minval=1,
title="Lagging Span",
group = "Indicator configuration"
)
strategy_1 = input.bool(
false,
title = "Tenkan Sen - Kijun Sen Strategy",
group = "Tenkan Sen - Kijun Sen Strategy Configuration"
)
strategy_2 = input.bool(
false,
title = "Price - Kijun Sen Strategy",
group = "Price - Kijun Sen Strategy Configuration"
)
strategy_3 = input.bool(
false,
title = "Kumo Breakout Strategy",
group = "Kumo Breakout Strategy Configuration"
)
strategy_4 = input.bool(
false,
title = "Kumo Twist Strategy",
group = "Kumo Twist Strategy Configuration"
)
stop_loss = input.float(
defval = 1,
minval = 0.01,
step = 0.05,
maxval = 500,
title = "Stop Loss",
group = "Kumo Breakout Strategy Configuration"
)
take_profit = input.float(
defval = 1,
minval = 0.01,
step = 0.05,
maxval = 500,
title = "Take Profit",
group = "Kumo Breakout Strategy Configuration"
)
// ########################################################################################################################
// ########################################################################################################################
// ########################################################################################################################
// ########################################################################################################################
// ########################################################################################################################
// ########################################################################################################################
// ########################################################################################################################
donchian(len) => math.avg(
ta.lowest(
len
),
ta.highest(
len
))
conversionLine = donchian(
conversionPeriods
)
baseLine = donchian(
basePeriods
)
leadLine1 = math.avg(
conversionLine,
baseLine
)
leadLine2 = donchian(
laggingSpan2Periods
)
adj_leadLine1 = leadLine1[displacement -1]
adj_leadLine2 = leadLine2[displacement -1]
// 1. Cross Tenkan Sen - Kijun Sen
price_over_kumo = close > adj_leadLine1
price_under_kumo = close < adj_leadLine2
price_in_kumo = close > adj_leadLine1
and close < adj_leadLine2
strong_xover_tenkan_kijun = ta.crossover(
conversionLine,
baseLine
)
and price_over_kumo
neutro_xover_tenkan_kijun = ta.crossover(
conversionLine,
baseLine
)
and price_in_kumo
light_xover_tenkan_kijun = ta.crossover(
conversionLine,
baseLine
)
and price_under_kumo
close_tenkan_kijun = ta.crossunder(
conversionLine,
baseLine
)
SelectTenkanKijun(type) =>
switch type
"Strong Crossover Tenkan Sen - Kijun Sen" => strong_xover_tenkan_kijun
"Neutro Crossover Tenkan Sen - Kijun Sen" => neutro_xover_tenkan_kijun
"Light Crossover Tenkan Sen - Kijun Sen" => light_xover_tenkan_kijun
type_input = input.string(
"Strong Crossover Tenkan Sen - Kijun Sen",
title = "Select strategy: ",
options = ["Strong Crossover Tenkan Sen - Kijun Sen", "Neutro Crossover Tenkan Sen - Kijun Sen", "Light Crossover Tenkan Sen - Kijun Sen" ],
tooltip = "",
group = "Tenkan Sen - Kijun Sen Strategy Configuration"
)
select_tenkan_kijun = SelectTenkanKijun(
type_input
)
and barstate.isconfirmed
price_entry_tenkan_kijun = ta.valuewhen(
select_tenkan_kijun,
close,
0
)
// 2. Cross Price - Kijun Sen
strong_xover_price_kijun = ta.crossover(
close,
baseLine
)
and price_over_kumo
neutro_xover_price_kijun = ta.crossover(
close,
baseLine
)
and price_in_kumo
light_xover_price_kijun = ta.crossover(
close,
baseLine
)
and price_under_kumo
close_price_kijun = ta.crossunder(
close,
baseLine
)
SelectPriceKijun(type) =>
switch type
"Strong Crossover Price - Kijun Sen" => strong_xover_price_kijun
"Neutro Crossover Price - Kijun Sen" => neutro_xover_price_kijun
"Light Crossover Price - Kijun Sen" => light_xover_price_kijun
type_input_2 = input.string(
"Strong Crossover Price - Kijun Sen",
title = "Select strategy: ",
options = ["Strong Crossover Price - Kijun Sen", "Neutro Crossover Price - Kijun Sen", "Light Crossover Price - Kijun Sen" ],
tooltip = "",
group = "Price - Kijun Sen Strategy Configuration"
)
select_price_kijun = SelectPriceKijun(
type_input_2
)
and barstate.isconfirmed
price_entry_price_kijun = ta.valuewhen(
select_price_kijun,
close,
0
)
// 3. Kumo breakout
kumo_breakout = ta.crossover(
close,
adj_leadLine1
)
// 4. Kumo Twist
strong_kumo_twist = ta.crossover(
adj_leadLine1,
adj_leadLine2
)
and price_over_kumo
light_kumo_twist = ta.crossover(
adj_leadLine1,
adj_leadLine2
)
and price_under_kumo
close_kumo_twist = ta.crossunder(
adj_leadLine1,
adj_leadLine2)
SelectKumoTwist(type) =>
switch type
"Strong Crossover Kumo Twist" => strong_kumo_twist
"Light Crossover Kumo Twist" => light_kumo_twist
type_input_3 = input.string(
"Strong Crossover Kumo Twist",
title = "Select strategy: ",
options = ["Strong Crossover Kumo Twist", "Light Crossover Kumo Twist" ],
tooltip = "",
group = "Kumo Twist Strategy Configuration"
)
select_kumo_twist = SelectKumoTwist(
type_input_3
)
and barstate.isconfirmed
price_entry_kumo_twist = ta.valuewhen(
select_kumo_twist,
close,
0
)
// ########################################################################################################################
var tb = table.new(
position.bottom_left,
1, 1,
bgcolor = color.new(
color.blue,
90
))
if barstate.isfirst
table.cell(
tb,
0, 0,
'Developed by The Quant Science™'
,text_size = size.normal
,text_color = color.new(
color.blue,
20
))
// ########################################################################################################################
// ########################################################################################################################
// ########################################################################################################################
// ########################################################################################################################
// ########################################################################################################################
// ########################################################################################################################
entry_string_1 = input.string(
title = "Entry string:",
defval = "#######",
confirm = false,
group = "Tenkan Sen - Kijun Sen Strategy Configuration",
tooltip = "Enter 3Commas or Cryptohopper string link. Enter only the open entry link in this field."
)
exit_string_1 = input.string(
title = "Exit string:",
defval = "#######",
confirm = false,
group = "Tenkan Sen - Kijun Sen Strategy Configuration",
tooltip = "Enter 3Commas or Cryptohopper string link. Enter only the close exit link in this field."
)
isLong = false
isLong := nz(
isLong[1],
false
)
isSellLong = false
isSellLong := nz(
isSellLong[1],
false
)
LONG = not isLong and select_tenkan_kijun
price_1 = ta.valuewhen(
LONG,
close,
0
)
lot_1 = start / price_1
CLOSE_LONG = not isSellLong and close_tenkan_kijun
if (LONG) and strategy_1 == true
isLong := true
isSellLong := false
strategy.entry(
id = "Tenkan Kijun Open",
direction = strategy.long,
qty = lot_1,
limit = price_entry_tenkan_kijun
)
alert(
entry_string_1,
alert.freq_once_per_bar
)
if (CLOSE_LONG) and strategy_1 == true
isLong := false
isSellLong := true
strategy.close_all(
comment = "Tenkan Kijun Closing"
)
alert(
exit_string_1,
alert.freq_once_per_bar
)
// ########################################################################################################################
entry_string_2 = input.string(
title = "Entry string:",
defval = "#######",
confirm = false,
group = "Price - Kijun Sen Strategy Configuration",
tooltip = "Enter 3Commas or Cryptohopper string link. Enter only the open entry link in this field."
)
exit_string_2 = input.string(
title = "Exit string:",
defval = "#######",
confirm = false,
group = "Price - Kijun Sen Strategy Configuration",
tooltip = "Enter 3Commas or Cryptohopper string link. Enter only the close exit link in this field."
)
isLong_2 = false
isLong_2 := nz(
isLong_2[1],
false
)
isSellLong_2 = false
isSellLong_2 := nz(
isSellLong_2[1],
false
)
LONG_2 = not isLong_2 and select_price_kijun
price_2 = ta.valuewhen(
LONG_2,
close,
0
)
lot_2 = start / price_2
CLOSE_LONG_2 = not isSellLong_2 and close_price_kijun
if (LONG_2) and strategy_2 == true
isLong_2 := true
isSellLong_2 := false
strategy.entry(
id = "Price Kijun Open",
direction = strategy.long,
qty = lot_2,
limit = price_entry_price_kijun
)
alert(
entry_string_2,
alert.freq_once_per_bar
)
if (CLOSE_LONG_2) and strategy_2 == true
isLong_2 := false
isSellLong_2 := true
strategy.close_all(comment = "Price Kijun Closing")
alert(
exit_string_2,
alert.freq_once_per_bar
)
// ########################################################################################################################
entry_string_3 = input.string(
title = "Entry string:",
defval = "#######",
confirm = false,
group = "Kumo Breakout Strategy Configuration",
tooltip = "Enter 3Commas or Cryptohopper string link. Enter only the open entry link in this field."
)
exit_string_3 = input.string(
title = "Exit string:",
defval = "#######",
confirm = false,
group = "Kumo Breakout Strategy Configuration",
tooltip = "Enter 3Commas or Cryptohopper string link. Enter only the close exit link in this field."
)
isLong_3 = false
isLong_3 := nz(
isLong_3[1],
false
)
isSellLong_3 = false
isSellLong_3 := nz(
isSellLong_3[1],
false
)
LONG_3 = not isLong_3 and kumo_breakout
price_kumobrk = ta.valuewhen(
LONG_3,
close,
0
)
lot_3 = start / price_kumobrk
take_profit_kumobrk_price = (
price_kumobrk * (
100 +
take_profit
) / 100
)
stop_loss_kumobrk_price = (
price_kumobrk * (
100 -
stop_loss
) / 100
)
if (LONG_3) and strategy_3 == true
isLong_3 := true
isSellLong_3 := false
strategy.entry(
id = "Kumo Breakout Open",
direction = strategy.long,
qty = lot_3,
limit = price_kumobrk
)
alert(
entry_string_3,
alert.freq_once_per_bar
)
if (take_profit_kumobrk_price)
isLong_3 := false
isSellLong_3 := true
strategy.exit(
id = "Kumo Breakout Closing",
from_entry = "Kumo Breakout Open",
limit = take_profit_kumobrk_price,
stop = stop_loss_kumobrk_price
)
alert(
exit_string_3,
alert.freq_once_per_bar
)
if (stop_loss_kumobrk_price)
isLong_3 := false
isSellLong_3 := true
strategy.exit(
id = "Kumo Breakout Closing",
from_entry = "Kumo Breakout Open",
limit = take_profit_kumobrk_price,
stop = stop_loss_kumobrk_price
)
alert(
exit_string_3,
alert.freq_once_per_bar
)
// ########################################################################################################################
entry_string_4 = input.string(
title = "Entry string:",
defval = "#######",
confirm = false,
group = "Kumo Twist Strategy Configuration",
tooltip = "Enter 3Commas or Cryptohopper string link. Enter only the open entry link in this field."
)
exit_string_4 = input.string(
title = "Exit string:",
defval = "#######",
confirm = false,
group = "Kumo Twist Strategy Configuration",
tooltip = "Enter 3Commas or Cryptohopper string link. Enter only the close exit link in this field."
)
isLong_4 = false
isLong_4 := nz(
isLong_4[1],
false
)
isSellLong_4 = false
isSellLong_4 := nz(
isSellLong_4[1],
false
)
LONG_4 = not isLong_4 and select_kumo_twist
price_4 = ta.valuewhen(
LONG_4,
close,
0
)
lot_4 = start / price_4
CLOSE_LONG_4 = not isSellLong_4 and close_kumo_twist
if (LONG_4) and strategy_4 == true
isLong_4 := true
isSellLong_4 := false
strategy.entry(
id = "Kumo Twist Open",
direction = strategy.long,
qty = lot_4,
limit = price_entry_kumo_twist
)
alert(
entry_string_4,
alert.freq_once_per_bar
)
if (CLOSE_LONG_4) and strategy_4 == true
isLong_4 := false
isSellLong_4 := true
strategy.close_all(comment = "Kumo Twist Closing")
alert(
exit_string_4,
alert.freq_once_per_bar
)
// ########################################################################################################################
// ########################################################################################################################
// ########################################################################################################################
// ########################################################################################################################
// ########################################################################################################################
plot(
conversionLine,
color =color.new(
color.aqua,
65),
title = "Conversion Line or Tenkan Sen"
)
plot(
baseLine,
color=color.new(
color.purple,
65),
title="Base Line or Kijun Sen"
)
plot(
close,
offset = -displacement + 1,
color= color.new(
color.gray,
85
),
title="Lagging Span Chokou"
)
p1 = plot(
leadLine1,
offset = displacement - 1,
color= color.aqua,
title="Leading Span A"
)
p2 = plot(
leadLine2,
offset = displacement - 1,
color= color.aqua,
title="Leading Span B"
)
fill(
p1,
p2,
color = leadLine1 > leadLine2 ? color.rgb(
21, 149, 253, 90
) : color.rgb(
21, 149, 253, 90
))
// ########################################################################################################################
// ########################################################################################################################
// ########################################################################################################################
// ########################################################################################################################
// ########################################################################################################################
|
CM_SlingShotSystem+_CassicEMA+Willams21EMA13 htc1977 edition | https://www.tradingview.com/script/PHjfLCaN-cm-slingshotsystem-cassicema-willams21ema13-htc1977-edition/ | Arivadis | https://www.tradingview.com/u/Arivadis/ | 68 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © svatvlad1993
//@version=5
strategy("CM_SlingShotSystem", overlay=true, margin_long = 100, margin_short = 100, initial_capital = 500, currency=currency.USDT, calc_on_every_tick = false)
// do not use 'calc_on_every_tick = true', better to use lower timeframe
// if You strong need - you can, but the part of code(some variables) should be overwritten
// CM_SLING_SHOT_SYSTEM
// Has updated for pinescript v5
// this is first indicator you provided https://tr.tradingview.com/script/GE7tSQK1-CM-Sling-Shot-System/
// this indicator based on EMA, so there are some reasons to use much bigger/lower EMA classic(see below)
sae = input(true, title="Show Aggressive Entry?, Or Use as Alert To Potential Conservative Entry?")
sce = input(true, title="Show Conservative Entry?")
st = input(true, title="Show Trend Arrows at Top and Bottom of Screen?")
def = input(false, title="Only Choose 1 - Either Conservative Entry Arrows or 'B'-'S' Letters")
pa = input(true, title="Show Conservative Entry Arrows?")
sl = input(false, title="Show 'B'-'S' Letters?")
// EMA Definitions
// This part for input each EMA for CM_SLING_SHOT_SYSTEM
CM_SLING_SHOT_emaSlow_input = input.int(62 ,minval = 2)
CM_SLING_SHOT_emaFast_input = input.int(38, minval = 1)
emaSlow = ta.ema(close, CM_SLING_SHOT_emaSlow_input)
emaFast = ta.ema(close, CM_SLING_SHOT_emaFast_input)
//Aggressive Entry or Alert To Potential Trade
pullbackUpT() => emaFast > emaSlow and close < emaFast
pullbackDnT() => emaFast < emaSlow and close > emaFast
//Conservative Entry Code For Highlight Bars
entryUpT() => emaFast > emaSlow and close[1] < emaFast and close > emaFast
entryDnT() => emaFast < emaSlow and close[1] > emaFast and close < emaFast
//Conservative Entry True/False Condition
entryUpTrend = emaFast > emaSlow and close[1] < emaFast and close > emaFast ? 1 : 0
entryDnTrend = emaFast < emaSlow and close[1] > emaFast and close < emaFast ? 1 : 0
//Define Up and Down Trend for Trend Arrows at Top and Bottom of Screen
upTrend = emaFast >= emaSlow
downTrend = emaFast < emaSlow
//Definition for Conseervative Entry Up and Down PlotArrows
codiff = entryUpTrend == 1 ? entryUpTrend : 0
codiff2 = entryDnTrend == 1 ? entryDnTrend : 0
//Color definition for Moving Averages
col = emaFast > emaSlow ? color.lime : emaFast < emaSlow ? color.red : color.yellow
//Moving Average Plots and Fill
p1 = plot(emaSlow, title="Slow MA", style=plot.style_linebr, linewidth=4, color=col)
p2 = plot(emaFast, title="Fast MA", style=plot.style_linebr, linewidth=2, color=col)
fill(p1, p2, color.new(color.silver, 50))
//Aggressive Entry, Conservative Entry Highlight Bars
barcolor(sae and pullbackUpT() ? color.yellow : sae and pullbackDnT() ? color.yellow : na)
barcolor(sce and entryUpT() ? color.aqua : sce and entryDnT() ? color.aqua : na)
//Trend Triangles at Top and Bottom of Screen
plotshape(st and upTrend ? upTrend : na, title="Conservative Buy Entry Triangle",style=shape.triangleup, location=location.bottom, color=color.new(color.lime, transp=0), offset=0)
plotshape(st and downTrend ? downTrend : na, title="Conservative Short Entry Triangle",style=shape.triangledown, location=location.top, color=color.new(color.red, transp=0), offset=0)
//Plot Arrows OR Letters B and S for Buy Sell Signals
plotarrow(pa and codiff ? codiff : na, title="Up Entry Arrow", colorup=color.new(color.lime, transp=0), maxheight=30, minheight=30)
plotarrow(pa and codiff2*-1 ? codiff2*-1 : na, title="Down Entry Arrow", colordown=color.new(color.red, transp=0), maxheight=30, minheight=30)
plotchar(sl and codiff ? low - ta.tr : na, title="Buy Entry", offset=0, char='B', location=location.absolute, color=color.new(color.lime, transp=0))
plotchar(sl and codiff2 ? high + ta.tr : na, title="Short Entry", offset=0, char='S', location=location.absolute, color=color.new(color.red, transp=0))
// Willams21EMA13 htc1977 edition
// second indicator https://tr.tradingview.com/v/BYEfUEKp/
// input number of candles for diapason
Willams_candles_back_length = input.int(21, minval=1)
upper = ta.highest(Willams_candles_back_length)
lower = ta.lowest(Willams_candles_back_length)
// calc willy
willyout = 100 * (close - upper) / (upper - lower)
src = willyout
Willams_len = input.int(13, minval=1, title="Length")
// compute the EMA of willy
emaout = ta.ema(willyout, Willams_len)
// draw willy and EMA
current_price = close
// EMA classic
// You can use this EMA for bult indicator or/and inside strategy buy logic
// You can ON/OFF EMA for calculating(but for OFF indicator there is another field in settings)
switcher_EMA = input.bool(true)
EMA_classic_len = input.int(200, minval=1, title="Length")
EMA_OHLC = input(close, title="Source")
offset2 = input.int(title="Offset", defval=0, minval=-500, maxval=500)
out2 = ta.ema(EMA_OHLC, EMA_classic_len)
plot(out2, title="EMA", color=color.blue, offset=offset2)
ma(source, length, type) =>
switch type
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"SMMA (RMA)" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)
// choose indicator - for You it is EMA
typeMA2 = input.string(title = "Method", defval = "SMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Smoothing")
smoothingLength2 = input.int(title = "Length", defval = 5, minval = 1, maxval = 100, group="Smoothing")
smoothingLine2 = ma(out2, smoothingLength2, typeMA2)
plot(smoothingLine2, title="Smoothing Line", color=#f37f20, offset=offset2, display=display.none)
// logic for strategy_ema_switcher
var long_EMA_classic = true
var short_EMA_classic = true
if switcher_EMA == true
if close > out2
long_EMA_classic := true
short_EMA_classic := false
else
long_EMA_classic := false
short_EMA_classic := true
else
long_EMA_classic := true
short_EMA_classic := true
// var for entered order + stop_loss for each side
var calc = 0
var cust_stop_long = 0.0
var cust_stop_short = 0.0
if strategy.position_size == 0
cust_stop_long := 0.0
cust_stop_short := 0.0
custom_stop_percent = input.float(0.01, minval = 0.001, title = 'custom stop') //this is 1%, 55% = 0.55
// logict enry order
if calc == 0
if emaFast > emaSlow and ta.crossunder(low, emaFast) and low[1] > emaFast and long_EMA_classic == true
strategy.order('long_entry', strategy.long, 50)
alert('long_signal')
cust_stop_long := close - (close * custom_stop_percent)
strategy.exit('long_entry', stop=cust_stop_long)
calc := 1
if emaFast < emaSlow and ta.crossover(high, emaFast) and high[1] < emaFast and short_EMA_classic == true
strategy.order('short_entry', strategy.short, 50)
alert('short_signal')
cust_stop_short := close + (close * custom_stop_percent)
strategy.exit('short_entry', stop=cust_stop_short)
calc := -1
// logic for close position
if calc == 1 and (emaFast < emaSlow or (emaout > -20 and willyout > -20) or close < cust_stop_long)
strategy.close('long_entry', immediately = true)
calc := 0
if calc == -1 and (emaFast > emaSlow or (emaout < -80 and willyout < -80) or close > cust_stop_short)
strategy.close('short_entry', immediately = true)
calc := 0
plot(strategy.equity)
// a piece of advice
// here are a lot of ema, probably You have to try some else indicators.
// a lot of negative orders were also opened on period of small difference between emaslow and emafast. This could be avoided.
// Play with variables, see profit, gave fan!!!
// Arivadis |
VWMA/SMA 3Commas Bot | https://www.tradingview.com/script/cH5Tjlns-VWMA-SMA-3Commas-Bot/ | CrackingCryptocurrency | https://www.tradingview.com/u/CrackingCryptocurrency/ | 1,105 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Copyright © 2022 by CrackingCryptocurrency
//@version=5
strategy(title="VWMA/SMA 3Commas Bot", shorttitle="VWMA/SMA 3,,, Bot", overlay=true, initial_capital=100, currency="USD",
calc_on_every_tick=false, pyramiding=1, calc_on_order_fills=true, process_orders_on_close = true, commission_type=strategy.commission.percent, commission_value=0.06, margin_long = 0, precision = 8)
// INPUTS:
i_strategySettings = 'Strategy Settings'
i_longTrades = input.bool(defval = true, title = 'Long Trades?', tooltip = 'If enabled, the Strategy will perform Long Trades.', group = i_strategySettings)
i_shortTrades = input.bool(defval = true, title = 'Short Trades?', tooltip = 'If enabled, the Strategy will perform Short Trades.', group = i_strategySettings)
i_risk = input.float(defval = 2.0, title = 'Risk Percentage', minval = 0.1, step = 0.1, tooltip = 'Set your desired Risk per Trade. For example, if you input 2, you will risk 2% of your account per trade.', group = i_strategySettings)
i_entryType = input.string(defval = 'Fast Crosses', title = 'Entry Signal', options = ['Fast Crosses', 'Medium Crosses', 'Slow Crosses'], group = i_strategySettings,
tooltip = 'What signal triggers a trade. Fast Crosses are crosses of the Fast VWMA and Fast SMA. Medium Crosses are crosses of the Medium VWMA and Medium SMA. Slow Crosses are crosses of the Slow VWMA and Slow SMA.')
i_tpmult = input.float(defval = 1.0, title = 'Take Profit Multiple', step = 0.5, tooltip = 'The Average True Range Value at the time of an Entry Trigger will be multiplied against this value to determine your positions Take Profit distance.', group = i_strategySettings)
i_slmult = input.float(defval = 1.5, title = 'Stop Loss Multiple', step = 0.5, tooltip = 'The Average True Range Value at the time of an Entry Trigger will be multiplied against this value to determine your positions Stop Loss distance.', group = i_strategySettings)
i_vwmaSettings = 'VWMA/SMA Settings'
i_lenFastVWMA = input.int(13, title='Fast VWMA Length', minval=1, group = i_vwmaSettings)
i_lenSlowVWMA = input.int(26, title='Slow VWMA Length', minval=1, group = i_vwmaSettings)
i_lenFastSMA = input.int(13, title='Fast SMA Length', minval=1, group = i_vwmaSettings)
i_lenSlowSMA = input.int(26, title='Slow SMA Length', minval=1, group = i_vwmaSettings)
i_src = input(title='Source', defval=close, group = i_vwmaSettings)
// VWMA/SMA Calculations
fastSMA = ta.sma(i_src, i_lenFastSMA)
slowSMA = ta.sma(i_src, i_lenSlowSMA)
fastVWMA = ta.vwma(i_src, i_lenFastVWMA)
slowVWMA = ta.vwma(i_src, i_lenSlowVWMA)
//ATR Calculation
atr = ta.atr(21)
tp = atr * i_tpmult
sl = atr * i_slmult
// Strategy Backtest Limiting Algorithm
backtest_group = 'Backtesting Settings'
i_startTime = input.time(defval=timestamp('01 Jan 2022 13:30 +0000'), title='Backtesting Start Time', group = backtest_group)
i_endTime = input.time(defval=timestamp('31 Dec 2099 19:30 +0000'), title='Backtesting End Time', group = backtest_group)
timeCond = time > i_startTime and time < i_endTime
// Trading Signals
fastUpCross = ta.crossover(fastVWMA, fastSMA)
mediumUpCross = ta.crossover(fastVWMA, slowSMA)
slowUpCross = ta.crossover(slowVWMA, slowSMA)
fastDownCross = ta.crossunder(fastVWMA, fastSMA)
mediumDownCross = ta.crossunder(fastVWMA, slowSMA)
slowDownCross = ta.crossunder(slowVWMA, slowSMA)
longEntry = false
shortEntry = false
if i_entryType == 'Fast Crosses' and timeCond
longEntry := fastUpCross
shortEntry := fastDownCross
if i_entryType == 'Medium Crosses' and timeCond
longEntry := mediumUpCross
shortEntry := mediumDownCross
if i_entryType == 'Slow Crosses' and timeCond
longEntry := slowUpCross
shortEntry := slowDownCross
// Stochastic RSI - For Exiting Trades
stoch_group = 'Stochastic RSI Settings'
useStoch = input.bool(defval = true, title = 'Use Stochastic RSI To Exit?', tooltip = 'If enabled, strategy will exit trades when the RSI crosses in Overbought or Oversold Conditions', group = stoch_group)
k = ta.sma(ta.stoch(close, high, low, 14), 6)
d = ta.sma(k, 3)
stoch_crossunder = ta.crossunder(k, d)
stoch_crossover = ta.crossover(k, d)
stoch_ob_crossunder = ta.crossunder(k, d) ? math.avg(k, d) >= 80 : na
stoch_os_crossover = ta.crossover(k, d) ? math.avg(k, d) <= 20 : na
exitLong = false
exitShort = false
if useStoch
exitLong := stoch_ob_crossunder
exitShort := stoch_os_crossover
// Take Profit and Stop Loss - Here we calculate our Take Profit and Stop Loss Levels at the moment we receive a Trading Signal.
longTakeLevel = 0.0
longTakeLevel := slowUpCross ? close + tp : longTakeLevel[1]
longStopLevel = 0.0
longStopLevel := slowUpCross ? close - sl : longStopLevel[1]
shortTakeLevel = 0.0
shortTakeLevel := slowDownCross ? close - tp : shortTakeLevel[1]
shortStopLevel = 0.0
shortStopLevel := slowDownCross ? close + sl : shortStopLevel[1]
// Position Sizing - This is how we calculate our Position Size for our Backtest and for our DCA Bot.
initialCapital = strategy.initial_capital
balance = initialCapital + strategy.netprofit
risk = i_risk / 100
loss = balance * risk
valueAtClose = ta.valuewhen(slowUpCross, close, 0)
distanceToStop = math.abs(valueAtClose - longStopLevel) / valueAtClose
valueAtCloseShort = ta.valuewhen(slowDownCross, close, 0)
distanceToStopShort = math.abs(valueAtCloseShort - shortStopLevel) / valueAtCloseShort
positionSize = (loss / (distanceToStop / valueAtClose)) / valueAtClose
positionSizeShort = (loss / (distanceToStopShort / valueAtCloseShort)) / valueAtCloseShort
if positionSize > 1000000
positionSize := 1000000
if positionSize < 0
positionSize := 1
if positionSizeShort > 1000000
positionSizeShort := 1000000
if positionSizeShort < 0
positionSizeShort := 1
// Close Function - This will cause the Bot to close the trade when the specified actions occur.
closeFunction = strategy.position_entry_name == 'Long' and high > longTakeLevel or strategy.position_entry_name == 'Long' and low < longStopLevel or strategy.position_entry_name == 'Long' and slowDownCross or exitLong
closeFunctionShort = strategy.position_entry_name == 'Short' and low < shortTakeLevel or strategy.position_entry_name == 'Short' and high > shortStopLevel or strategy.position_entry_name == 'Short' and slowUpCross or exitShort
//Strategy Stuff
strategy.entry('Long', strategy.long, when = longEntry, qty = positionSize)
strategy.entry('Short', strategy.short, when = shortEntry, qty = positionSizeShort)
strategy.exit('Long Exit', from_entry='Long', limit = longTakeLevel, stop = longStopLevel, when = strategy.position_size > 0)
strategy.exit('Short Exit', from_entry = 'Short', limit = shortTakeLevel, stop = shortStopLevel, when = strategy.position_size < 0)
strategy.close('Long', when = closeFunction)
strategy.close('Short', when = closeFunctionShort)
// Automation Stuff
// Note for Users - Simply replace the JSON messages below with your Bot Message from your 3Commas DCA Bot.
// If you have any issues with the Bot not sizing your trades up to your correct position size, try putting a 3-6 second delay in your 'addAlert' variable. Simply replace the 0 after "delay_seconds" with a number between 3-6.
buyAlert = '{ "message_type": "bot", "bot_id": insert your bot id here, "email_token": "insert your email token between these quotes", "delay_seconds": 0}'
exitAlert = '{ "action": "close_at_market_price", "message_type": "bot", "bot_id": insert your bot id here, "email_token": "insert your email token between these quotes", "delay_seconds": 0}'
addAlert = '{ "action": "add_funds_in_quote", "message_type": "bot", "bot_id": insert your bot id here, "email_token": "insert your email token between these quotes", "delay_seconds": 0, "volume":' + str.tostring(positionSize) + '}'
shortAlert = '{ "message_type": "bot", "bot_id": insert your bot id here, "email_token": "insert your email token between these quotes", "delay_seconds": 0}'
exitShortAlert = '{ "action": "close_at_market_price", "message_type": "bot", "bot_id": insert your bot id here, "email_token": "insert your email token between these quotes", "delay_seconds": 0}'
addShortAlert = '{ "action": "add_funds_in_quote", "message_type": "bot", "bot_id": insert your bot id here, "email_token": "insert your email token between these quotes", "delay_seconds": 0, "volume":' + str.tostring(positionSizeShort) + '}'
if longEntry
alert(buyAlert, alert.freq_once_per_bar)
if shortEntry
alert(shortAlert, alert.freq_once_per_bar)
if closeFunction
alert(exitAlert, alert.freq_once_per_bar)
if closeFunctionShort
alert(exitShortAlert, alert.freq_once_per_bar)
if longEntry
alert(addAlert, alert.freq_once_per_bar)
if shortEntry
alert(addShortAlert, alert.freq_once_per_bar)
// Plots
s0 = plot(slowSMA, title='Slow SMA', color=color.new(color.red, 0), linewidth=2)
v0 = plot(slowVWMA, title='Slow VWMA', color=color.new(color.green, 0), linewidth=2)
s1 = plot(fastSMA, title='Fast SMA', color=color.new(color.fuchsia, 0), linewidth=2, style=plot.style_circles)
v1 = plot(fastVWMA, title='Fast VWMA', color=color.new(color.teal, 0), linewidth=2, style=plot.style_circles)
fill(s0, v0, color=slowSMA < slowVWMA ? color.new(color.green, 70) : color.new(color.red, 70))
fill(s1, v1, color=fastSMA < fastVWMA ? color.new(color.teal, 80) : color.new(color.fuchsia, 80)) |
I11L - Reversal Trading Ideas by Larry Connors | https://www.tradingview.com/script/qvbGDFKf/ | I11L | https://www.tradingview.com/u/I11L/ | 119 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © I11L
//@version=5
strategy("I11L - Reversal Trading Ideas by Larry Connors", overlay=false, pyramiding=3, default_qty_value=10000, initial_capital=10000, default_qty_type=strategy.cash,process_orders_on_close=true, calc_on_every_tick=false)
lowestPointBars = input.int(7)
rsiLength = input.int(2)
sellBarrier = input.int(70, step=55)
onlyBuyWhenAbove55Average = input.bool(false)
isLowest = ta.lowest(close,lowestPointBars*(strategy.opentrades+1)) == close
isHighest = ta.rsi(close,rsiLength) > sellBarrier
isBuy = isLowest and (strategy.position_avg_price * (1-0.01*strategy.opentrades) > close or strategy.opentrades == 0) and (close > ta.sma(close, 55) or not(onlyBuyWhenAbove55Average))
isClose = isHighest
plot(ta.rsi(close,rsiLength), color=isBuy ? color.green : isLowest ? color.yellow : color.white)
plot(sellBarrier, color=color.red)
if(isBuy)
strategy.entry("Buy"+str.tostring(strategy.opentrades+1),strategy.long, comment="#"+str.tostring(strategy.opentrades+1))
if(isClose)
strategy.exit("Close",limit=close)
|
Extended Recursive Bands Strategy | https://www.tradingview.com/script/ZE5dQUPR-Extended-Recursive-Bands-Strategy/ | Adulari | https://www.tradingview.com/u/Adulari/ | 336 | strategy | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// @version=5
// Original indicator by alexgrover.
// Strategy version by Adulari, with added functionality.
// Strategy
strategy('Extended Recursive Bands Strategy', overlay=true, commission_type=strategy.commission.percent,commission_value=0.06,default_qty_type =strategy.percent_of_equity,default_qty_value = 100,initial_capital =1000, pyramiding=0)
// Inputs
showTrades = input.bool(false, title='Trades',group='Display Settings', confirm=true,inline='Trades')
showPlots = input.bool(false, title='Plots',group='Display Settings',confirm=true,inline='Trades')
rsiEntry = input.bool(true,title='RSI',group='Entry Conditions')
mfiEntry = input.bool(true,title='MFI',group='Entry Conditions')
adxEntry = input.bool(false,title='ADX',group='Entry Conditions')
cfEntry = input.bool(false, title='CF', group='Entry Conditions')
erbLength = input.int(250,minval=1,step=10, title='Length', group='ERB Settings',inline='Length')
erbSource = input(close, title='Source', group='ERB Settings',inline='Length')
erbMethod = input.string('Classic', options=['Classic', 'ATR', 'STDEV', 'AHLR', 'RFV'], title='Method', group='ERB Settings',inline='Method')
erbLookback = input.int(4,minval=1,title='Lookback', group='ERB Settings',inline='Method')
erbBDC = input.bool(true, title='Bands Direction', group='ERB Settings')
RR = input.float(3.4,title='RR',group='Risk Settings',inline='RR')
atrLength = input.int(14,minval=1,title='Length',inline='Length',group='ATR Settings')
atrMultiplier = input.float(4.0,minval=0.0,step=0.1,title='Multiplier',inline='Length',group='ATR Settings')
rsiLength = input.int(title='Length',minval=1, defval=14, group='RSI Settings',inline='Length')
rsiSource = input(close, title="Source", group='RSI Settings',inline='Length')
rsiOversold = input.int(title='Oversold', minval=0,defval=30, group='RSI Settings',inline='Oversold')
rsiOverbought = input.int(title='Overbought',minval=0, defval=69, group='RSI Settings',inline='Oversold')
mfiLength = input.int(title='Length',minval=1, defval=14, group='MFI Settings',inline='Length')
mfiSource = input(close, title="Source", group='MFI Settings',inline='Length')
mfiOversold = input.int(title='Oversold', minval=0,defval=50, group='MFI Settings',inline='Oversold')
mfiOverbought = input.int(title='Overbought',minval=0, defval=50, group='MFI Settings',inline='Oversold')
cfLength = input.int(59,minval=1, title='Length', group='CF Settings', inline='Length')
cfLookback = input.int(36,minval=1, title='Lookback', group='CF Settings', inline='Length')
adxSmoothing = input.int(24,minval=1, title='ADX Smoothing', group='ADX Settings', inline='ADX Smoothing')
diLength = input.int(24,minval=1, title='DI Length', group='ADX Settings', inline='ADX Smoothing')
adxThreshold = input.float(18,minval=0, title='Threshold', group='ADX Settings', inline='Threshold')
CbTiOD = input.bool(title='Close by Trade in Opposite Direction',defval=true,group='Behavioral Settings')
// Calculate Methods
atr = ta.atr(erbLength)
stdev = ta.stdev(erbSource, erbLength)
ahlr = ta.sma(high - low, erbLength)
rfv = 0.
rfv := ta.rising(erbSource, erbLength) or ta.falling(erbSource, erbLength) ? math.abs(ta.change(erbSource)) : rfv[1]
// Get ERB erbMethod
f(a, b, c) =>
erbMethod == a ? b : c
v(x) =>
f('ATR', atr, f('STDEV', stdev, f('AHLR', ahlr, f('RFV', rfv, x))))
// Recursive Bands
erbSC = 2 / (erbLength + 1)
erbUpperBand = 0.
erbUpperBand := math.max(nz(erbUpperBand[1], erbSource), erbSource) - erbSC * v(math.abs(erbSource - nz(erbUpperBand[1], erbSource)))
erbLowerBand = 0.
erbLowerBand := math.min(nz(erbLowerBand[1], erbSource), erbSource) + erbSC * v(math.abs(erbSource - nz(erbLowerBand[1], erbSource)))
erbMiddleBand = (erbUpperBand+erbLowerBand)/2 // added recursive middle line
erbOpenLong = ta.crossunder(low,erbLowerBand)
erbOpenShort = ta.crossover(high,erbUpperBand)
// RSI
RSI = ta.rsi(rsiSource,rsiLength)
rsiOpenLong = rsiEntry ? RSI<rsiOversold : true
rsiOpenShort = rsiEntry ? RSI>rsiOverbought : true
// MFI
MFI = ta.mfi(mfiSource,mfiLength)
mfiOpenLong = mfiEntry ? MFI<mfiOversold : true
mfiOpenShort = mfiEntry ? MFI>mfiOverbought : true
// ADX
[_,_,ADX] = ta.dmi(diLength,adxSmoothing)
adxOpen = adxEntry ? ADX>adxThreshold : true
// Band Direction by Adulari
bhdUptrendCount = 0
bhdDowntrendCount = 0
for i = 0 to erbLookback-1
if erbLowerBand[i] > erbLowerBand[i+1]
bhdUptrendCount:=bhdUptrendCount+1
if erbUpperBand[i] < erbUpperBand[i+1]
bhdDowntrendCount:=bhdDowntrendCount+1
bhdOpenLong = erbBDC ? bhdUptrendCount==erbLookback : true
bhdOpenShort = erbBDC ? bhdDowntrendCount==erbLookback : true
// ATR
ATR = ta.atr(atrLength)
atrLower = low-atr*atrMultiplier
atrHigher = high+atr*atrMultiplier
// Consolidation Zones by Lonesometheblue
float cfHighestBars = ta.highestbars(cfLookback) == 0 ? high : na
float cfLowestBars = ta.lowestbars(cfLookback) == 0 ? low : na
var int cfDir = 0
float cfZZ = na
float cfPP = na
cfIff = cfLowestBars and na(cfHighestBars) ? -1 : cfDir
cfDir := cfHighestBars and na(cfLowestBars) ? 1 : cfIff
if cfHighestBars and cfLowestBars
if cfDir == 1
cfZZ := cfHighestBars
cfZZ
else
cfZZ := cfLowestBars
cfZZ
else
cfIff = cfLowestBars ? cfLowestBars : na
cfZZ := cfHighestBars ? cfHighestBars : cfIff
cfZZ
for x = 0 to 1000 by 1
if na(close) or cfDir != cfDir[x]
break
if cfZZ[x]
if na(cfPP)
cfPP := cfZZ[x]
cfPP
else
if cfDir[x] == 1 and cfZZ[x] > cfPP
cfPP := cfZZ[x]
cfPP
if cfDir[x] == -1 and cfZZ[x] < cfPP
cfPP := cfZZ[x]
cfPP
var int cfCount = 0
var float cfHigh = na
var float cfLow = na
float cfH = ta.highest(cfLength)
float cfL = ta.lowest(cfLength)
var line cfUpperLine = na
var line cfLowerLine = na
bool cfBreakout = false
bool cfBreakdown = false
if ta.change(cfPP)
if cfCount > cfLength
if cfPP > cfHigh
cfBreakout := true
cfBreakout
if cfPP < cfLow
cfBreakdown := true
cfBreakdown
if cfCount > 0 and cfPP <= cfHigh and cfPP >= cfLow
cfCount += 1
cfCount
else
cfCount := 0
cfCount
else
cfCount += 1
cfCount
if cfCount >= cfLength
if cfCount == cfLength
cfHigh := cfH
cfLow := cfL
cfLow
else
cfHigh := math.max(cfHigh, high)
cfLow := math.min(cfLow, low)
cfLow
cfLowerLine
cfOpen = cfEntry ? cfCount < cfLength : true
// Stop Loss & Take Profit
barsSinceEntry = ta.barssince(bar_index==strategy.opentrades.entry_bar_index(0))
max_bars_back(atrLower, 5000)
max_bars_back(atrHigher, 5000)
longSL = atrLower[barsSinceEntry]
shortSL = atrHigher[barsSinceEntry]
longTP = strategy.position_avg_price+(strategy.position_avg_price-longSL)*RR
shortTP = strategy.position_avg_price-(shortSL-strategy.position_avg_price)*RR
// Conditions
CbTiODLong = CbTiOD ? true : strategy.position_size>0 or strategy.opentrades==0
CbTiODShort = CbTiOD ? true : strategy.position_size<0 or strategy.opentrades==0
openLong = erbOpenLong and bhdOpenLong and rsiOpenLong and adxOpen and cfOpen and CbTiODLong and mfiOpenLong
openShort = erbOpenShort and bhdOpenShort and rsiOpenShort and adxOpen and cfOpen and CbTiODShort and mfiOpenShort
closeLong = (low<longSL or high>longTP)
closeShort = (high>shortSL or low<shortTP)
// Colors
beColor = #675F76
buColor = #a472ff
// Plots
pA = plot(showPlots ? erbUpperBand : na, color=color.new(beColor, 0), linewidth=1, title='Upper Band')
pB = plot(showPlots ? erbLowerBand : na, color=color.new(buColor, 0), linewidth=1, title='Lower Band')
pC = plot(showPlots ? erbMiddleBand : na, color=color.rgb(120,123,134,0), linewidth=1, title='Middle Band')
fill(pC, pA, color=color.new(beColor,95))
fill(pC, pB, color=color.new(buColor,95))
// Orders
if openLong
strategy.entry(id='Long',direction=strategy.long)
if openShort
strategy.entry(id='Short',direction=strategy.short)
if closeLong
strategy.close(id='Long')
if closeShort
strategy.close(id='Short')
// Trade Plots
entryPlot = plot(showTrades ? strategy.opentrades > 0 ? strategy.position_avg_price : na : na, title='Strategy Entry', color=color.rgb(120,123,134,0),style=plot.style_linebr,editable=true)
tpPlot = plot(showTrades ? strategy.position_size > 0 ? longTP : strategy.position_size < 0 ? shortTP : na : na, title='Take Profit', color=buColor,style=plot.style_linebr,editable=true)
slPlot = plot(showTrades ? strategy.position_size > 0 ? longSL : strategy.position_size < 0 ? shortSL : na : na, title='Stop Loss', color=beColor,style=plot.style_linebr,editable=true)
fill(entryPlot,slPlot,color=showTrades ? color.new(beColor,95) : na,editable=true)
fill(entryPlot,tpPlot,color=showTrades ? color.new(buColor,95) : na,editable=true) |
Trend Following based on Trend Confidence | https://www.tradingview.com/script/AZYfvGxf-Trend-Following-based-on-Trend-Confidence/ | carefulCamel61097 | https://www.tradingview.com/u/carefulCamel61097/ | 208 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © carefulCamel61097
// ################################################################################################
// "This is a trend following strategy that performed very well on the past 5 years"
// "Intended to be used on BTC-USDT, 4hr timeframe"
// "A factor 2 Leverage can be added by changing Order Size to 200% of equity"
// "Higher leverage is not recommended due to big drawdowns"
// "Also seems to work on 1D timeframe, although ideal parameters may be different"
// "Also seems to work on ETH-USDT and some other altcoins, although ideal parameters are different"
// ################################################################################################
//@version=5
strategy("Trend Following based on Trend Confidence", overlay=false, pyramiding=1, default_qty_type=strategy.percent_of_equity, default_qty_value=100, margin_long=1./2*50, margin_short=1./2*50, commission_value=0.1, slippage=5, initial_capital=1000)
// Inputs
source = input(close)
since = input.time(timestamp('2000-01-01'), title='Start trading interval')
till = input.time(timestamp('2030-01-01'), title='End trading interval')
length = input(30, title='Length')
longs_on = input.bool(true, title='Longs')
shorts_on = input.bool(true, title='Shorts')
// Parameters for best performance 2018 - 2022
// long_entry = input.float(0.26, step=0.01, title='Long entry threshold')
// long_exit = input.float(-0.10, step=0.01, title='Long exit threshold')
// short_entry = input.float(-0.24, step=0.01, title='Short entry threshold')
// short_exit = input.float(-0.04, step=0.01, title='Short exit threshold')
long_entry = input.float(0.25, step=0.01, title='Long entry threshold')
long_exit = input.float(-0.10, step=0.01, title='Long exit threshold')
short_entry = input.float(-0.25, step=0.01, title='Short entry threshold')
short_exit = input.float(-0.05, step=0.01, title='Short exit threshold')
stop_loss = input.float(10, step=1, title='Stop loss (percentage)') / 100
// Trend Confidence
linreg = ta.linreg(source, length, 0)
linreg_p = ta.linreg(source, length, 0+1)
x = bar_index
slope = linreg - linreg_p
intercept = linreg - x*slope
deviationSum = 0.0
for i = 0 to length-1
deviationSum := deviationSum + math.pow(source[i]-(slope*(x-i)+intercept), 2)
deviation = math.sqrt(deviationSum/(length))
slope_perc = slope / source[0]
deviation_perc = deviation / source[0]
trend_confidence = slope_perc / deviation_perc
// Strategy
in_interval = (time > since) and (time < till)
sl_long = strategy.position_avg_price * (1 - stop_loss)
sl_short = strategy.position_avg_price * (1 + stop_loss)
if in_interval and longs_on and ta.crossover(trend_confidence, long_entry)
strategy.entry("TC Long Entry", strategy.long)
strategy.exit("TC Long Exit", stop=sl_long)
if in_interval and longs_on and ta.crossunder(trend_confidence, long_exit)
strategy.close("TC Long Entry")
if in_interval and shorts_on and ta.crossunder(trend_confidence, short_entry)
strategy.entry("TC Short Entry", strategy.short)
strategy.exit("TC Short Exit", stop=sl_short)
if in_interval and shorts_on and ta.crossover(trend_confidence, short_exit)
strategy.close("TC Short Entry")
// Plots
plot(trend_confidence, "Trend Confidence", color.rgb(255, 255, 255))
plot(long_entry, "", color.rgb(0, 255, 0), linewidth=1)
plot(long_exit, "", color.rgb(255, 0, 0), linewidth=1)
plot(short_entry, "", color=bar_index % 10 == 0 ? color.rgb(0, 255, 0) : #00000000, linewidth=1)
plot(short_exit, "", color=bar_index % 10 == 0 ? color.rgb(255, 0, 0) : #00000000, linewidth=1)
|
SeongMo_MA_V3(Elliot_helper) | https://www.tradingview.com/script/b175MV7o/ | suc1098 | https://www.tradingview.com/u/suc1098/ | 103 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © suc1098
//@version=5
strategy("SeongMo_MA_V3(Elliot_helper)",overlay = true)
var A=close
var B=0.0
var C=0.0
if high[1] < high and low[1] < low //A new high price
if close[1]<close // Rising Candle -> High Point
A:=high
if close[1]>close // Decline candle -> median
A:=(high+low)/2
if high[1] > high and low[1] > low //A new low price
if close[1]>close // // Decline candle -> Low Point
A:=low
if close[1]<close // Rising candle -> median
A:=(high+low)/2
if high[1] > high and low[1] < low // Previous Candle Range
B:=(high[1]+low[1])/2 // After calculating the median of the previous cans
C:= (100*(close-B)/close)// If the absolute value is 0.06 or less, the median value
if C >= -0.06 and C <= 0.06
A:=(high+low)/2
// High point if the closing price is large for the median value of the previous candle and fluctuations above 0.06
if B <= close and C >= 0.06
A:=high
// Low point if the closing price is small and changes below -0.06 for the median of the previous candle
if B >= close and C <= -0.06
A:=low
//Select a reference point after comparing the high and low prices of the reported and new lows simultaneously reached, and the previous and previous candles
if high[1] < high and low[1] > low
if low[2] < low[1]
A:=high
if high[2] < high[1]
A:=low
plot(A,color=color.white)
//Update of new low price for previous candles requires fine counting
plotshape(high[1] < high and low[1] > low and ((100*(high-low)/((high+low)/2))<= -0.6 or (100*(high-low)/((high+low)/2))>= +0.6), "", shape.arrowup,location.abovebar, color=color.rgb(230, 236, 231), text = "Check_candle!") |
Breakeven Line Demo | https://www.tradingview.com/script/XhBOZWmE-Breakeven-Line-Demo/ | Eliza123123 | https://www.tradingview.com/u/Eliza123123/ | 80 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Eliza123123
//@version=5
strategy("Breakeven Line Demo", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value = 0.27,
pyramiding=999, initial_capital=10000, commission_type=strategy.commission.percent, commission_value=0.00)
// Generic signal (not a viable strategy don't use, just some code I wrote quick for demo purposes only)
red = open > close, green = open < close
sevenReds = red and red[1] and red[2] and red[3] and red[4] and red[5] and red[6]
sevenGreens = green and green[1] and green[2] and green[3] and green[4] and green[5] and green[6]
if sevenReds
strategy.entry('Buy', direction=strategy.long)
if sevenGreens
strategy.entry('Sell', direction=strategy.short)
if (hour == 5 and minute == 0 ) or (hour == 11 and minute == 0) or (hour == 17 and minute == 0 ) or (hour == 23 and minute == 0)
strategy.close_all("Close")
// Breakeven line for visualising breakeven price on stacked orders.
var breakEvenLine = 0.0
if strategy.opentrades > 0
breakEvenLine := strategy.position_avg_price
else
breakEvenLine := 0.0
color breakEvenLineColor = na
if strategy.position_size > 0
breakEvenLineColor := #15FF00
if strategy.position_size < 0
breakEvenLineColor := #FF000D
plot(breakEvenLine, color = breakEvenLine and breakEvenLine[1] > 0 ? breakEvenLineColor : na, linewidth = 2, style = plot.style_circles)
|
Fast EMA above Slow EMA with MACD (by Coinrule) | https://www.tradingview.com/script/FG8dCAPM-Fast-EMA-above-Slow-EMA-with-MACD-by-Coinrule/ | Coinrule | https://www.tradingview.com/u/Coinrule/ | 176 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Coinrule
//@version=5
strategy('Fast EMA above Slow EMA with MACD (by Coinrule)',
overlay=true,
initial_capital=1000,
process_orders_on_close=true,
default_qty_type=strategy.percent_of_equity,
default_qty_value=30,
commission_type=strategy.commission.percent,
commission_value=0.1)
showDate = input(defval=true, title='Show Date Range')
timePeriod = time >= timestamp(syminfo.timezone, 2022, 1, 1, 0, 0)
notInTrade = strategy.position_size <= 0
// EMAs
fastEMA = ta.ema(close, 8)
slowEMA = ta.ema(close, 26)
plot(fastEMA, color = color.blue)
plot(slowEMA, color = color.green)
//buyCondition1 = ta.crossover(fastEMA, slowEMA)
buyCondition1 = fastEMA > slowEMA
// DMI and MACD inputs and calculations
[macd, macd_signal, macd_histogram] = ta.macd(close, 12, 26, 9)
buyCondition2 = ta.crossover(macd, macd_signal)
// Configure trail stop level with input options
longTrailPerc = input.float(title='Trail Long Loss (%)', minval=0.0, step=0.1, defval=3) * 0.01
shortTrailPerc = input.float(title='Trail Short Loss (%)', minval=0.0, step=0.1, defval=1) * 0.01
// Determine trail stop loss prices
longStopPrice = 0.0
shortStopPrice = 0.0
longStopPrice := if strategy.position_size > 0
stopValue = close * (1 - longTrailPerc)
math.max(stopValue, longStopPrice[1])
else
0
shortStopPrice := if strategy.position_size < 0
stopValue = close * (1 + shortTrailPerc)
math.min(stopValue, shortStopPrice[1])
else
999999
if (buyCondition1 and buyCondition2 and notInTrade and timePeriod)
strategy.entry(id="Long", direction = strategy.long)
strategy.exit(id="Exit", stop = longStopPrice, limit = shortStopPrice)
//if (sellCondition1 and sellCondition2 and notInTrade and timePeriod)
//strategy.close(id="Close", when = sellCondition1 or sellCondition2) |
Fair Value Strategy Ultimate | https://www.tradingview.com/script/W1XteW0B-Fair-Value-Strategy-Ultimate/ | calebsandfort | https://www.tradingview.com/u/calebsandfort/ | 516 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © calebsandfort
//@version=5
strategy("Fair Value Strategy Ultimate", overlay=false, initial_capital = 1000000, calc_on_every_tick = true)
import calebsandfort/NetLiquidityLibrary/43
fv_index_ticker = input.string("SPX", "Fair Value Index", ["SPX", "NDX", "RUT"])
mode = input.string("Long/Short", "Strategy", ["Short Only", "Long Only", "Long/Short"])
scalar = input.float(1.1, "Scalar", 0.0, 5.0, .1)
subtractor = input.int(1425, "Subtractor", step = 25)
ob_threshold = input.int(0, "OB Threshold", step = 25)
os_threshold = input.int(-175, "OS Threshold", step = 25)
inverse = input.bool(false, "Inverse")
startDate = input.int(title="Start Day", defval=20, minval=1, maxval=31)
startMonth = input.int(title="Start Month", defval=12, minval=1, maxval=12)
startYear = input.int(title="Start Year", defval=2021, minval=1800, maxval=2100)
// See if this bar's time happened on/after start date
afterStartDate = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0))
useCloseDate = input.bool(true, title="Use Close Date")
closeDay = input.int(title="Close Day", defval=12, minval=1, maxval=31)
closeMonth = input.int(title="Close Month", defval=01, minval=1, maxval=12)
closeYear = input.int(title="Close Year", defval=2023, minval=1800, maxval=2100)
// See if this bar's time happened on/after end date
afterEndDate = year == closeYear and month == closeMonth and dayofmonth == closeDay
net_liquidity = NetLiquidityLibrary.get_net_liquidity()
plotchar(net_liquidity, "net_liquidity", "", location.top)
index_fair_value = net_liquidity/1000000000/scalar - subtractor
index = request.security(fv_index_ticker, "D", close)
diff = index - index_fair_value
plot(index_fair_value > 0 ? diff : na, title = "Spread", color = color.orange, trackprice = true, linewidth = 2)
hline(0, title='Zero', color=color.gray, linestyle=hline.style_dotted, linewidth=2)
hline(ob_threshold, title='Overbought', color=color.red, linestyle=hline.style_dotted, linewidth=2)
hline(os_threshold, title='Oversold', color=color.green, linestyle=hline.style_dotted, linewidth=2)
overbought_signal = net_liquidity > 0.0 and (diff[1] < ob_threshold and diff[0] > ob_threshold)
oversold_signal = net_liquidity > 0.0 and (diff[1] > os_threshold and diff[0] < os_threshold)
barcolor(overbought_signal ? color.purple : oversold_signal ? color.blue : na)
qty = (strategy.initial_capital + strategy.netprofit + strategy.openprofit)/close
qty_adj = strategy.opentrades > 0 ? math.abs(strategy.opentrades.size(0) * 1) : qty[0]
if (mode == "Long/Short")
if (inverse)
if (overbought_signal and afterStartDate)
strategy.entry("Long", strategy.long, qty = qty[0], comment = "LE")
else if ((afterStartDate and oversold_signal) or (useCloseDate and afterEndDate))
strategy.entry("Short", strategy.short, qty = qty[0], comment = "SE")
else if (useCloseDate and afterEndDate)
strategy.close("Short", qty_percent=100, comment="close")
strategy.close("Long", qty_percent=100, comment="close")
else
if (overbought_signal and afterStartDate)
strategy.entry("Short", strategy.short, qty = qty[0], comment = "SE")
else if (afterStartDate and oversold_signal)
strategy.entry("Long", strategy.long, qty = qty[0], comment = "LE")
else if (useCloseDate and afterEndDate)
strategy.close("Short", qty_percent=100, comment="close")
strategy.close("Long", qty_percent=100, comment="close")
else if (mode == "Short Only")
if (inverse)
if (overbought_signal and afterStartDate)
strategy.entry("Long", strategy.long, qty = qty[0], comment = "LE")
if ((afterStartDate and oversold_signal) or (useCloseDate and afterEndDate))
strategy.close("Long", qty_percent=100, comment="close")
else
if (overbought_signal and afterStartDate)
strategy.entry("Short", strategy.short, qty = qty[0], comment = "SE")
if ((afterStartDate and oversold_signal) or (useCloseDate and afterEndDate))
strategy.close("Short", qty_percent=100, comment="close")
else if (mode == "Long Only")
if (inverse)
if (oversold_signal and afterStartDate)
strategy.entry("Short", strategy.short, qty = qty[0], comment = "SE")
if ((afterStartDate and overbought_signal) or (useCloseDate and afterEndDate))
strategy.close("Short", qty_percent=100, comment="close")
else
if (oversold_signal and afterStartDate)
strategy.entry("Long", strategy.long, qty = qty[0], comment = "LE")
if ((afterStartDate and overbought_signal) or (useCloseDate and afterEndDate))
strategy.close("Long", qty_percent=100, comment="close")
|
Strategy Myth-Busting #7 - MACDBB+SSL+VSF - [MYN] | https://www.tradingview.com/script/SBlz6mtG-Strategy-Myth-Busting-7-MACDBB-SSL-VSF-MYN/ | myncrypto | https://www.tradingview.com/u/myncrypto/ | 336 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © myn
//@version=5
strategy('Strategy Myth-Busting #7 - MACDBB+SSL+VSF - [MYN]', max_bars_back=5000, overlay=true, pyramiding=0, initial_capital=1000, currency='USD', default_qty_type=strategy.percent_of_equity, default_qty_value=1.0, commission_value=0.075, use_bar_magnifier = false)
/////////////////////////////////////
//* Put your strategy logic below *//
/////////////////////////////////////
//nwVqTuPe6yo
//5 min
//ak MACD BB by AlgoKid
//Disable bar colors in style
//SSL hybrid by mihkel00
// Style disable all but bar colors and ma baseline
// Change SSL1 baseline length from 60 to 30
// Change SSL1 baseline type from HMA to EMA
//volume strength Finder by Saravanan
// Get rid of bar colors on style
// Trading Rules
// SSL Hybrid.
// Buy only when price action is closed above the EMA and the line is blue color.
// Sell priace action must be closed below the EMA and the line is red color
// Volume Indicator
// Buy when Buyers strength / volume is higher than sellers volume
// Opposite
// General trading rules
// Short
// Price action must be moving below the EMA and then it has to create a pullback . The pullback is confirmed when the color changes from red to gray or from red to blue.
// If the price action is touching the EMA but the line does not change the color, the pullback is not confirmed.
// Once we have this pullback we're going to be waiting for the MACD to issue a new continuation short signal. A red circle must appear on the indicator and these circles should not be touching accross the zero level while they are being greeen
// Sellers strength above 50% at the time the MACD indiactor issues a new short signal.
// Stop Loss at EMA line 1:1.5 risk ratio.
// Functions universal to strategy
f_priorBarsSatisfied(_objectToEval, _numOfBarsToLookBack) =>
returnVal = false
for i = 0 to _numOfBarsToLookBack
if (_objectToEval[i] == true)
returnVal = true
// AK MACD BB v 1.00 by Algokid
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
//indicator('AK MACD BB v 1.00')
length = input.int(10, minval=1, title='BB Periods',group="AK MACD BB")
dev = input.float(1, minval=0.0001, title='Deviations')
//MACD
fastLength = input.int(12, minval=1)
slowLength = input.int(26, minval=1)
signalLength = input.int(9, minval=1)
fastMA = ta.ema(close, fastLength)
slowMA = ta.ema(close, slowLength)
macd = fastMA - slowMA
//BollingerBands
Std = ta.stdev(macd, length)
Upper = Std * dev + ta.sma(macd, length)
Lower = ta.sma(macd, length) - Std * dev
//Band1 = plot(Upper, color=color.new(color.gray, 0), style=plot.style_line, linewidth=2, title='Upper Band')
//Band2 = plot(Lower, color=color.new(color.gray, 0), style=plot.style_line, linewidth=2, title='lower Band')
//fill(Band1, Band2, color=color.new(color.blue, 75), title='Fill')
mc = macd >= Upper ? color.lime : color.red
// Indicator
//plot(macd, color=mc, style=plot.style_circles, linewidth=3)
zeroline = 0
//plot(zeroline, color=color.new(color.orange, 0), linewidth=2, title='Zeroline')
//buy
//barcolor(macd > Upper ? color.yellow : na)
//short
//barcolor(macd < Lower ? color.aqua : na)
//needs improvments
MACDBBNumBarsBackToLookForMACDToBelowZero = input(1, title="Number Of bars to look back to ensure MACD isn't above/below Zero Line?")
// Sell when MACD to issue a new continuation short signal. A new red circle must appear on the indicator and these circles should not be touching accross the zero level while they were previously green
MACDBBENtryShort = mc == color.red and macd < zeroline and f_priorBarsSatisfied(macd < zeroline and mc == color.lime, MACDBBNumBarsBackToLookForMACDToBelowZero)
// Buy when MACD to issue a new continuation long signal. A new green circle must appear on the indicator and these circles should not be touching accross the zero level while they were previously red
MACDBBENtryLong = mc == color.lime and macd > zeroline and f_priorBarsSatisfied(macd > zeroline and mc == color.red, MACDBBNumBarsBackToLookForMACDToBelowZero)
// SSL Hybrid by Mihkel00
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
//@version=5
//AK MACD BB
//created by Algokid , February 24,2015
//@version=5
//By Mihkel00
// This script is designed for the NNFX Method, so it is recommended for Daily charts only.
// Tried to implement a few VP NNFX Rules
// This script has a SSL / Baseline (you can choose between the SSL or MA), a secondary SSL for continiuation trades and a third SSL for exit trades.
// Alerts added for Baseline entries, SSL2 continuations, Exits.
// Baseline has a Keltner Channel setting for "in zone" Gray Candles
// Added "Candle Size > 1 ATR" Diamonds from my old script with the criteria of being within Baseline ATR range.
// Credits
// Strategy causecelebre https://www.tradingview.com/u/causecelebre/
// SSL Channel ErwinBeckers https://www.tradingview.com/u/ErwinBeckers/
// Moving Averages jiehonglim https://www.tradingview.com/u/jiehonglim/
// Moving Averages everget https://www.tradingview.com/u/everget/
// "Many Moving Averages" script Fractured https://www.tradingview.com/u/Fractured/
//indicator('SSL Hybrid', overlay=true)
show_Baseline = input(title='Show Baseline', defval=true, group="SSL Hybrid")
show_SSL1 = input(title='Show SSL1', defval=false)
show_atr = input(title='Show ATR bands', defval=true)
//ATR
atrlen = input(14, 'ATR Period')
mult = input.float(1, 'ATR Multi', step=0.1)
smoothing = input.string(title='ATR Smoothing', defval='WMA', options=['RMA', 'SMA', 'EMA', 'WMA'])
ma_function(source, atrlen) =>
if smoothing == 'RMA'
ta.rma(source, atrlen)
else
if smoothing == 'SMA'
ta.sma(source, atrlen)
else
if smoothing == 'EMA'
ta.ema(source, atrlen)
else
ta.wma(source, atrlen)
atr_slen = ma_function(ta.tr(true), atrlen)
////ATR Up/Low Bands
upper_band = atr_slen * mult + close
lower_band = close - atr_slen * mult
////BASELINE / SSL1 / SSL2 / EXIT MOVING AVERAGE VALUES
maType = input.string(title='SSL1 / Baseline Type', defval='EMA', options=['SMA', 'EMA', 'DEMA', 'TEMA', 'LSMA', 'WMA', 'MF', 'VAMA', 'TMA', 'HMA', 'JMA', 'Kijun v2', 'EDSMA', 'McGinley'])
len = input(title='SSL1 / Baseline Length', defval=30)
SSL2Type = input.string(title='SSL2 / Continuation Type', defval='JMA', options=['SMA', 'EMA', 'DEMA', 'TEMA', 'WMA', 'MF', 'VAMA', 'TMA', 'HMA', 'JMA', 'McGinley'])
len2 = input(title='SSL 2 Length', defval=5)
//
SSL3Type = input.string(title='EXIT Type', defval='HMA', options=['DEMA', 'TEMA', 'LSMA', 'VAMA', 'TMA', 'HMA', 'JMA', 'Kijun v2', 'McGinley', 'MF'])
len3 = input(title='EXIT Length', defval=15)
src = input(title='Source', defval=close)
//
tema(src, len) =>
ema1 = ta.ema(src, len)
ema2 = ta.ema(ema1, len)
ema3 = ta.ema(ema2, len)
3 * ema1 - 3 * ema2 + ema3
kidiv = input.int(defval=1, maxval=4, title='Kijun MOD Divider')
jurik_phase = input(title='* Jurik (JMA) Only - Phase', defval=3)
jurik_power = input(title='* Jurik (JMA) Only - Power', defval=1)
volatility_lookback = input(10, title='* Volatility Adjusted (VAMA) Only - Volatility lookback length')
//MF
beta = input.float(0.8, minval=0, maxval=1, step=0.1, title='Modular Filter, General Filter Only - Beta')
feedback = input(false, title='Modular Filter Only - Feedback')
z = input.float(0.5, title='Modular Filter Only - Feedback Weighting', step=0.1, minval=0, maxval=1)
//EDSMA
ssfLength = input.int(title='EDSMA - Super Smoother Filter Length', minval=1, defval=20)
ssfPoles = input.int(title='EDSMA - Super Smoother Filter Poles', defval=2, options=[2, 3])
//----
//EDSMA
get2PoleSSF(src, length) =>
PI = 2 * math.asin(1)
arg = math.sqrt(2) * PI / length
a1 = math.exp(-arg)
b1 = 2 * a1 * math.cos(arg)
c2 = b1
c3 = -math.pow(a1, 2)
c1 = 1 - c2 - c3
ssf = 0.0
ssf := c1 * src + c2 * nz(ssf[1]) + c3 * nz(ssf[2])
ssf
get3PoleSSF(src, length) =>
PI = 2 * math.asin(1)
arg = PI / length
a1 = math.exp(-arg)
b1 = 2 * a1 * math.cos(1.738 * arg)
c1 = math.pow(a1, 2)
coef2 = b1 + c1
coef3 = -(c1 + b1 * c1)
coef4 = math.pow(c1, 2)
coef1 = 1 - coef2 - coef3 - coef4
ssf = 0.0
ssf := coef1 * src + coef2 * nz(ssf[1]) + coef3 * nz(ssf[2]) + coef4 * nz(ssf[3])
ssf
ma(type, src, len) =>
float result = 0
if type == 'TMA'
result := ta.sma(ta.sma(src, math.ceil(len / 2)), math.floor(len / 2) + 1)
result
if type == 'MF'
ts = 0.
b = 0.
c = 0.
os = 0.
//----
alpha = 2 / (len + 1)
a = feedback ? z * src + (1 - z) * nz(ts[1], src) : src
//----
b := a > alpha * a + (1 - alpha) * nz(b[1], a) ? a : alpha * a + (1 - alpha) * nz(b[1], a)
c := a < alpha * a + (1 - alpha) * nz(c[1], a) ? a : alpha * a + (1 - alpha) * nz(c[1], a)
os := a == b ? 1 : a == c ? 0 : os[1]
//----
upper = beta * b + (1 - beta) * c
lower = beta * c + (1 - beta) * b
ts := os * upper + (1 - os) * lower
result := ts
result
if type == 'LSMA'
result := ta.linreg(src, len, 0)
result
if type == 'SMA' // Simple
result := ta.sma(src, len)
result
if type == 'EMA' // Exponential
result := ta.ema(src, len)
result
if type == 'DEMA' // Double Exponential
e = ta.ema(src, len)
result := 2 * e - ta.ema(e, len)
result
if type == 'TEMA' // Triple Exponential
e = ta.ema(src, len)
result := 3 * (e - ta.ema(e, len)) + ta.ema(ta.ema(e, len), len)
result
if type == 'WMA' // Weighted
result := ta.wma(src, len)
result
if type == 'VAMA' // Volatility Adjusted
/// Copyright © 2019 to present, Joris Duyck (JD)
mid = ta.ema(src, len)
dev = src - mid
vol_up = ta.highest(dev, volatility_lookback)
vol_down = ta.lowest(dev, volatility_lookback)
result := mid + math.avg(vol_up, vol_down)
result
if type == 'HMA' // Hull
result := ta.wma(2 * ta.wma(src, len / 2) - ta.wma(src, len), math.round(math.sqrt(len)))
result
if type == 'JMA' // Jurik
/// Copyright © 2018 Alex Orekhov (everget)
/// Copyright © 2017 Jurik Research and Consulting.
phaseRatio = jurik_phase < -100 ? 0.5 : jurik_phase > 100 ? 2.5 : jurik_phase / 100 + 1.5
beta = 0.45 * (len - 1) / (0.45 * (len - 1) + 2)
alpha = math.pow(beta, jurik_power)
jma = 0.0
e0 = 0.0
e0 := (1 - alpha) * src + alpha * nz(e0[1])
e1 = 0.0
e1 := (src - e0) * (1 - beta) + beta * nz(e1[1])
e2 = 0.0
e2 := (e0 + phaseRatio * e1 - nz(jma[1])) * math.pow(1 - alpha, 2) + math.pow(alpha, 2) * nz(e2[1])
jma := e2 + nz(jma[1])
result := jma
result
if type == 'Kijun v2'
kijun = math.avg(ta.lowest(len), ta.highest(len)) //, (open + close)/2)
conversionLine = math.avg(ta.lowest(len / kidiv), ta.highest(len / kidiv))
delta = (kijun + conversionLine) / 2
result := delta
result
if type == 'McGinley'
mg = 0.0
mg := na(mg[1]) ? ta.ema(src, len) : mg[1] + (src - mg[1]) / (len * math.pow(src / mg[1], 4))
result := mg
result
if type == 'EDSMA'
zeros = src - nz(src[2])
avgZeros = (zeros + zeros[1]) / 2
// Ehlers Super Smoother Filter
ssf = ssfPoles == 2 ? get2PoleSSF(avgZeros, ssfLength) : get3PoleSSF(avgZeros, ssfLength)
// Rescale filter in terms of Standard Deviations
stdev = ta.stdev(ssf, len)
scaledFilter = stdev != 0 ? ssf / stdev : 0
alpha = 5 * math.abs(scaledFilter) / len
edsma = 0.0
edsma := alpha * src + (1 - alpha) * nz(edsma[1])
result := edsma
result
result
///SSL 1 and SSL2
emaHigh = ma(maType, high, len)
emaLow = ma(maType, low, len)
maHigh = ma(SSL2Type, high, len2)
maLow = ma(SSL2Type, low, len2)
///EXIT
ExitHigh = ma(SSL3Type, high, len3)
ExitLow = ma(SSL3Type, low, len3)
///Keltner Baseline Channel
BBMC = ma(maType, close, len)
useTrueRange = input(true)
multy = input.float(0.2, step=0.05, title='Base Channel Multiplier')
Keltma = ma(maType, src, len)
range_1 = useTrueRange ? ta.tr : high - low
rangema = ta.ema(range_1, len)
upperk = Keltma + rangema * multy
lowerk = Keltma - rangema * multy
//Baseline Violation Candle
open_pos = open * 1
close_pos = close * 1
difference = math.abs(close_pos - open_pos)
atr_violation = difference > atr_slen
InRange = upper_band > BBMC and lower_band < BBMC
candlesize_violation = atr_violation and InRange
//plotshape(candlesize_violation, color=color.new(color.white, 0), size=size.tiny, style=shape.diamond, location=location.top, title='Candle Size > 1xATR')
//SSL1 VALUES
Hlv = int(na)
Hlv := close > emaHigh ? 1 : close < emaLow ? -1 : Hlv[1]
sslDown = Hlv < 0 ? emaHigh : emaLow
//SSL2 VALUES
Hlv2 = int(na)
Hlv2 := close > maHigh ? 1 : close < maLow ? -1 : Hlv2[1]
sslDown2 = Hlv2 < 0 ? maHigh : maLow
//EXIT VALUES
Hlv3 = int(na)
Hlv3 := close > ExitHigh ? 1 : close < ExitLow ? -1 : Hlv3[1]
sslExit = Hlv3 < 0 ? ExitHigh : ExitLow
base_cross_Long = ta.crossover(close, sslExit)
base_cross_Short = ta.crossover(sslExit, close)
codiff = base_cross_Long ? 1 : base_cross_Short ? -1 : na
//COLORS
show_color_bar = input(title='Color Bars', defval=true)
color_bar = close > upperk ? #00c3ff : close < lowerk ? #ff0062 : color.gray
color_ssl1 = close > sslDown ? #00c3ff : close < sslDown ? #ff0062 : na
//PLOTS
//plotarrow(codiff, colorup=color.new(#00c3ff, 20), colordown=color.new(#ff0062, 20), title='Exit Arrows', maxheight=20, offset=0)
p1 = plot(show_Baseline ? BBMC : na, color=color_bar, linewidth=4, title='MA Baseline', transp=0)
//DownPlot = plot(show_SSL1 ? sslDown : na, title='SSL1', linewidth=3, color=color_ssl1, transp=10)
barcolor(show_color_bar ? color_bar : na)
//up_channel = plot(show_Baseline ? upperk : na, color=color_bar, title='Baseline Upper Channel')
//low_channel = plot(show_Baseline ? lowerk : na, color=color_bar, title='Basiline Lower Channel')
//fill(up_channel, low_channel, color=color_bar, transp=90)
////SSL2 Continiuation from ATR
atr_crit = input.float(0.9, step=0.1, title='Continuation ATR Criteria')
upper_half = atr_slen * atr_crit + close
lower_half = close - atr_slen * atr_crit
buy_inatr = lower_half < sslDown2
sell_inatr = upper_half > sslDown2
sell_cont = close < BBMC and close < sslDown2
buy_cont = close > BBMC and close > sslDown2
sell_atr = sell_inatr and sell_cont
buy_atr = buy_inatr and buy_cont
atr_fill = buy_atr ? color.green : sell_atr ? color.purple : color.white
//LongPlot = plot(sslDown2, title='SSL2', linewidth=2, color=atr_fill, style=plot.style_circles, transp=0)
//u = plot(show_atr ? upper_band : na, '+ATR', color=color.new(color.white, 80))
//l = plot(show_atr ? lower_band : na, '-ATR', color=color.new(color.white, 80))
//ALERTS
alertcondition(ta.crossover(close, sslDown), title='SSL Cross Alert', message='SSL1 has crossed.')
alertcondition(ta.crossover(close, sslDown2), title='SSL2 Cross Alert', message='SSL2 has crossed.')
alertcondition(sell_atr, title='Sell Continuation', message='Sell Continuation.')
alertcondition(buy_atr, title='Buy Continuation', message='Buy Continuation.')
alertcondition(ta.crossover(close, sslExit), title='Exit Sell', message='Exit Sell Alert.')
alertcondition(ta.crossover(sslExit, close), title='Exit Buy', message='Exit Buy Alert.')
alertcondition(ta.crossover(close, upperk), title='Baseline Buy Entry', message='Base Buy Alert.')
alertcondition(ta.crossover(lowerk, close), title='Baseline Sell Entry', message='Base Sell Alert.')
// Buy only when price action is closed above the EMA and the line is blue color.
SSLHybridEntryLong1 = src > BBMC and color_bar == #00c3ff
// Sell only when action must be closed below the EMA and the line is red color
SSLHybridEntryShort1 = src < BBMC and color_bar == #ff0062
sslHybridNumBarsBackToLookForPullBack = input(4, title="Number Of bars back to look for SSL pullback")
// Buy when Price action must be moving above the EMA and then it has to create a pullback . The pullback is confirmed when the color changes from blue to gray or from blue to red.
SSLHybridEntryLong2 = color_bar == #00c3ff and (f_priorBarsSatisfied(color_bar == #ff0062,sslHybridNumBarsBackToLookForPullBack) or f_priorBarsSatisfied(color_bar == color.gray, sslHybridNumBarsBackToLookForPullBack))
// Sell when Price action must be moving below the EMA and then it has to create a pullback . The pullback is confirmed when the color changes from red to gray or from red to blue.
SSLHybridEntryShort2 = color_bar == #ff0062 and (f_priorBarsSatisfied(color_bar == #00c3ff,sslHybridNumBarsBackToLookForPullBack) or f_priorBarsSatisfied(color_bar == color.gray, sslHybridNumBarsBackToLookForPullBack))
SSLHybridEntryLong = SSLHybridEntryLong1 and SSLHybridEntryLong2
SSLHybridEntryShort = SSLHybridEntryShort1 and SSLHybridEntryShort2
// Price action must be moving below the EMA and then it has to create a pullback . The pullback is confirmed when the color changes from red to gray or from red to blue.
// If the price action is touching the EMA but the line does not change the color, the pullback is not confirmed.
// Volume Strength Finder by Saravanan_Ragavan
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Saravanan_Ragavan
//@version=5
//indicator('Volume Strength Finder', 'VSF', overlay=true)
T1 = time(timeframe.period, '0915-0916:23456')
T2 = time(timeframe.period, '0915-1530:23456')
Y = bar_index
Z1 = ta.valuewhen(T1, bar_index, 0)
L = Y - Z1 + 1
SSPV = 0.00
SSNV = 0.00
pdw = 0.00
ndw = 0.00
total_w = 0.00
for i = 1 to L - 1 by 1
total_w := high[i] - low[i]
positive = close[i] - low[i]
negative = high[i] - close[i]
pdw := positive / total_w * 100
ndw := negative / total_w * 100
SSPV := volume[i] * pdw / 100 + SSPV
SSNV := volume[i] * ndw / 100 + SSNV
SSNV
total_v = SSPV + SSNV
Pos = SSPV / total_v * 100
Neg = SSNV / total_v * 100
bgc = SSPV > SSNV ? color.green : SSPV < SSNV ? color.red : color.white
//barcolor(bgc)
var table sDisplay = table.new(position.top_right, 1, 5, bgcolor=color.aqua, frame_width=2, frame_color=color.black)
if barstate.islast
table.cell(sDisplay, 0, 0, 'Today\'s Volume : ' + str.tostring(total_v), text_color=color.white, text_size=size.large, bgcolor=color.aqua)
table.cell(sDisplay, 0, 1, 'Buyers Volume: ' + str.tostring(math.round(SSPV)), text_color=color.white, text_size=size.large, bgcolor=color.green)
table.cell(sDisplay, 0, 2, 'Sellers Volume: ' + str.tostring(math.round(SSNV)), text_color=color.white, text_size=size.large, bgcolor=color.red)
table.cell(sDisplay, 0, 3, 'Buyers Strength: ' + str.tostring(math.round(Pos)) + '%', text_color=color.white, text_size=size.large, bgcolor=color.green)
table.cell(sDisplay, 0, 4, 'Sellers Strength: ' + str.tostring(math.round(Neg)) + '%', text_color=color.white, text_size=size.large, bgcolor=color.red)
// Sellers strength above 50% at the time the MACD indiactor issues a new short signal.
VSFShortEntry = math.round(Neg) > 50
// Buyers strength above 50% at the time the MACD indiactor issues a new long signal.
VSFLongEntry = math.round(Pos) > 50
//////////////////////////////////////
//* Put your strategy rules below *//
/////////////////////////////////////
longCondition = SSLHybridEntryLong and VSFLongEntry and MACDBBENtryLong
shortCondition =SSLHybridEntryShort and VSFShortEntry and MACDBBENtryShort
//define as 0 if do not want to use
closeLongCondition = 0
closeShortCondition = 0
// ADX
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
adxEnabled = input.bool(defval = false , title = "Average Directional Index (ADX)", tooltip = "", group ="ADX" )
adxlen = input(14, title="ADX Smoothing", group="ADX")
adxdilen = input(14, title="DI Length", group="ADX")
adxabove = input(25, title="ADX Threshold", group="ADX")
adxdirmov(len) =>
adxup = ta.change(high)
adxdown = -ta.change(low)
adxplusDM = na(adxup) ? na : (adxup > adxdown and adxup > 0 ? adxup : 0)
adxminusDM = na(adxdown) ? na : (adxdown > adxup and adxdown > 0 ? adxdown : 0)
adxtruerange = ta.rma(ta.tr, len)
adxplus = fixnan(100 * ta.rma(adxplusDM, len) / adxtruerange)
adxminus = fixnan(100 * ta.rma(adxminusDM, len) / adxtruerange)
[adxplus, adxminus]
adx(adxdilen, adxlen) =>
[adxplus, adxminus] = adxdirmov(adxdilen)
adxsum = adxplus + adxminus
adx = 100 * ta.rma(math.abs(adxplus - adxminus) / (adxsum == 0 ? 1 : adxsum), adxlen)
adxsig = adxEnabled ? adx(adxdilen, adxlen) : na
isADXEnabledAndAboveThreshold = adxEnabled ? (adxsig > adxabove) : true
//Backtesting Time Period (Input.time not working as expected as of 03/30/2021. Giving odd start/end dates
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
useStartPeriodTime = input.bool(true, 'Start', group='Date Range', inline='Start Period')
startPeriodTime = input.time(timestamp('1 Jan 2019'), '', group='Date Range', inline='Start Period')
useEndPeriodTime = input.bool(true, 'End', group='Date Range', inline='End Period')
endPeriodTime = input.time(timestamp('31 Dec 2030'), '', group='Date Range', inline='End Period')
start = useStartPeriodTime ? startPeriodTime >= time : false
end = useEndPeriodTime ? endPeriodTime <= time : false
calcPeriod = not start and not end
// Trade Direction
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tradeDirection = input.string('Long and Short', title='Trade Direction', options=['Long and Short', 'Long Only', 'Short Only'], group='Trade Direction')
// Percent as Points
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
per(pcnt) =>
strategy.position_size != 0 ? math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na)
// Take profit 1
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp1 = input.float(title='Take Profit 1 - Target %', defval=1, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 1')
q1 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 1')
// Take profit 2
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp2 = input.float(title='Take Profit 2 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 2')
q2 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 2')
// Take profit 3
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp3 = input.float(title='Take Profit 3 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 3')
q3 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 3')
// Take profit 4
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp4 = input.float(title='Take Profit 4 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit')
/// Stop Loss
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
stoplossPercent = input.float(title='Stop Loss (%)', defval=2, minval=0.01, group='Stop Loss') * 0.01
slLongClose = close < strategy.position_avg_price * (1 - stoplossPercent)
slShortClose = close > strategy.position_avg_price * (1 + stoplossPercent)
/// Leverage
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
leverage = input.float(1, 'Leverage', step=.5, group='Leverage')
contracts = math.min(math.max(.000001, strategy.equity / close * leverage), 1000000000)
/// Trade State Management
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
isInLongPosition = strategy.position_size > 0
isInShortPosition = strategy.position_size < 0
/// ProfitView Alert Syntax String Generation
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
alertSyntaxPrefix = input.string(defval='CRYPTANEX_99FTX_Strategy-Name-Here', title='Alert Syntax Prefix', group='ProfitView Alert Syntax')
alertSyntaxBase = alertSyntaxPrefix + '\n#' + str.tostring(open) + ',' + str.tostring(high) + ',' + str.tostring(low) + ',' + str.tostring(close) + ',' + str.tostring(volume) + ','
/// Trade Execution
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
longConditionCalc = (longCondition and isADXEnabledAndAboveThreshold)
shortConditionCalc = (shortCondition and isADXEnabledAndAboveThreshold)
if calcPeriod
if longConditionCalc and tradeDirection != 'Short Only' and isInLongPosition == false
strategy.entry('Long', strategy.long, qty=contracts)
alert(message=alertSyntaxBase + 'side:long', freq=alert.freq_once_per_bar_close)
if shortConditionCalc and tradeDirection != 'Long Only' and isInShortPosition == false
strategy.entry('Short', strategy.short, qty=contracts)
alert(message=alertSyntaxBase + 'side:short', freq=alert.freq_once_per_bar_close)
//Inspired from Multiple %% profit exits example by adolgo https://www.tradingview.com/script/kHhCik9f-Multiple-profit-exits-example/
strategy.exit('TP1', qty_percent=q1, profit=per(tp1))
strategy.exit('TP2', qty_percent=q2, profit=per(tp2))
strategy.exit('TP3', qty_percent=q3, profit=per(tp3))
strategy.exit('TP4', profit=per(tp4))
strategy.close('Long', qty_percent=100, comment='SL Long', when=slLongClose)
strategy.close('Short', qty_percent=100, comment='SL Short', when=slShortClose)
strategy.close_all(when=closeLongCondition or closeShortCondition, comment='Close Postion')
/// Dashboard
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Inspired by https://www.tradingview.com/script/uWqKX6A2/ - Thanks VertMT
showDashboard = input.bool(group="Dashboard", title="Show Dashboard", defval=true)
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
_cellText = _title + "\n" + _value
table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=size.auto)
// Draw dashboard table
if showDashboard
var bgcolor = color.new(color.black,0)
// Keep track of Wins/Losses streaks
newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
varip int winRow = 0
varip int lossRow = 0
varip int maxWinRow = 0
varip int maxLossRow = 0
if newWin
lossRow := 0
winRow := winRow + 1
if winRow > maxWinRow
maxWinRow := winRow
if newLoss
winRow := 0
lossRow := lossRow + 1
if lossRow > maxLossRow
maxLossRow := lossRow
// Prepare stats table
var table dashTable = table.new(position.bottom_right, 1, 15, border_width=1)
if barstate.islastconfirmedhistory
// Update table
dollarReturn = strategy.netprofit
f_fillCell(dashTable, 0, 0, "Start:", str.format("{0,date,long}", strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.closedtrades.entry_time(0))
f_fillCell(dashTable, 0, 1, "End:", str.format("{0,date,long}", strategy.opentrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.opentrades.entry_time(0))
_profit = (strategy.netprofit / strategy.initial_capital) * 100
f_fillCell(dashTable, 0, 2, "Net Profit:", str.tostring(_profit, '##.##') + "%", _profit > 0 ? color.green : color.red, color.white)
_numOfDaysInStrategy = (strategy.opentrades.entry_time(0) - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24)
f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit / _numOfDaysInStrategy, '#########################.#####')+"%", _profit > 0 ? color.green : color.red, color.white)
_winRate = ( strategy.wintrades / strategy.closedtrades ) * 100
f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? color.red : _winRate < 75 ? #999900 : color.green, color.white)
f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? color.green : color.red, color.white)
f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white)
f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white)
f_fillCell(dashTable, 0, 9, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white) |
rt maax EMA cross strategy | https://www.tradingview.com/script/QgiJQoBE-rt-maax-EMA-cross-strategy/ | rtmaax | https://www.tradingview.com/u/rtmaax/ | 53 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © rt-maax
//@version=5
strategy(title = "rt maax EMA cross strategy", shorttitle = "rt maax ema ", overlay = true, precision = 8, max_bars_back = 200, pyramiding = 0, initial_capital = 100000,
currency = currency.USD, default_qty_type = strategy.cash, default_qty_value = 100000, commission_type = "percent", commission_value = 0.27)
fastema = ta.ema (close , 50)
fema=ta.ema(close,20)
slowema= ta.ema(close,200)
price = close
// === INPUT BACKTEST RANGE ===
fromMonth = input.int(defval = 1, title = "From Month", minval = 1, maxval = 12)
fromDay = input.int(defval = 1, title = "From Day", minval = 1, maxval = 31)
fromYear = input.int(defval = 2021, title = "From Year", minval = 1970)
thruMonth = input.int(defval = 10, title = "Thru Month", minval = 1, maxval = 12)
thruDay = input.int(defval = 25, title = "Thru Day", minval = 1, maxval = 31)
thruYear = input.int(defval = 2112, title = "Thru Year", minval = 1970)
// === INPUT SHOW PLOT ===
showDate = input(defval = true, title = "Show Date Range")
// === FUNCTION EXAMPLE ===
longCondition1= ta.crossover (fema , fastema)
longcondition2= fema> slowema
longcondition3=fastema>slowema
if (longCondition1 and longcondition2 and longcondition3 )
stoploss=low*0.97
takeprofit=high*1.12
strategy.entry("Long Entry", strategy.long)
strategy.exit ("exit","long",stop=stoploss,limit=takeprofit)
shortCondition1 = ta.crossunder (fema , fastema )
shortcondition2= fastema< slowema
shortcondition3= fema< slowema
if (shortCondition1 and shortcondition2 and shortcondition3 )
stoploss=low*0.97
takeprofit=high*1.5
strategy.entry("Short Entry", strategy.short)
strategy.exit("exit","short",stop=stoploss,limit=takeprofit)
|
SPX Fair Value Strategy Ultimate | https://www.tradingview.com/script/Wxp4PJkS-SPX-Fair-Value-Strategy-Ultimate/ | calebsandfort | https://www.tradingview.com/u/calebsandfort/ | 354 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © calebsandfort
//@version=5
strategy("SPX Fair Value Strategy Ultimate", overlay=false, initial_capital = 1000000, calc_on_every_tick = true)
import calebsandfort/NetLiquidityLibrary/16
mode = input.string("Short Only", "Strategy", ["Short Only", "Long Only", "Long/Short"])
inverse = input.bool(false, "Inverse")
startDate = input.int(title="Start Day", defval=31, minval=1, maxval=31)
startMonth = input.int(title="Start Month", defval=12, minval=1, maxval=12)
startYear = input.int(title="Start Year", defval=2021, minval=1800, maxval=2100)
// See if this bar's time happened on/after start date
afterStartDate = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0))
useCloseDate = input.bool(true, title="Use Close Date")
closeDay = input.int(title="Close Day", defval=21, minval=1, maxval=31)
closeMonth = input.int(title="Close Month", defval=10, minval=1, maxval=12)
closeYear = input.int(title="Close Year", defval=2022, minval=1800, maxval=2100)
// See if this bar's time happened on/after end date
afterEndDate = year == closeYear and month == closeMonth and dayofmonth == closeDay
net_liquidity = NetLiquidityLibrary.get_net_liquidity()
// plotchar(year, "year", "", location.top)
// plotchar(month, "month", "", location.top)
// plotchar(dayofmonth, "dayofmonth", "", location.top)
// plotchar(net_liquidity, "net_liquidity", "", location.top)
spx_fair_value = net_liquidity/1000000000/1.1 -1625
spx = request.security("SP:SPX", "D", close)
diff = spx - spx_fair_value
plot(spx_fair_value > 0 ? diff : na, title = "Spread", color = color.orange, trackprice = true, linewidth = 2)
hline(350, title='Overbought', color=color.red, linestyle=hline.style_dotted, linewidth=2)
hline(0, title='Zero', color=color.gray, linestyle=hline.style_dotted, linewidth=2)
hline(-150, title='Oversold', color=color.green, linestyle=hline.style_dotted, linewidth=2)
overbought_signal = net_liquidity > 0.0 and (diff[1] < 350 and diff[0] > 350)
oversold_signal = net_liquidity > 0.0 and (diff[1] > -150 and diff[0] < -150)
barcolor(overbought_signal ? color.purple : oversold_signal ? color.blue : na)
qty = (strategy.initial_capital + strategy.netprofit + strategy.openprofit)/close
qty_adj = strategy.opentrades > 0 ? math.abs(strategy.opentrades.size(0) * 1) : qty[0]
if (mode == "Long/Short")
if (inverse)
if (overbought_signal and afterStartDate)
strategy.entry("Long", strategy.long, qty = qty[0], comment = "LE")
else if ((afterStartDate and oversold_signal) or (useCloseDate and afterEndDate))
strategy.entry("Short", strategy.short, qty = qty[0], comment = "SE")
else if (afterEndDate)
strategy.close("Short", qty_percent=100, comment="close")
strategy.close("Long", qty_percent=100, comment="close")
else
if (overbought_signal and afterStartDate)
strategy.entry("Short", strategy.short, qty = qty[0], comment = "SE")
else if (afterStartDate and oversold_signal)
strategy.entry("Long", strategy.long, qty = qty[0], comment = "LE")
else if (afterEndDate)
strategy.close("Short", qty_percent=100, comment="close")
strategy.close("Long", qty_percent=100, comment="close")
else if (mode == "Short Only")
if (inverse)
if (overbought_signal and afterStartDate)
strategy.entry("Long", strategy.long, qty = qty[0], comment = "LE")
if ((afterStartDate and oversold_signal) or (useCloseDate and afterEndDate))
strategy.close("Long", qty_percent=100, comment="close")
else
if (overbought_signal and afterStartDate)
strategy.entry("Short", strategy.short, qty = qty[0], comment = "SE")
if ((afterStartDate and oversold_signal) or (useCloseDate and afterEndDate))
strategy.close("Short", qty_percent=100, comment="close")
else if (mode == "Long Only")
if (inverse)
if (oversold_signal and afterStartDate)
strategy.entry("Short", strategy.short, qty = qty[0], comment = "SE")
if ((afterStartDate and overbought_signal) or (useCloseDate and afterEndDate))
strategy.close("Short", qty_percent=100, comment="close")
else
if (oversold_signal and afterStartDate)
strategy.entry("Long", strategy.long, qty = qty[0], comment = "LE")
if ((afterStartDate and overbought_signal) or (useCloseDate and afterEndDate))
strategy.close("Long", qty_percent=100, comment="close")
|
50 Pips A Day Strategy - Kaspricci | https://www.tradingview.com/script/Ab9UrFp5/ | Kaspricci | https://www.tradingview.com/u/Kaspricci/ | 161 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Kaspricci
//@version=5
strategy("50 Pips A Day Strategy - Kaspricci", overlay=true, initial_capital = 1000, currency = currency.USD, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, margin_long = 0, margin_short = 0, calc_on_every_tick = true, calc_on_order_fills = false, slippage = 0, close_entries_rule = "ANY")
headlineEntry = "Entry Seettings"
tooltipTF = "Combined timeframe of London and New York Stock Exchange opening hours from 7:00 - 15:30 GMT and 13:30 - 20:00 GMT"
openingSession = input.session(defval="0700-0800:23456", title="Opening Time", group=headlineEntry, tooltip="GMT timezone")
openingTime = time(timeframe.period, openingSession, "GMT")
tradingSession = input.session(defval="0800-2000:23456", title="Trading Time", group=headlineEntry, tooltip=tooltipTF)
tradingTime = time(timeframe.period, tradingSession, "GMT")
buyStopSource = input.source( defval = high, title = "Source for Buy Stop order", inline = "B", group=headlineEntry)
buyStopGap = input.float( defval = 2.0, minval = 0, step = 0.1, title = " + Pips:", inline = "B", group=headlineEntry)
sellStopSource = input.source( defval = low, title = "Source for Sell Stop order", inline = "S", group=headlineEntry)
sellStopGap = input.float( defval = 2.0, minval = 0, step = 0.1, title = " - Pips:", inline = "S", group=headlineEntry)
closePending = input.bool( defval = true, group = headlineEntry, title = "Cancel pending order when new trade entered?", tooltip = "This will cancel the reamaining order, once the first trade has been entered.")
headlineTrade = "Trade Seettings"
stopLossType = input.string(defval = "FIX", title = "Stop Loss Type", options = ["ATR", "FIX"], group = headlineTrade)
atrLength = input.int(defval = 14, title = " ATR: Length ", inline = "ATR", group = headlineTrade, minval = 1)
atrFactor = input.float(defval = 2.0, title = "Factor ", inline = "ATR", group = headlineTrade, tooltip = "multiplier for ATR value", minval = 0, step = 0.05)
takeProfitRatio = input.float(defval = 2.0, title = " TP Ration", group = headlineTrade, tooltip = "Multiplier for Take Profit calculation", minval = 0, step = 0.05)
fixStopLoss = input.float(defval = 15.0, title = " FIX: Stop Loss ", inline = "FIX", group = headlineTrade, minval = 0, step = 0.5) * 10 // need this in ticks
fixTakeProfit = input.float(defval = 50.0, title = "Take Profit", inline = "FIX", group = headlineTrade, tooltip = "in pips", minval = 0, step = 0.5) * 10 // need this in ticks
useRiskMagmt = input.bool( title = "", defval = false, group = headlineTrade, inline = "RM")
riskPercent = input.float( title = "Risk in % ", defval = 1.0, minval = 0.0, step = 0.5, group = headlineTrade, inline = "RM", tooltip = "This will overwrite quantity from startegy settings and calculate the trade size based on stop loss and risk percent") / 100
rsikCapital = input.string(defval = "Balance", group = headlineTrade, inline = "RM", title = "", options = ["Balance", "Initial"], tooltip = "This will overwrite quantity from startegy settings and calculate the trade size based on stop loss and risk percent")
applyLotSizing = input.bool(defval = true, title = "Apply Lot sizing", tooltip = "When enabled, the quantity will be rounded to the minimum lot size of 1000 (0.01 lots)")
stopLoss = switch stopLossType
"ATR" => math.round(ta.atr(atrLength) * atrFactor / syminfo.mintick, 0)
"FIX" => fixStopLoss
takeProfit = switch stopLossType
"ATR" => math.round(stopLoss * takeProfitRatio, 0)
"FIX" => fixTakeProfit
// calculate quantity
baseCapital = switch rsikCapital
"Balance" => strategy.initial_capital + strategy.netprofit
"Initial" => strategy.initial_capital
riskAmount = strategy.convert_to_symbol(baseCapital * riskPercent)
tickValue = syminfo.pointvalue * syminfo.mintick
riskBasedQty = riskAmount / stopLoss / tickValue
riskBasedQty := applyLotSizing ? math.round(riskBasedQty / 100000, 2) * 100000 : riskBasedQty
quantity = useRiskMagmt ? riskBasedQty : na // if NaN the default from strategy settings will be used
inTradingTime = not na(tradingTime)
inOpeningTime = not na(openingTime)
var float buyStopPrice = na
var float sellStopPrice = na
plot(inTradingTime ? buyStopPrice : na, title = "Buy Stop Price", color = color.green, style = plot.style_linebr)
plot(inTradingTime ? sellStopPrice : na, title = "Sell Stop Price", color = color.red, style = plot.style_linebr)
///////////////////////////////////////////////////////////////////////////////
// api bot values
longSL = buyStopPrice - stopLoss * syminfo.mintick
longTP1 = buyStopPrice + takeProfit * syminfo.mintick * 0.5 // 50% of total take profit
longTP2 = buyStopPrice + takeProfit * syminfo.mintick // same as full
longTPFull = buyStopPrice + takeProfit * syminfo.mintick
shortSL = sellStopPrice + stopLoss * syminfo.mintick
shortTP1 = sellStopPrice - takeProfit * syminfo.mintick * 0.5 // 50% of total take profit
shortTP2 = sellStopPrice - takeProfit * syminfo.mintick
shortTPFull = sellStopPrice - takeProfit * syminfo.mintick
takeAmount1 = riskPercent / 2
takeAmount2 = riskPercent
takeAmountFull = riskPercent
headlineAlerts = "Alert Settings"
i_apiEnterLong = input.text_area('Enter Long - 3commas,alerteron etc', 'API Entry - Long', group = headlineAlerts)
i_apiExitLong = input.text_area('Exit Long - 3commas,alerteron etc', 'API Exit - Long', group = headlineAlerts)
i_apiEnterShort = input.text_area('Enter Short - 3commas,alerteron etc', 'API Entry - Short', group = headlineAlerts)
i_apiExitShort = input.text_area('Exit Short - 3commas,alerteron etc', 'API Exit - Short', group = headlineAlerts)
// #nl# => New line
// #side# => Buy or Sell (Long or Short)
// #symbol# => The ticker e.g. BTCUSDT
f_replaceKeys (_str) =>
_value = _str
_value := str.replace_all(_value, "#nl#", "\n")
// _value := str.replace_all(_value, "#side#", "\n") // does not make sense to me...
_value := str.replace_all(_value, "#symbol#", syminfo.ticker)
// #LongSL# => Long Stop loss
// #LongTP1# => Long Take Profit 1
// #LongTP2# => Long Take Profit 2
// #LongTPFULL# => Long Take Profit in FULL
// #TakeAmount1# => Percent to remove from trade on hitting TP1
// #TakeAmount2# => Percent to remove from trade on hitting TP2
// #TakeAmountFULL# => Percent to remove from trade on hitting TP3 (should be 100%)
f_replaceLongTokens (_str, _sl, _tp1, _tp2, _tpFull, _ta1, _ta2, _taFull) =>
_value = _str
_value := str.replace_all(_value, "#LongSL#", str.tostring(_sl))
_value := str.replace_all(_value, "#LongTP1#", str.tostring(_tp1))
_value := str.replace_all(_value, "#LongTP2#", str.tostring(_tp2))
_value := str.replace_all(_value, "#LongTPFULL#", str.tostring(_tpFull))
_value := str.replace_all(_value, "#TakeAmount1#", str.tostring(_ta1))
_value := str.replace_all(_value, "#TakeAmount2#", str.tostring(_ta2))
_value := str.replace_all(_value, "#TakeAmountFULL#", str.tostring(_taFull))
// #ShortSL# => Short Stop loss
// #ShortTP1# => Short Take Profit 1
// #ShortTP2# => Short Take Profit 2
// #ShortTPFULL# => Short Take Profit in FULL
// #TakeAmount1# => Percent to remove from trade on hitting TP1
// #TakeAmount2# => Percent to remove from trade on hitting TP2
// #TakeAmountFULL# => Percent to remove from trade on hitting TP3 (should be 100%)
f_replaceShortTokens (_str, _sl, _tp1, _tp2, _tpFull, _ta1, _ta2, _taFull) =>
_value = _str
_value := str.replace_all(_value, "#ShortSL#", str.tostring(_sl))
_value := str.replace_all(_value, "#ShortTP1#", str.tostring(_tp1))
_value := str.replace_all(_value, "#ShortTP2#", str.tostring(_tp2))
_value := str.replace_all(_value, "#ShortTPFULL#", str.tostring(_tpFull))
_value := str.replace_all(_value, "#TakeAmount1#", str.tostring(_ta1))
_value := str.replace_all(_value, "#TakeAmount2#", str.tostring(_ta2))
_value := str.replace_all(_value, "#TakeAmountFULL#", str.tostring(_taFull))
i_apiEnterLong := f_replaceKeys (i_apiEnterLong)
i_apiEnterLong := f_replaceLongTokens (i_apiEnterLong, longSL, longTP1, longTP2, longTPFull, takeAmount1, takeAmount2, takeAmountFull)
i_apiExitLong := f_replaceKeys (i_apiExitLong)
i_apiExitLong := f_replaceLongTokens (i_apiExitLong, longSL, longTP1, longTP2, longTPFull, takeAmount1, takeAmount2, takeAmountFull)
i_apiEnterShort := f_replaceKeys (i_apiEnterShort)
i_apiEnterShort := f_replaceShortTokens (i_apiEnterShort, shortSL, shortTP1, shortTP2, shortTPFull, takeAmount1, takeAmount2, takeAmountFull)
i_apiExitShort := f_replaceKeys (i_apiExitShort)
i_apiExitShort := f_replaceShortTokens (i_apiExitShort, shortSL, shortTP1, shortTP2, shortTPFull, takeAmount1, takeAmount2, takeAmountFull)
// ----- handline trade entries and exits --------------------------------------------------------------------------------------------------------------------------
var float openingHigh = na
var float openingLow = na
// determine high and low druing opening session
if barstate.isconfirmed and inOpeningTime
openingHigh := math.max(buyStopSource, nz(openingHigh[1], buyStopSource))
openingLow := math.min(sellStopSource, nz(openingLow[1], sellStopSource))
buyStopPrice := openingHigh + buyStopGap * 10 * syminfo.mintick
sellStopPrice := openingLow - sellStopGap * 10 * syminfo.mintick
// as soon as the trading session starts calculate stop prices based on high / low of first closing candle, create pending orders
if barstate.isconfirmed and inTradingTime and not inTradingTime[1]
tradeID = str.tostring(strategy.closedtrades + strategy.opentrades + 1)
strategy.entry(tradeID + "L", strategy.long, qty = quantity, stop = buyStopPrice, comment = "Long: " + tradeID, alert_message = i_apiEnterLong)
strategy.exit(tradeID + "SL", tradeID + "L", profit = takeProfit, loss = stopLoss, comment_loss = "SL", comment_profit = "TP", alert_message = i_apiExitLong)
strategy.entry(tradeID + "S", strategy.short, qty = quantity, stop = sellStopPrice, comment = "Short: " + tradeID, alert_message = i_apiEnterShort)
strategy.exit(tradeID + "SL", tradeID + "S", profit = takeProfit, loss = stopLoss, comment_loss = "SL", comment_profit = "TP", alert_message = i_apiExitShort)
// once the session is gone, reset prices and cancel all remaining pending orders, close open orders
if barstate.isconfirmed and not inTradingTime and inTradingTime[1]
buyStopPrice := na
sellStopPrice := na
openingHigh := na
openingLow := na
strategy.cancel_all()
currentTradeID = str.tostring(strategy.closedtrades + strategy.opentrades)
strategy.close(currentTradeID + "L", immediately = true, comment = "L: session end", alert_message = i_apiExitLong)
strategy.close(currentTradeID + "S", immediately = true, comment = "S: session end", alert_message = i_apiExitShort)
// as soon as the first pending order has been entered the remaing pending order shall be cancelled
if strategy.opentrades > 0 and closePending
currentTradeID = str.tostring(strategy.closedtrades + strategy.opentrades)
strategy.cancel(currentTradeID + "L")
strategy.cancel(currentTradeID + "S")
|
Simple RSI and SMA Long and Short (by Coinrule) | https://www.tradingview.com/script/Clpg5ju2-Simple-RSI-and-SMA-Long-and-Short-by-Coinrule/ | Coinrule | https://www.tradingview.com/u/Coinrule/ | 519 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Coinrule
//@version=5
strategy('RSI and SMA',
overlay=true,
initial_capital=1000,
process_orders_on_close=true,
default_qty_type=strategy.percent_of_equity,
default_qty_value=30,
commission_type=strategy.commission.percent,
commission_value=0.1)
showDate = input(defval=true, title='Show Date Range')
timePeriod = time >= timestamp(syminfo.timezone, 2022, 1, 1, 0, 0)
notInTrade = strategy.position_size <= 0
//==================================Buy Conditions============================================
//RSI
length = input(14)
rsi = ta.rsi(close, length)
//SMA
fastEMA = ta.sma(close, 100)
slowEMA = ta.sma(close, 150)
plot(fastEMA, color = color.green)
plot(slowEMA, color = color.blue)
bullish = ta.crossover(fastEMA, slowEMA) and rsi > 50
bearish = ta.crossover(slowEMA, fastEMA) and rsi < 50
strategy.entry("Long", strategy.long, when=bullish and timePeriod)
strategy.close("Exit", when=bearish)
strategy.entry("Short", strategy.short, when=bearish and timePeriod)
strategy.close("Exit", when=bullish)
|
The Only EURUSD Trading Strategy You Need - Kaspricci | https://www.tradingview.com/script/CjTnMUWB/ | Kaspricci | https://www.tradingview.com/u/Kaspricci/ | 80 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Kaspricci
//@version=5
strategy(
title = "Trade Beta - The Only EURUSD Trading Strategy You Need - Kaspricci",
shorttitle = "The Only EURUSD Trading Strategy You Need - Kaspricci",
overlay=true,
initial_capital = 1000,
currency = currency.USD,
default_qty_type = strategy.percent_of_equity,
default_qty_value = 100,
calc_on_every_tick = true,
close_entries_rule = "ANY")
headlineEntry = "Entry Seettings"
tooltipTF = "New York Stock Exchange opening hours from 13:30 - 20:00 GMT"
session = input.session(defval="1330-2000:23456", title="Trading Time", group=headlineEntry, tooltip=tooltipTF)
sessionTime = time(timeframe.period, session, "GMT")
// swing high
shSource = input.source(defval = high, title = "Swing High Source ", group = headlineEntry, inline = "SH")
shBars = input.int( defval = 5, title = "Bars ", group = headlineEntry, inline = "SH")
// swing low
slSource = input.source(defval = low, title = "Swing Low Source ", group = headlineEntry, inline = "SL")
slBars = input.int( defval = 5, title = "Bars ", group = headlineEntry, inline = "SL")
headlineTrade = "Trade Seettings"
stopLossType = input.string(defval = "ATR", title = "Stop Loss Type", options = ["ATR", "FIX"], group = headlineTrade)
atrLength = input.int(defval = 14, title = " ATR: Length ", inline = "ATR", group = headlineTrade, minval = 1)
atrFactor = input.float(defval = 2.0, title = "Factor ", inline = "ATR", group = headlineTrade, tooltip = "multiplier for ATR value", minval = 0, step = 0.05)
takeProfitRatio = input.float(defval = 2.0, title = " TP Ration", group = headlineTrade, tooltip = "Multiplier for Take Profit calculation", minval = 0, step = 0.05)
fixStopLoss = input.float(defval = 10.0, title = " FIX: Stop Loss ", inline = "FIX", group = headlineTrade, minval = 0, step = 0.5) * 10 // need this in ticks
fixTakeProfit = input.float(defval = 20.0, title = "Take Profit", inline = "FIX", group = headlineTrade, tooltip = "in pips", minval = 0, step = 0.5) * 10 // need this in ticks
useRiskMagmt = input.bool( title = "", defval = false, group = headlineTrade, inline = "RM")
riskPercent = input.float( title = "Risk in % ", defval = 1.0, minval = 0.0, step = 0.5, group = headlineTrade, inline = "RM", tooltip = "This will overwrite quantity from startegy settings and calculate the trade size based on stop loss and risk percent") / 100
stopLoss = switch stopLossType
"ATR" => math.round(ta.atr(atrLength) * atrFactor / syminfo.mintick, 0)
"FIX" => fixStopLoss
takeProfit = switch stopLossType
"ATR" => math.round(stopLoss * takeProfitRatio, 0)
"FIX" => fixTakeProfit
inSession = not na(sessionTime)
var float buyStopPrice = na
var float sellStopPrice = na
plot(inSession ? buyStopPrice : na, title = "Buy Stop Price", color = color.green, style = plot.style_linebr)
plot(inSession ? sellStopPrice : na, title = "Sell Stop Price", color = color.red, style = plot.style_linebr)
var float swingHigh = na
var float swingLow = na
swingHigh := nz(ta.pivothigh(shSource, shBars, shBars), swingHigh[1])
swingLow := nz(ta.pivotlow( slSource, slBars, slBars), swingLow[1])
///////////////////////////////////////////////////////////////////////////////
// api bot values
longSL = buyStopPrice - stopLoss * syminfo.mintick
longTP1 = buyStopPrice + takeProfit * syminfo.mintick * 0.5 // 50% of total take profit
longTP2 = buyStopPrice + takeProfit * syminfo.mintick // same as full
longTPFull = buyStopPrice + takeProfit * syminfo.mintick
shortSL = sellStopPrice + stopLoss * syminfo.mintick
shortTP1 = sellStopPrice - takeProfit * syminfo.mintick * 0.5 // 50% of total take profit
shortTP2 = sellStopPrice - takeProfit * syminfo.mintick
shortTPFull = sellStopPrice - takeProfit * syminfo.mintick
takeAmount1 = riskPercent / 2
takeAmount2 = riskPercent
takeAmountFull = riskPercent
headlineAlerts = "Alert Settings"
i_apiEnterLong = input.text_area('Enter Long - 3commas,alerteron etc', 'API Entry - Long', group = headlineAlerts)
i_apiExitLong = input.text_area('Exit Long - 3commas,alerteron etc', 'API Exit - Long', group = headlineAlerts)
i_apiEnterShort = input.text_area('Enter Short - 3commas,alerteron etc', 'API Entry - Short', group = headlineAlerts)
i_apiExitShort = input.text_area('Exit Short - 3commas,alerteron etc', 'API Exit - Short', group = headlineAlerts)
// #nl# => New line
// #side# => Buy or Sell (Long or Short)
// #symbol# => The ticker e.g. BTCUSDT
f_replaceKeys (_str) =>
_value = _str
_value := str.replace_all(_value, "#nl#", "\n")
// _value := str.replace_all(_value, "#side#", "\n") // does not make sense to me...
_value := str.replace_all(_value, "#symbol#", syminfo.ticker)
// #LongSL# => Long Stop loss
// #LongTP1# => Long Take Profit 1
// #LongTP2# => Long Take Profit 2
// #LongTPFULL# => Long Take Profit in FULL
// #TakeAmount1# => Percent to remove from trade on hitting TP1
// #TakeAmount2# => Percent to remove from trade on hitting TP2
// #TakeAmountFULL# => Percent to remove from trade on hitting TP3 (should be 100%)
f_replaceLongTokens (_str, _sl, _tp1, _tp2, _tpFull, _ta1, _ta2, _taFull) =>
_value = _str
_value := str.replace_all(_value, "#LongSL#", str.tostring(_sl))
_value := str.replace_all(_value, "#LongTP1#", str.tostring(_tp1))
_value := str.replace_all(_value, "#LongTP2#", str.tostring(_tp2))
_value := str.replace_all(_value, "#LongTPFULL#", str.tostring(_tpFull))
_value := str.replace_all(_value, "#TakeAmount1#", str.tostring(_ta1))
_value := str.replace_all(_value, "#TakeAmount2#", str.tostring(_ta2))
_value := str.replace_all(_value, "#TakeAmountFULL#", str.tostring(_taFull))
// #ShortSL# => Short Stop loss
// #ShortTP1# => Short Take Profit 1
// #ShortTP2# => Short Take Profit 2
// #ShortTPFULL# => Short Take Profit in FULL
// #TakeAmount1# => Percent to remove from trade on hitting TP1
// #TakeAmount2# => Percent to remove from trade on hitting TP2
// #TakeAmountFULL# => Percent to remove from trade on hitting TP3 (should be 100%)
f_replaceShortTokens (_str, _sl, _tp1, _tp2, _tpFull, _ta1, _ta2, _taFull) =>
_value = _str
_value := str.replace_all(_value, "#ShortSL#", str.tostring(_sl))
_value := str.replace_all(_value, "#ShortTP1#", str.tostring(_tp1))
_value := str.replace_all(_value, "#ShortTP2#", str.tostring(_tp2))
_value := str.replace_all(_value, "#ShortTPFULL#", str.tostring(_tpFull))
_value := str.replace_all(_value, "#TakeAmount1#", str.tostring(_ta1))
_value := str.replace_all(_value, "#TakeAmount2#", str.tostring(_ta2))
_value := str.replace_all(_value, "#TakeAmountFULL#", str.tostring(_taFull))
i_apiEnterLong := f_replaceKeys (i_apiEnterLong)
i_apiEnterLong := f_replaceLongTokens (i_apiEnterLong, longSL, longTP1, longTP2, longTPFull, takeAmount1, takeAmount2, takeAmountFull)
i_apiExitLong := f_replaceKeys (i_apiExitLong)
i_apiExitLong := f_replaceLongTokens (i_apiExitLong, longSL, longTP1, longTP2, longTPFull, takeAmount1, takeAmount2, takeAmountFull)
i_apiEnterShort := f_replaceKeys (i_apiEnterShort)
i_apiEnterShort := f_replaceShortTokens (i_apiEnterShort, shortSL, shortTP1, shortTP2, shortTPFull, takeAmount1, takeAmount2, takeAmountFull)
i_apiExitShort := f_replaceKeys (i_apiExitShort)
i_apiExitShort := f_replaceShortTokens (i_apiExitShort, shortSL, shortTP1, shortTP2, shortTPFull, takeAmount1, takeAmount2, takeAmountFull)
// ----- handline trade entries and exits --------------------------------------------------------------------------------------------------------------------------
// as soon as the session starts calculate stop prices based on recent swing high / low, create pending orders
if barstate.isconfirmed and inSession and not inSession[1]
buyStopPrice := swingHigh
sellStopPrice := swingLow
tradeID = str.tostring(strategy.closedtrades + strategy.opentrades + 1)
quantity = useRiskMagmt ? math.round(strategy.equity * riskPercent / stopLoss, 2) / syminfo.mintick : na
commentTemplate = "{0} QTY: {1,number,#.##} SL: {2} TP: {3}"
// price between recent swing high and low, a buy and sell stop order at swing high and low
if sellStopPrice < close and close < buyStopPrice
longComment = str.format(commentTemplate, tradeID + "L", quantity, stopLoss / 10, takeProfit / 10)
strategy.entry(tradeID + "L", strategy.long, qty = quantity, stop = buyStopPrice, comment = longComment, alert_message = i_apiEnterLong)
strategy.exit(tradeID + "SL", tradeID + "L", profit = takeProfit, loss = stopLoss, comment_loss = "SL", comment_profit = "TP", alert_message = i_apiExitLong)
shortComment = str.format(commentTemplate, tradeID + "S", quantity, stopLoss / 10, takeProfit / 10)
strategy.entry(tradeID + "S", strategy.short, qty = quantity, stop = sellStopPrice, comment = shortComment, alert_message = i_apiEnterShort)
strategy.exit(tradeID + "SL", tradeID + "S", profit = takeProfit, loss = stopLoss, comment_loss = "SL", comment_profit = "TP", alert_message = i_apiExitShort)
// price above swing high, only one sell stop order at swingg high
if close > buyStopPrice
shortComment = str.format(commentTemplate, tradeID + "S", quantity, stopLoss / 10, takeProfit / 10)
strategy.entry(tradeID + "S", strategy.short, qty = quantity, stop = buyStopPrice, comment = shortComment, alert_message = i_apiEnterShort)
strategy.exit(tradeID + "SL", tradeID + "S", profit = takeProfit, loss = stopLoss, comment_loss = "SL", comment_profit = "TP", alert_message = i_apiExitShort)
// price below swing low, only one buy stop order at swing low
if close < sellStopPrice
longComment = str.format(commentTemplate, tradeID + "L", quantity, stopLoss / 10, takeProfit / 10)
strategy.entry(tradeID + "L", strategy.long, qty = quantity, stop = sellStopPrice, comment = longComment, alert_message = i_apiEnterLong)
strategy.exit(tradeID + "SL", tradeID + "L", profit = takeProfit, loss = stopLoss, comment_loss = "SL", comment_profit = "TP", alert_message = i_apiExitLong)
// once the session is gone, reset prices and cancel all remaining pending orders, close open orders
if barstate.isconfirmed and not inSession
buyStopPrice := na
sellStopPrice := na
strategy.cancel_all()
currentTradeID = str.tostring(strategy.closedtrades + strategy.opentrades)
strategy.close(currentTradeID + "L", immediately = true, comment = "L: session end", alert_message = i_apiExitLong)
strategy.close(currentTradeID + "S", immediately = true, comment = "S: session end", alert_message = i_apiExitShort)
// as soon as the first pending order has been entered the remaing pending order shall be cancelled
if strategy.opentrades > 0
currentTradeID = str.tostring(strategy.closedtrades + strategy.opentrades)
strategy.cancel(currentTradeID + "S")
strategy.cancel(currentTradeID + "L")
|
Big Whale Purchases and Sales | https://www.tradingview.com/script/gYGCDkW2-Big-Whale-Purchases-and-Sales/ | Powerscooter | https://www.tradingview.com/u/Powerscooter/ | 382 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Powerscooter
//@version=5
strategy("Big Whale Purchases and Sales", "Big Whale Moves", overlay=true, initial_capital = 100, default_qty_type = strategy.cash, default_qty_value = 100, pyramiding = 5)
UseStrategy = input.bool(false,"Strategy Mode", "Use this box to switch between strategy and indicator mode", group = "Script Settings")
//Inputs
StdDevs = input(2.0,"Standard Deviations", "How many Standard Deviations need to be passed to identify an outlier. 0 will show all changes in whale holdings.", group = "Inputs")
//Chain ID
Source = input.string(title="Blockchain", defval="BTC", options=["BTC", "ETH", "DOGE", "ADA", "MATIC", "SHIB", "UNI", "OKB", "LEO", "LINK", "LTC", "FTT", "CRO", "ALGO",
"QNT", "BCH", "SAND", "MANA", "FXS", "AAVE", "CHZ", "HT", "LDO", "KCS", "AXS", "MKR", "ZEC", "GRT", "FTM", "SNX", "NEXO", "CRV", "BIT", "DASH", "BAT", "ENS"], group="Inputs")
SourceA = switch Source
"BTC" => "INTOTHEBLOCK:BTC_WHALESASSETS"
"ETH" => "INTOTHEBLOCK:ETH_WHALESASSETS"
"DOGE" => "INTOTHEBLOCK:DOGE_WHALESASSETS"
"ADA" => "INTOTHEBLOCK:ADA_WHALESASSETS"
"MATIC" => "INTOTHEBLOCK:MATIC_WHALESASSETS"
"SHIB" => "INTOTHEBLOCK:SHIB_WHALESASSETS"
"UNI" => "INTOTHEBLOCK:UNI_WHALESASSETS"
"OKB" => "INTOTHEBLOCK:OKB_WHALESASSETS"
"LEO" => "INTOTHEBLOCK:LEO_WHALESASSETS"
"LINK" => "INTOTHEBLOCK:LINK_WHALESASSETS"
"LTC" => "INTOTHEBLOCK:LTC_WHALESASSETS"
"FTT" => "INTOTHEBLOCK:FTT_WHALESASSETS"
"CRO" => "INTOTHEBLOCK:CRO_WHALESASSETS"
"ALGO" => "INTOTHEBLOCK:ALGO_WHALESASSETS"
"QNT" => "INTOTHEBLOCK:QNT_WHALESASSETS"
"BCH" => "INTOTHEBLOCK:BCH_WHALESASSETS"
"SAND" => "INTOTHEBLOCK:SAND_WHALESASSETS"
"MANA" => "INTOTHEBLOCK:MANA_WHALESASSETS"
"FXS" => "INTOTHEBLOCK:FXS_WHALESASSETS"
"AAVE" => "INTOTHEBLOCK:AAVE_WHALESASSETS"
"CHZ" => "INTOTHEBLOCK:CHZ_WHALESASSETS"
"HT" => "INTOTHEBLOCK:HT_WHALESASSETS"
"LDO" => "INTOTHEBLOCK:LDO_WHALESASSETS"
"KCS" => "INTOTHEBLOCK:KCS_WHALESASSETS"
"AXS" => "INTOTHEBLOCK:AXS_WHALESASSETS"
"MKR" => "INTOTHEBLOCK:MKR_WHALESASSETS"
"ZEC" => "INTOTHEBLOCK:ZEC_WHALESASSETS"
"GRT" => "INTOTHEBLOCK:GRT_WHALESASSETS"
"FTM" => "INTOTHEBLOCK:FTM_WHALESASSETS"
"SNX" => "INTOTHEBLOCK:SNX_WHALESASSETS"
"NEXO" => "INTOTHEBLOCK:NEXO_WHALESASSETS"
"CRV" => "INTOTHEBLOCK:CRV_WHALESASSETS"
"BIT" => "INTOTHEBLOCK:BIT_WHALESASSETS"
"DASH" => "INTOTHEBLOCK:DASH_WHALESASSETS"
"BAT" => "INTOTHEBLOCK:BAT_WHALESASSETS"
"ENS" => "INTOTHEBLOCK:ENS_WHALESASSETS"
Assets = request.security(SourceA, "D", close)
//Define day to day change
AssetMoves = ta.change(Assets,1)
//Catch outliers
var float bot=0
var float top=0
var float mid=0
if StdDevs != 0
[mid2,top2,bot2]=ta.bb(AssetMoves,21,StdDevs)
mid:=mid2
top:=top2
bot:=bot2
else
top:=0
bot:=0
//Mark the corresponding Bars
plotshape(AssetMoves>top and not UseStrategy,"Purchase",shape.triangleup, location.belowbar, size=size.normal, color=color.green, text = "Purchase", textcolor = color.green)
plotshape(AssetMoves<bot and not UseStrategy,"Sale",shape.triangledown, location.abovebar, size=size.normal, color=color.red, text = "Sale", textcolor = color.red)
//Order Conditions
LongCondition = AssetMoves>top and UseStrategy
ShortCondition = AssetMoves<bot and UseStrategy
//Order Execution
if LongCondition
strategy.entry("Long", strategy.long)
if ShortCondition
strategy.entry("Short", strategy.short) |
Heikin Ashi Supertrend | https://www.tradingview.com/script/9z16eauD-Heikin-Ashi-Supertrend/ | jordanfray | https://www.tradingview.com/u/jordanfray/ | 1,334 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jordanfray
//@version=5
// About This Indicator
// The default settings for this indicator are for BTC/USDT and intended to be used on the 3D timeframe to identify market trends.
// This indicator does a great job identifying whether the market is bullish, bearish, or consolidating.
// This can also work well on lower time frames to help identify when a trend is strong or when it's reversing.
strategy("Heikin Ashi Supertrend", overlay=true, max_bars_back=5000, default_qty_type=strategy.cash, default_qty_value=100, initial_capital=100, commission_type=strategy.commission.percent, close_entries_rule="ANY", commission_value=0.035, backtest_fill_limits_assumption=0, process_orders_on_close=true)
import jordanfray/threengine_global_automation_library/89 as bot
import jordanfray/obvFilter/2 as obv
// Colors - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
green = color.new(#2DBD85,0)
lightGreen = color.new(#2DBD85,90)
red = color.new(#E02A4A,0)
lightRed = color.new(#E02A4A,90)
yellow = color.new(#FFED00,0)
lightYellow = color.new(#FFED00,90)
purple = color.new(#5A00FF,0)
blue = color.new(#0C6090,0)
oceanBlue = color.new(#0C6090,0)
skyBlue = color.new(#00A5FF,0)
lightBlue = color.new(#00A5FF,80)
black = color.new(#000000,0)
gray = color.new(#AAAAAA,0)
white = color.new(#ffffff,0)
transparent = color.new(#000000,100)
// Tooltips
alertatronSecretTip = "The key that is configured in Alertatron that selects which exchange integration you want to use."
exchangeTooltip = "Pick the exchange that your Alertatron API Secret is configured to. This is used to get the right divider between the pair and the base currency."
exchangeCurrencyOverrideTip = "If you want to use a different base currency than the current chart, you can override it here. Be sure it matches the exchange base currency. \n \n Do not include the currency/symbol divider in this."
exchangeCurrencySymbolTip = "If you want to use a different symbol than the current chart, you can override it here. Be sure it matches the exchange symbol. \n \n Do not include the currency/symbol divider in this."
moveStopToolTip = "If enabled, the stop loss will be moved to a price relative to the average entry price using a percentange as an offset after the price reaches the 'after' threshold. \n 0 = break even.\n \n Default: .1"
// Strategy Settings - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
strategyIdentifier = input.string(defval="HASTXXXUSDT (Nm)", title="Strategy Identifier", group="Strategy Information")
supertrendAtrPeriod = input.int(defval = 10, step = 1, title = "ATR Length", group = "Supertrend")
supertrendAtrMultiplier = input.float(defval = 2.7, step = 0.1, title = "ATR Multiplier", group = "Supertrend")
lotSize = input.float(defval=100, title="Lot Size", group="Entry Settings")
lotSizeType = input.string(defval="Dollars", title="Lot Size Type", options=["Percent Of Account","Dollars", "Contracts"], group="Entry Settings")
profitTargetPercent = input.float(defval = 47.0, title = "Profit Target (%)", step = .25, group="Exit Settings")
stopLimitTrigger = input.float(defval=21, title="Stop Limit Trigger (%)", step=0.25, group="Exit Settings")
stopLimitOffset = input.float(defval=0.10, title="Stop Limit Offset (%)", step=0.01, group="Exit Settings")
enableMoveStopToBreakEven = input.bool(defval=true, title="Move Stop Loss", group="Move Stop Loss")
moveTo = input.float(defval=1.0, title="to (%)", tooltip=moveStopToolTip)
moveAfter = input.float(defval=4.0, title="after (%)", tooltip=moveStopToolTip)
manuallyCloseTrade = input.bool(defval=false, title="Manullay Close Trade?", group="Manually Close Trade")
dateTimeClosed = input.time(defval=timestamp("01 Jan 2022 00:00"), title="Date/Time When Trade Was Closed", group="Manually Close Trade")
priceClosed = input.price(defval=0.0, title="Price Trade Was Closed At", group="Manually Close Trade")
// Trade Automation
enableWebhookMessages = input.bool(defval=false, title="Enable Webook Messages", group="Automation Settings")
tradeAutomationExchange = input.string(defval="ByBit", options=["ByBit", "FTX.us"], title="Exchange", group="Automation Settings", tooltip=exchangeTooltip)
tradeAutomationSecret = input.string(defval="haStEthUsdt", title="Alertatron API Secret", group="Automation Settings", tooltip=alertatronSecretTip)
tradeAutomationLeverage = input.int(defval=1, title="Leverage Amount", group="Automation Settings")
tradeAutomationLeverageType = input.string(defval="Cross", title="Leverage Type", options=["Cross", "Isolated"], group="Automation Settings")
tradeAutomationCurrencyOverride = input.string(defval="", title="Currency Override", group="Automation Settings", tooltip=exchangeCurrencyOverrideTip)
tradeAutomationSymbolOverride = input.string(defval="", title="Symbol Override", group="Automation Settings", tooltip=exchangeCurrencySymbolTip)
exchangeQtyDecimals = input.int(defval=3, title="Order QTY Decimal Rounding", group="Automation Settings")
showDebugTable = input.bool(defval=false, title="Show Debug Table", group="Testing")
// Position States
currentlyInLongPosition = strategy.position_size > 0
currentlyInShortPosition = strategy.position_size < 0
currentlyInAPosition = strategy.position_size != 0
// Heikin Ashi Candles
haOpen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
haHigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
haLow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
haClose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
plotcandle(haOpen < haClose ? haOpen : na, haHigh, haLow, haClose, title='Green Candles', color=green, wickcolor=green, bordercolor=green, display=display.pane)
plotcandle(haOpen >= haClose ? haOpen : na, haHigh, haLow, haClose, title='Red Candles', color=red, wickcolor=red, bordercolor=red, display=display.pane)
plot(display=display.status_line, series=haOpen, color=green)
plot(display=display.status_line, series=haHigh, color=green)
plot(display=display.status_line, series=haLow, color=red)
plot(display=display.status_line, series=haClose, color=red)
// HA Supertrend
haTrueRange = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ta.atr(supertrendAtrPeriod)) // math.max(haHigh - haLow, math.abs(haHigh - haClose[1]), math.abs(haLow - haClose[1]))
haSupertrendUp = ((haHigh + haLow) / 2) - (supertrendAtrMultiplier * haTrueRange)
haSupertrendDown = ((haHigh + haLow) / 2) + (supertrendAtrMultiplier * haTrueRange)
float trendingUp = na
float trendingDown = na
direction = 0
trendingUp := haClose[1] > trendingUp[1] ? math.max(haSupertrendUp,trendingUp[1]) : haSupertrendUp
trendingDown := haClose[1] < trendingDown[1] ? math.min(haSupertrendDown,trendingDown[1]) : haSupertrendDown
direction := haClose > trendingDown[1] ? 1: haClose < trendingUp[1]? -1: nz(direction[1],1)
supertrend = direction == 1 ? trendingUp : trendingDown
supertrendUp = ta.change(direction) < 0
supertrendDown = ta.change(direction) > 0
// Average Entry Price
float averageEntryPrice = currentlyInAPosition ? strategy.position_avg_price : close
justClosedPosition = ta.change(averageEntryPrice)
barsSinceOpen = currentlyInAPosition ? (bar_index - strategy.opentrades.entry_bar_index(0)) : 0
// Profit and Loss
profitAndLoss = strategy.opentrades.profit(0)
profitAndLossPercent = math.round(((close - averageEntryPrice) / averageEntryPrice) * 100,2)
// Profit Target
profitTarget = currentlyInLongPosition ? averageEntryPrice + (averageEntryPrice * (profitTargetPercent/100)) : averageEntryPrice - (averageEntryPrice * (profitTargetPercent/100))
// Stop Loss Criteria
float stopLossLimitPrice = currentlyInLongPosition ? math.round(averageEntryPrice - (averageEntryPrice * stopLimitTrigger/100),exchangeQtyDecimals) : currentlyInShortPosition ? math.round(averageEntryPrice + (averageEntryPrice * stopLimitTrigger/100),exchangeQtyDecimals) : na
float stopLossTriggerPrice = currentlyInLongPosition ? math.round(stopLossLimitPrice + (stopLossLimitPrice * stopLimitOffset/100),exchangeQtyDecimals) : currentlyInShortPosition ? math.round(stopLossLimitPrice - (stopLossLimitPrice * stopLimitOffset/100),exchangeQtyDecimals) : na
// Move Stop Loss
float moveStopLossAfter = currentlyInLongPosition ? math.round(averageEntryPrice + (averageEntryPrice * (moveAfter/100)),exchangeQtyDecimals) : currentlyInShortPosition ? math.round(averageEntryPrice - (averageEntryPrice * (moveAfter/100)),exchangeQtyDecimals) : na
var bool moveStopTriggered = false
moveStopLossTo = currentlyInLongPosition ? math.round(averageEntryPrice + (averageEntryPrice * (moveTo/100)),exchangeQtyDecimals) : currentlyInShortPosition ? math.round(averageEntryPrice - (averageEntryPrice * (moveTo/100)),exchangeQtyDecimals) : na
if currentlyInLongPosition and high > moveStopLossAfter and enableMoveStopToBreakEven and moveStopTriggered == false
moveStopTriggered := true
if currentlyInShortPosition and low < moveStopLossAfter and enableMoveStopToBreakEven and moveStopTriggered == false
moveStopTriggered := true
if enableMoveStopToBreakEven and moveStopTriggered
stopLossLimitPrice := moveStopLossTo
stopLossTriggerPrice := currentlyInLongPosition ? math.round(stopLossLimitPrice + (stopLossLimitPrice * stopLimitOffset/100),exchangeQtyDecimals) : currentlyInShortPosition ? math.round(stopLossLimitPrice - (stopLossLimitPrice * stopLimitOffset/100),exchangeQtyDecimals) : na
if not currentlyInAPosition or justClosedPosition
moveStopTriggered := false
// Entry/Exit Criteria
bool openLong = supertrendDown
bool openShort = supertrendUp
bool exitLong = currentlyInLongPosition and close > profitTarget
bool exitShort = currentlyInShortPosition and close < profitTarget
bool longStopLoss = currentlyInLongPosition and close < stopLossTriggerPrice and barsSinceOpen > 2
bool shortStopLoss = currentlyInShortPosition and close > stopLossTriggerPrice and barsSinceOpen > 2
bool manuallyCloseShort = currentlyInShortPosition and manuallyCloseTrade and time == dateTimeClosed
bool manuallyCloseLong = currentlyInLongPosition and manuallyCloseTrade and time == dateTimeClosed
// Alertatron Webhook Messages - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[symbol,baseCurrency] = bot.getPairOverrides(tradeAutomationSymbolOverride,tradeAutomationCurrencyOverride)
[contractCount,entryAmount] = bot.getLotSize(lotSizeType, lotSize, tradeAutomationLeverage, exchangeQtyDecimals)
string enterLongAlertMessage = enableWebhookMessages ? bot.getAlertatronMarketEntryMessage(secret=tradeAutomationSecret, symbol=symbol, baseCurrency=baseCurrency, pairDivider=bot.getPairDividerForExchange(tradeAutomationExchange), side="buy", symbolMaxDecimals=exchangeQtyDecimals, leverage=tradeAutomationLeverage, leverageType=tradeAutomationLeverageType, entryPrice=close, amount=lotSize, amountType=lotSizeType, stopTrigger=stopLimitTrigger, stopTriggerType="percent", stopLimitOffset=stopLimitOffset) : "Webhooks disabled by strategy."
string enterShortAlertMessage = enableWebhookMessages ? bot.getAlertatronMarketEntryMessage(secret=tradeAutomationSecret, symbol=symbol, baseCurrency=baseCurrency, pairDivider=bot.getPairDividerForExchange(tradeAutomationExchange), side="sell", symbolMaxDecimals=exchangeQtyDecimals, leverage=tradeAutomationLeverage, leverageType=tradeAutomationLeverageType, entryPrice=close, amount=lotSize, amountType=lotSizeType, stopTrigger=stopLimitTrigger, stopTriggerType="percent", stopLimitOffset=stopLimitOffset) : "Webhooks disabled by strategy."
string exitLongAlertMessage = enableWebhookMessages ? bot.getAlertatronMarketExitMessage(secret=tradeAutomationSecret, symbol=symbol, baseCurrency=baseCurrency, pairDivider=bot.getPairDividerForExchange(tradeAutomationExchange), side="sell") : "Webhooks disabled by strategy."
string exitShortAlertMessage = enableWebhookMessages ? bot.getAlertatronMarketExitMessage(secret=tradeAutomationSecret, symbol=symbol, baseCurrency=baseCurrency, pairDivider=bot.getPairDividerForExchange(tradeAutomationExchange), side="buy") : "Webhooks disabled by strategy."
// Long Entries/Exits - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if openLong
strategy.entry(id="Long", direction=strategy.long, qty=contractCount, alert_message=enterLongAlertMessage)
if exitLong
strategy.close(id="Long", qty_percent=100, comment="Exit Long", alert_message=exitLongAlertMessage)
if longStopLoss
strategy.exit(id=moveStopTriggered ? "Moved Stop" : "Stop Loss", from_entry="Long", qty_percent=100, stop=stopLossLimitPrice)
if manuallyCloseLong
strategy.exit(id="Manually Close Long", from_entry="Long", qty_percent=100, stop=priceClosed)
// Short Entries/Exits - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if openShort
strategy.entry(id="Short", direction=strategy.short, qty=contractCount, alert_message=enterShortAlertMessage)
if exitShort
strategy.close(id="Short", qty_percent=100, comment="Exit Short", alert_message=exitShortAlertMessage)
if shortStopLoss
strategy.exit(id=moveStopTriggered ? "Moved Stop" : "Stop Loss", from_entry="Short", qty_percent=100, stop=stopLossLimitPrice)
if manuallyCloseShort
strategy.exit(id="Manually Close Short", from_entry="Short", qty_percent=100, stop=priceClosed)
// Plots, Lines, and Labels
bodyMiddle = plot((haOpen + haClose) / 2, display=display.none)
downTrend = plot(direction < 0 ? supertrend : na, "Down Trend", color = red, style=plot.style_linebr)
upTrend = plot(direction < 0? na : supertrend, "Up Trend", color = green, style=plot.style_linebr)
fill(bodyMiddle, upTrend, lightGreen, fillgaps=false)
fill(bodyMiddle, downTrend, lightRed, fillgaps=false)
color stopLossColor = red
color stopLossBackgroundColor = red
if currentlyInLongPosition and stopLossLimitPrice > averageEntryPrice
stopLossColor := green
stopLossBackgroundColor := lightGreen
else
if currentlyInShortPosition and stopLossLimitPrice < averageEntryPrice
stopLossColor := green
stopLossBackgroundColor := lightGreen
else
stopLossColor := red
stopLossBackgroundColor := lightRed
var label stopLossLabel = na
var label moveStopAfterLabel = na
var label averageEntryLabel = na
var label profitAndLossLabel = na
var label profitTargetLabel = na
var line stopLossTriggerLine = na
var line moveStopAfterLine = na
var line stopLossLimitLine = na
var line averageEntryLine = na
var line profitTargetLine = na
var linefill stopLossBackground = na
var linefill profitTargetBackground = na
label.delete(stopLossLabel)
label.delete(moveStopAfterLabel)
label.delete(averageEntryLabel)
label.delete(profitAndLossLabel)
label.delete(profitTargetLabel)
line.delete(stopLossTriggerLine)
line.delete(moveStopAfterLine)
line.delete(stopLossLimitLine)
line.delete(averageEntryLine)
line.delete(profitTargetLine)
linefill.delete(stopLossBackground)
linefill.delete(profitTargetBackground)
string stopLossLabelText = na
if moveStopLossAfter and not moveStopTriggered
stopLossLabelText := " Stop Trigger | " + str.format("{0,number,currency}", stopLossTriggerPrice) + "\n" + " Stop Limit | " + str.format("{0,number,currency}" + " ", stopLossLimitPrice) + "\n" + " Moving to " + str.format("{0,number,currency}", moveStopLossTo) + " after " + str.tostring(moveAfter) + "% "
else
stopLossLabelText := " Stop Trigger | " + str.format("{0,number,currency}", stopLossTriggerPrice) + "\n" + " Stop Limit | " + str.format("{0,number,currency}" + " ", stopLossLimitPrice)
xOffset = 2 * timeframe.in_seconds(timeframe.period) * 1000
profitAndLossLabel := label.new(x=time + xOffset, xloc=xloc.bar_time, y=close, style=label.style_label_left, size=size.normal, color=profitAndLoss > 0 ? green : red, textcolor=white, text=" P&L | " + str.format("{0,number,currency}", profitAndLoss) + " (" + str.tostring(profitAndLossPercent) + "%) ")
averageEntryLabel := label.new(x=time + xOffset, xloc=xloc.bar_time, y=averageEntryPrice, style=label.style_label_left, size=size.normal, color=oceanBlue, textcolor=white, text=" Entry | " + str.format("{0,number,currency}" + " ", averageEntryPrice))
stopLossLabel := label.new(x=time + xOffset, xloc=xloc.bar_time, y=stopLossLimitPrice, style=label.style_label_left, textalign=text.align_left, size=size.normal, color=stopLossColor, textcolor=white, text=stopLossLabelText)
averageEntryLine := line.new(x1=strategy.opentrades.entry_bar_index(0), y1=averageEntryPrice, x2=bar_index, y2=averageEntryPrice, color=oceanBlue, width=2, xloc=xloc.bar_index, style=line.style_solid)
profitTargetLine := line.new(x1=strategy.opentrades.entry_bar_index(0), y1=profitTarget, x2=bar_index, y2=profitTarget, color=green, width=1, xloc=xloc.bar_index, style=line.style_solid)
profitTargetLabel := label.new(x=time + xOffset, xloc=xloc.bar_time, y=profitTarget, style=label.style_label_left, size=size.normal, color=red, textcolor=white, text=" ProfitTarget | " + str.format("{0,number,currency}" + " ", profitTarget))
stopLossTriggerLine := line.new(x1=strategy.opentrades.entry_bar_index(0), y1=stopLossTriggerPrice, x2=bar_index, y2=stopLossTriggerPrice, color=stopLossColor, width=1, xloc=xloc.bar_index, style=line.style_solid)
stopLossLimitLine := line.new(x1=strategy.opentrades.entry_bar_index(0), y1=stopLossLimitPrice, x2=bar_index, y2=stopLossLimitPrice, color=stopLossColor, width=1, xloc=xloc.bar_index, style=line.style_solid)
stopLossBackground := linefill.new(averageEntryLine, stopLossLimitLine, stopLossBackgroundColor)
profitTargetBackground := linefill.new(averageEntryLine, profitTargetLine, lightGreen)
if enableMoveStopToBreakEven
moveStopAfterLabel := label.new(x=time + xOffset, xloc=xloc.bar_time, y=moveStopLossAfter, style=label.style_label_left, size=size.normal, color=purple, textcolor=white, text=" Move Stop After " + str.tostring(moveAfter) + "% | " + str.format("{0,number,currency}" + " ", moveStopLossAfter))
moveStopAfterLine := line.new(x1=strategy.opentrades.entry_bar_index(0), y1=moveStopLossAfter, x2=bar_index, y2=moveStopLossAfter, color=purple, width=1, xloc=xloc.bar_index, style=line.style_solid)
stopLimitStatus = plot(stopLossLimitPrice, color=stopLossColor, display=display.price_scale)
stopTriggerStatus = plot(stopLossTriggerPrice, color=stopLossColor, display=display.price_scale)
averageEntryStatus = plot(averageEntryPrice, color=oceanBlue, display=display.price_scale)
if not currentlyInAPosition
label.delete(stopLossLabel)
label.delete(moveStopAfterLabel)
label.delete(averageEntryLabel)
label.delete(profitAndLossLabel)
label.delete(profitTargetLabel)
line.delete(stopLossTriggerLine)
line.delete(moveStopAfterLine)
line.delete(stopLossLimitLine)
line.delete(averageEntryLine)
line.delete(profitTargetLine)
linefill.delete(stopLossBackground)
linefill.delete(profitTargetBackground)
// Alertatron Automation Status Message
warning_color = enableWebhookMessages == true ? red : green
var table status = table.new(position=position.top_right, columns=2, rows=100, bgcolor=warning_color, border_color=warning_color, border_width=1)
rowCount2 = 0
table.cell(status, 0, rowCount2, text=" " + strategyIdentifier, text_color=white, text_halign=text.align_left, bgcolor=warning_color, text_size=size.small)
table.cell(status, 1, rowCount2, text=" ", text_color=white, text_halign=text.align_left, bgcolor=warning_color, text_size=size.small)
rowCount2 += 1
table.cell(status, 0, rowCount2, text=" " + "Webhook Enabled", text_color=white, text_halign=text.align_left, bgcolor=warning_color, text_size=size.small)
table.cell(status, 1, rowCount2, text=str.tostring(enableWebhookMessages) + " ", text_color=white, text_halign=text.align_left, bgcolor=warning_color, text_size=size.small)
rowCount2 += 1
table.cell(status, 0, rowCount2, text=" " + "Exchange", text_color=white, text_halign=text.align_left, bgcolor=warning_color, text_size=size.small)
table.cell(status, 1, rowCount2, text=tradeAutomationExchange + " ", text_color=white, text_halign=text.align_left, bgcolor=warning_color, text_size=size.small)
rowCount2 += 1
table.cell(status, 0, rowCount2, text=" " + "Code", text_color=white, text_halign=text.align_left, bgcolor=warning_color, text_size=size.small)
table.cell(status, 1, rowCount2, text=tradeAutomationSecret == "" ? "N/A" : tradeAutomationSecret + " ", text_color=white, text_halign=text.align_left, bgcolor=warning_color, text_size=size.small)
rowCount2 += 1
table.cell(status, 0, rowCount2, text=" " + "Leverage", text_color=white, text_halign=text.align_left, bgcolor=warning_color, text_size=size.small)
table.cell(status, 1, rowCount2, text=str.tostring(tradeAutomationLeverageType) + " " + str.tostring(tradeAutomationLeverage) + "x", text_color=white, text_halign=text.align_left, bgcolor=warning_color, text_size=size.small)
rowCount2 += 1
table.cell(status, 0, rowCount2, text=" " + "Pair", text_color=white, text_halign=text.align_left, bgcolor=warning_color, text_size=size.small)
table.cell(status, 1, rowCount2, text=str.tostring(symbol) + bot.getPairDividerForExchange(tradeAutomationExchange) + str.tostring(baseCurrency), text_color=white, text_halign=text.align_left, bgcolor=warning_color, text_size=size.small)
rowCount2 += 1
lotSizeDisplay = lotSizeType == "Percent Of Account" ? str.format("{0,number,percent}" + " of account ", lotSize/100): str.format("{0,number,currency}", lotSize)
table.cell(status, 0, rowCount2, text=" " + "Lot Size", text_color=white, text_halign=text.align_left, bgcolor=warning_color, text_size=size.small)
table.cell(status, 1, rowCount2, text=lotSizeDisplay + " ", text_color=white, text_halign=text.align_left, bgcolor=warning_color, text_size=size.small)
rowCount2 += 1
table.cell(status, 0, rowCount2, text=" " + "Account Size", text_color=white, text_halign=text.align_left, bgcolor=warning_color, text_size=size.small)
table.cell(status, 1, rowCount2, text=str.format("{0,number,currency}" + " ", strategy.initial_capital), text_color=white, text_halign=text.align_left, bgcolor=warning_color, text_size=size.small)
rowCount2 += 1
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// D E B U G M O D E - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if showDebugTable
var table debug = table.new(position=position.bottom_left, columns=2, rows=100, bgcolor=gray, border_color=gray, border_width=2)
rowCount = 0
table.cell(debug, 0, rowCount, text="enterLongAlertMessage: ", text_color=white, text_halign=text.align_left, bgcolor=gray, text_size=size.small)
table.cell(debug, 1, rowCount, text=str.tostring(enterLongAlertMessage), text_color=white, text_halign=text.align_left, bgcolor=gray, text_size=size.small)
rowCount += 1
table.cell(debug, 0, rowCount, text="enterShortAlertMessage: ", text_color=white, text_halign=text.align_left, bgcolor=gray, text_size=size.small)
table.cell(debug, 1, rowCount, text=str.tostring(enterShortAlertMessage), text_color=white, text_halign=text.align_left, bgcolor=gray, text_size=size.small)
rowCount += 1
table.cell(debug, 0, rowCount, text="exitLongAlertMessage: ", text_color=white, text_halign=text.align_left, bgcolor=gray, text_size=size.small)
table.cell(debug, 1, rowCount, text=str.tostring(exitLongAlertMessage), text_color=white, text_halign=text.align_left, bgcolor=gray, text_size=size.small)
rowCount += 1
table.cell(debug, 0, rowCount, text="exitShortAlertMessage: ", text_color=white, text_halign=text.align_left, bgcolor=gray, text_size=size.small)
table.cell(debug, 1, rowCount, text=str.tostring(exitShortAlertMessage), text_color=white, text_halign=text.align_left, bgcolor=gray, text_size=size.small)
rowCount += 1
table.cell(debug, 0, rowCount, text="moveStopTriggered: ", text_color=white, text_halign=text.align_left, bgcolor=gray, text_size=size.small)
table.cell(debug, 1, rowCount, text=str.tostring(moveStopTriggered), text_color=white, text_halign=text.align_left, bgcolor=gray, text_size=size.small)
rowCount += 1
table.cell(debug, 0, rowCount, text="longStopLoss (stopLossTriggerPrice): ", text_color=white, text_halign=text.align_left, bgcolor=gray, text_size=size.small)
table.cell(debug, 1, rowCount, text=str.tostring(longStopLoss) + " | " + str.tostring(stopLossTriggerPrice), text_color=white, text_halign=text.align_left, bgcolor=gray, text_size=size.small)
rowCount += 1
table.cell(debug, 0, rowCount, text="barsSinceOpen", text_color=white, text_halign=text.align_left, bgcolor=gray, text_size=size.small)
table.cell(debug, 1, rowCount, text=str.tostring(barsSinceOpen), text_color=white, text_halign=text.align_left, bgcolor=gray, text_size=size.small) |
Click Draw TrendLine [UhoKang] v2 | https://www.tradingview.com/script/570UaPp3-Click-Draw-TrendLine-UhoKang-v2/ | zard96 | https://www.tradingview.com/u/zard96/ | 349 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
strategy("Click Draw TrendLine [UhoKang] v2", shorttitle="Click TrendLine v2", overlay=true, initial_capital=10000,default_qty_type=strategy.percent_of_equity,default_qty_value=20,commission_value=0.075,pyramiding = 5, slippage=3, process_orders_on_close=true)
// This is an indicator that directly draws a trend line by clicking on the candle.
// Click to Create Trend lines !!
// Create a trend line by connecting A, B, and C with three vertices.
// 1. Draw Bear Trend line
// Click [A] pivot high : First pivothigh of the downtrend line
// Click [B] pivot low : pivotlow of the downtrend line
// Click [C] pivot high : Second pivothigh of the downtrend line
// 2. Draw Bull Trend line
// Click [A] pivot low : First pivotlow of the uptrend line
// Click [B] pivot high : pivothigh of the uptrend line
// Click [C] pivot low : Second pivotlow of the uptrend line
// Modefiy Trendlines
// 1. Edit Bear Trend line
// Drag Red[A],[B],[C]
// 2. Edit Bull Trend line
// Drag Green[A],[B],[C]
/////////////////////////////////////////////// TrendLine /////////////////////////////////////////////////////////
// 1. input
var TriangleHigh_A = input.time(timestamp("2021-12-30"), confirm = true, title = "Bear Trendline : [A] Pivot high")
var TriangleHigh_B = input.time(timestamp("2021-12-30"), confirm = true, title = "Bear Trendline : [B] Pivot low")
var TriangleHigh_C = input.time(timestamp("2021-12-30"), confirm = true, title = "Bear Trendline : [C] Pivot high")
var TriangleLow_A = input.time(timestamp("2021-12-30"), confirm = true, title = "Bull Trendline : [A] Pivot low")
var TriangleLow_B = input.time(timestamp("2021-12-30"), confirm = true, title = "Bull Trendline : [B] Pivot high")
var TriangleLow_C = input.time(timestamp("2021-12-30"), confirm = true, title = "Bull Trendline : [C] Pivot low")
// 2. get bar_index of pivotpoint (피봇의 인덱스를 구하기)
BigH1 = TriangleHigh_A == time ? bar_index : na
BigHR1 = TriangleHigh_B == time ? bar_index : na
BigH2 = TriangleHigh_C == time ? bar_index : na
BigL1 = TriangleLow_A == time ? bar_index: na
BigLR1 = TriangleLow_B == time ? bar_index: na
BigL2 = TriangleLow_C == time ? bar_index : na
// 2. get price of pivotpoint (피봇의 가격을 구하기)
BigH_price1 = BigH1 ? high : na
BigH_price2 = BigH2 ? high : na
BigL_price1 = BigL1 ? low : na
BigL_price2 = BigL2 ? low : na
BigHR_price1 = BigHR1 ? low : na
BigLR_price1 = BigLR1 ? high : na
// 3. set datas (고점의 정보들을 var 변수에 기록해두기)
// trendlines var (긴추세선 변수 기록)
var BigH_Line_index1 = int(na)
var BigH_Line_index2 = int(na)
var BigL_Line_index1 = int(na)
var BigL_Line_index2 = int(na)
var BigH_Line_price1 = float(na)
var BigH_Line_price2 = float(na)
var BigL_Line_price1 = float(na)
var BigL_Line_price2 = float(na)
BigH_Line_index1 := BigH1? BigH1: BigH_Line_index1 [1]
BigH_Line_index2 := BigH2? BigH2: BigH_Line_index2 [1]
BigL_Line_index1 := BigL1? BigL1: BigL_Line_index1 [1]
BigL_Line_index2 := BigL2? BigL2: BigL_Line_index2 [1]
BigH_Line_price1 := BigH_price1? BigH_price1 : BigH_Line_price1 [1]
BigH_Line_price2 := BigH_price2? BigH_price2 : BigH_Line_price2 [1]
BigL_Line_price1 := BigL_price1? BigL_price1 : BigL_Line_price1 [1]
BigL_Line_price2 := BigL_price2? BigL_price2 : BigL_Line_price2 [1]
// parallel lines var (평행선 변수 기록)
var BigHR_Line_price1 = float(na)
var BigLR_Line_price1 = float(na)
var BigH_Atr = float(na)
var BigL_Atr = float(na)
var BigHR_index = int(na)
var BigLR_index = int(na)
BigHR_Line_price1 := BigHR_price1? BigHR_price1 : BigHR_Line_price1 [1]
BigLR_Line_price1 := BigLR_price1? BigLR_price1 : BigLR_Line_price1 [1]
BigHR_index := BigHR1 ? BigHR1 : BigHR_index[1]
BigLR_index := BigLR1 ? BigLR1 : BigLR_index[1]
// mini trendlines var (짧은추세선 변수 기록)
var MidH_Line_index1 = int(na)
var MidH_Line_index2 = int(na)
var MidL_Line_index1 = int(na)
var MidL_Line_index2 = int(na)
var MidH_Line_price1 = float(na)
var MidH_Line_price2 = float(na)
var MidL_Line_price1 = float(na)
var MidL_Line_price2 = float(na)
// 4. plotshape inputpoint on chart 입력 받았는지 차트에 표시하기
plotshape(BigH1, location = location.abovebar, color=color.maroon, textcolor=color.yellow, text = "A", style = shape.labeldown)
plotshape(BigHR1, location = location.belowbar, color=color.maroon, textcolor=color.yellow, text = "B", style = shape.labeldown)
plotshape(BigH2, location = location.abovebar, color=color.maroon, textcolor=color.yellow, text = "C", style = shape.labeldown)
plotshape(BigL1, location = location.belowbar, color=color.olive, textcolor=color.white, text = "A", style = shape.labelup)
plotshape(BigLR1, location = location.abovebar, color=color.olive, textcolor=color.white, text = "B", style = shape.labelup)
plotshape(BigL2, location = location.belowbar, color=color.olive, textcolor=color.white, text = "C", style = shape.labelup)
// 5. plot startpoint of trendlines (추세선이 생성된 지점의 라인 그리기)
plot(BigH1 ? high : BigH2 ? high : na, color=color.new(color.maroon,30), style=plot.style_line, linewidth=1, editable=false, title = "iAC guideline")
plot(BigHR1 ? low : BigH1 ? high : na, color=color.new(color.maroon,80), style=plot.style_line, linewidth=1, editable=false, title = "AB guideline")
plot(BigHR1 ? low : BigH2 ? high : na, color=color.new(color.maroon,80), style=plot.style_line, linewidth=1, editable=false, title = "BC guideline")
plot(BigL1 ? low : BigL2 ? low : na, color=color.new(color.olive,30), style=plot.style_line, linewidth=1, editable=false, title = "AC guideline")
plot(BigLR1 ? high : BigL1 ? low : na, color=color.new(color.olive,80), style=plot.style_line, linewidth=1, editable=false, title = "AB guideline")
plot(BigLR1 ? high : BigL2 ? low : na, color=color.new(color.olive,80), style=plot.style_line, linewidth=1, editable=false, title = "BC guideline")
/////////////////////////////////////////////////////// 추 세 선 계 산 하 기 ////////////////////////////////////////////////////////
////////////////////////////////////////////////////// calc trendline ///////////////////////////////////////////////////////////
// get avg of trendline (추세선 곡률계산)
avgLine(src1,src2, x1, x2) => // pivot price1, pivot price2, pivot index1, pivot index2 (가격1, 가격2, 시작점, 끝점)
avgLineRatio = (src1 - src2)/(x2-x1)
avgLineRatioLast = -(avgLineRatio * (bar_index-x2)) // x2 꼭지점 ~ 현재 꼭지점의 차이를 계산
// calc trendlines (추세선 계산)
BigH_Avg = avgLine(BigH_Line_price1,BigH_Line_price2,BigH_Line_index1,BigH_Line_index2)
BigL_Avg = avgLine(BigL_Line_price1,BigL_Line_price2,BigL_Line_index1,BigL_Line_index2)
MidH_Avg = avgLine(MidH_Line_price1,MidH_Line_price2,MidH_Line_index1,MidH_Line_index2)
MidL_Avg = avgLine(MidL_Line_price1,MidL_Line_price2,MidL_Line_index1,MidL_Line_index2)
BigH_Line = BigH_Line_price2 + BigH_Avg
BigL_Line = BigL_Line_price2 + BigL_Avg
MidH_Line = MidH_Line_price2 + MidH_Avg
MidL_Line = MidL_Line_price2 + MidL_Avg
// calc triangles (삼각수렴 계산)
lineTop = float(na)
lineMid = float(na)
lineBot = float(na)
if BigH_Line and BigL_Line and BigH_Line > BigL_Line
lineHeight = (BigH_Line - BigL_Line)/4
lineTop := BigL_Line + (lineHeight*3)
lineMid := BigL_Line + (lineHeight*2)
lineBot := BigL_Line + (lineHeight*1)
// calc trendLine and parallel lines (추세선과 평행선의 간격계산)
BigH_Atr := (BigH_Line_price1 - BigHR_Line_price1)
BigH_Atr:= BigH_Atr - (BigH_Line_price1-BigH_Line_price2) * (BigHR_index - BigH_Line_index1)/(BigH_Line_index2 - BigH_Line_index1)
BigL_Atr := (BigLR_Line_price1 - BigL_Line_price1)
BigL_Atr:= BigL_Atr + (BigL_Line_price1-BigL_Line_price2) * (BigLR_index - BigL_Line_index1)/(BigL_Line_index2 - BigL_Line_index1)
BigH_TrendLineMax = BigH_Line - BigH_Atr
BigH_TrendLineTop = BigH_Line - BigH_Atr*0.25
BigH_TrendLineMid = BigH_Line - BigH_Atr*0.5
BigH_TrendLineBot = BigH_Line - BigH_Atr*0.75
BigL_TrendLineMax = BigL_Line + BigL_Atr
BigL_TrendLineTop = BigL_Line + BigL_Atr*0.75
BigL_TrendLineMid = BigL_Line + BigL_Atr*0.5
BigL_TrendLineBot = BigL_Line + BigL_Atr*0.25
// calc price line for trade (매수선 계산)
LineRange = input.float(0.05, title = "Grid percent value", step = 0.01)
BigH_Line_Buy2 = BigH_Line -(BigH_TrendLineMax - BigH_TrendLineTop )*LineRange*2
BigH_Line_Buy1 = BigH_Line -(BigH_TrendLineMax - BigH_TrendLineTop )*LineRange
BigH_Line_Sell1 = BigH_Line +(BigH_TrendLineMax - BigH_TrendLineTop )*LineRange
BigH_Line_Sell2 = BigH_Line +(BigH_TrendLineMax - BigH_TrendLineTop )*LineRange*2
BigL_Line_Buy2 = BigL_Line -(BigL_TrendLineBot - BigL_TrendLineMax )*LineRange*2
BigL_Line_Buy1 = BigL_Line -(BigL_TrendLineBot - BigL_TrendLineMax )*LineRange
BigL_Line_Sell1 = BigL_Line +(BigL_TrendLineBot - BigL_TrendLineMax )*LineRange
BigL_Line_Sell2 = BigL_Line +(BigL_TrendLineBot - BigL_TrendLineMax )*LineRange*2
// plot mini trendlines (추세선그리기)
plot_BigH_LIne = plot(BigH_Line, color=color.new(color.maroon,0), style = plot.style_linebr, linewidth = 2, title = "Bull Trendline")
plot_BigL_LIne = plot(BigL_Line, color=color.new(color.olive,0), style = plot.style_linebr, linewidth = 2, title = "Bear Trendline")
plot(MidH_Line, color=color.new(color.red,0), style = plot.style_linebr, linewidth = 1, title = "Bull line")
plot(MidL_Line, color=color.new(color.green,0), style = plot.style_linebr, linewidth = 1, title = "Bear line")
// plot triangles (삼각수렴 그리기)
plotTriTop = plot(lineTop, color = color.new(color.green,60), title = "Triangle line Top")
plotTriMid = plot(lineMid, color = color.new(color.black,50), title = "Triangle line Middle")
plotTriBot = plot(lineBot, color = color.new(color.red,60), title = "Triangle line Bottom")
fill(plot_BigH_LIne,plotTriTop, color = color.new(color.green,70), title = "Triangle fill Top")
fill(plot_BigH_LIne,plotTriMid, color = color.new(color.green,90), title = "Triangle fill Top")
fill(plot_BigL_LIne,plotTriMid, color = color.new(color.red,90), title = "Triangle fill Bottom")
fill(plot_BigL_LIne,plotTriBot, color = color.new(color.red,70), title = "Triangle fill Bottom")
// plot parallel lines (평행선 그리기)
plot_TrendHMax = plot(BigH_TrendLineMax, color=color.new(color.maroon,50), style = plot.style_circles, linewidth = 1, title = "Bear parallel Max")
plot_TrendHTop = plot(BigH_TrendLineTop, color=color.new(color.maroon,85), style = plot.style_linebr, linewidth = 1, title = "Bear parallel Top")
plot_TrendHMid = plot(BigH_TrendLineMid, color=color.new(color.maroon,90), style = plot.style_linebr, linewidth = 1, title = "Bear parallel Mid")
plot_TrendHBot = plot(BigH_TrendLineBot, color=color.new(color.maroon,95), style = plot.style_linebr, linewidth = 1, title = "Bear parallel Bot")
fill(plot_TrendHMax,plot_TrendHMid, color = color.new(color.maroon,90), title = "Bear parallel lines")
plot_TrendLMax = plot(BigL_TrendLineMax, color=color.new(color.olive,50), style = plot.style_circles, linewidth = 1, title = "Bull parallel Max")
plot_TrendLTop = plot(BigL_TrendLineTop, color=color.new(color.olive,95), style = plot.style_linebr, linewidth = 1, title = "Bull parallel Top")
plot_TrendLMid = plot(BigL_TrendLineMid, color=color.new(color.olive,90), style = plot.style_linebr, linewidth = 1, title = "Bull parallel Mid")
plot_TrendLBot = plot(BigL_TrendLineBot, color=color.new(color.olive,85), style = plot.style_linebr, linewidth = 1, title = "Bull parallel Bot")
fill(plot_TrendLMax,plot_TrendLMid, color = color.new(color.olive,90), title = "Bull parallel lines")
// draw start point of parallel lines (평행선 작도선 그리기)
plot(BigHR1 ? low : BigH2 ? BigH_TrendLineMax : na, color=color.new(color.maroon,80), style=plot.style_line, linewidth=1, editable=false, title = "Bear parallel guideline")
plot(BigLR1 ? high : BigL2 ? BigL_TrendLineMax : na, color=color.new(color.olive,80), style=plot.style_line, linewidth=1, editable=false, title = "Bull parallel guideline")
// // plot price lines for trade (parallel lines) (평행선에 매수선 그리기)
plot(BigH_Line_Buy2, color=color.new(color.green,80), style = plot.style_linebr, linewidth = 2, title = "Bear Trendline Buy B2")
plot(BigH_Line_Buy1, color=color.new(color.green,90), style = plot.style_linebr, linewidth = 1, title = "Bear Trendline Buy B1")
plot(BigH_Line_Sell1, color=color.new(color.red,90), style = plot.style_linebr, linewidth = 1, title = "Bear Trendline Sell T1")
plot(BigH_Line_Sell2, color=color.new(color.red,80), style = plot.style_linebr, linewidth = 2, title = "Bear Trendline Sell T2")
plot(BigL_Line_Buy2, color=color.new(color.green,80), style = plot.style_linebr, linewidth = 2, title = "Bull Trendline Buy B2")
plot(BigL_Line_Buy1, color=color.new(color.green,90), style = plot.style_linebr, linewidth = 1, title = "Bull Trendline Buy B1")
plot(BigL_Line_Sell1, color=color.new(color.red,90), style = plot.style_linebr, linewidth = 1, title = "Bull Trendline Sell T1")
plot(BigL_Line_Sell2, color=color.new(color.red,80), style = plot.style_linebr, linewidth = 2, title = "Bull Trendline Sell T2")
// set trend
var trendline_trend = 0
if close > BigH_Line
trendline_trend := 1
else if close < BigL_Line
trendline_trend := -1
else
trendline_trend := 0
trendline_trend_color = trendline_trend > 0 ? color.new(color.green,80) : trendline_trend < 0 ? color.new(color.red,80) : na
bgcolor(trendline_trend_color , title = "Plot Trendline Trend")
// set trigger
trendline_longTr = false
trendline_longExitTr = false
trendline_shortTr = false
trendline_shortExitTr = false
//
if trendline_trend == 0
if ta.crossover(close, BigL_Line_Buy1) or ta.crossover(close, BigL_Line_Buy2)
trendline_longTr := true
if ta.crossunder(close, BigH_Line_Sell1) or ta.crossunder(close, BigH_Line_Sell2)
trendline_shortTr := true
if ta.crossunder(close, lineTop)
trendline_longExitTr := true
if ta.crossover(close,lineBot)
trendline_shortExitTr := true
if trendline_trend == -1
if ta.crossover(close, BigL_Line) or ta.crossover(close, BigL_Line_Sell1)
trendline_longTr := true
trendline_shortExitTr := true
if close < BigL_Line_Sell2
trendline_longExitTr := true
if trendline_trend == 1
if ta.crossunder(close, BigH_Line) or ta.crossunder(close, BigH_Line_Buy1)
trendline_shortTr := true
trendline_longExitTr := true
if close > BigH_Line_Buy2
trendline_shortExitTr := true
// Lets trade ----------------------------------------------------------------
check_long_mode = input.bool(true, title = "Long Mode On!")
check_short_mode = input.bool(false, title = "Short Mode On!")
if trendline_longTr
if check_long_mode
strategy.entry("L", strategy.long)
else if trendline_shortTr
if check_short_mode
strategy.entry("S", strategy.short)
if trendline_longExitTr
strategy.close("L")
else if trendline_shortExitTr
strategy.close("S")
|
Linear EDCA v1.2 | https://www.tradingview.com/script/xMtuW4V2/ | stephan8306 | https://www.tradingview.com/u/stephan8306/ | 118 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//
// © Stephan-Gao
//@version=5
strategy("Linear EDCA v1.2.3", overlay=true, default_qty_type = strategy.percent_of_equity,
default_qty_value = 1, initial_capital = 10000, currency = currency.USD, commission_type = strategy.commission.percent, commission_value = 0.2)
strategy.risk.allow_entry_in(strategy.direction.long)
// 单位定投比率
defInvestRatio = input.float(0.025, title = "default invest ratio", tooltip = "The default fixed investment ratio, the strategy will calculate the position ratio of a single fixed investment based on this ratio and a linear function. The default 0.025 represents 2.5% of the position")
// 最小单笔买卖头寸数量
minPositionSize = input.float(0.001, title = "min position size", minval = 0)
// 定买的线性函数斜率
buySlope = input.float(-35, title = "buy slope", maxval = 0, tooltip = "the slope of the linear function of the order to buy, used to control the position ratio of a single buy")
// 定卖的线性函数斜率
sellSlope = input.float(-0.7, title = "sell slope", maxval = 0, tooltip = "the slope of the linear function of the order to sell, used to control the position ratio of a single sell")
// 定卖的偏移度(如果是正数,则在均线以上一段距离还保持买入;如果是负数,则在偏离度为0时即开始卖出。一般对于牛市较长的市场,一般偏移为正数)
sellOffset = input.float(0.6, title = "sell offset", tooltip = "The offset of the order to sell. If it is greater than 0, it will keep a small buy within a certain range to avoid starting to sell too early")
// 最大卖出倍率(defInvestRatio * maxSellRate = 最大单次卖出仓位)
maxSellRate = input.float(5, title = "max sell rate", minval = 0, tooltip = "Controls the maximum sell multiple. The maximum ratio of a single sell position does not exceed defInvestRatio * maxSellRate")
// 最大买入倍率(defInvestRatio * maxBuyRate = 最大单次买入仓位)
maxBuyRate = input.float(6, title = "max buy rate", minval = 0, tooltip = "Controls the maximum buy multiple. The maximum ratio of a single buy position does not exceed defInvestRatio * maxBuyRate")
maPeriod = input(1100, "MA Period")
smoothing = input.string(defval="SMA", options=["EMA", "SMA"])
useDateFilter = input.bool(true, title="Filter Date Range of Backtest", group = "Backtest Date Range")
settleOnEnd = input.bool(false, title="settle account on end", group = "Backtest Date Range")
startDate = input.time(title="startDate", defval=timestamp("2013-11-30T00:00+00:00"), group = "Backtest Date Range")
endDate = input.time(title="endDate", defval=timestamp("2022-09-16T00:00+00:00"), group = "Backtest Date Range")
investDayofweek = input.int(2, title = "invest day of week", tooltip = "1 means Sunday, 2 means Monday, 7 means Saturday", minval = 1, maxval = 7, group = "Backtest Date Range")
intervalDays = input.int(14, title="interval days", group = "Backtest Date Range")
inTradeWindow = not useDateFilter or (time >= startDate and time < endDate)
var int investBarIndex = 0
isInvestDay() => timeframe.period == "D" and dayofweek == investDayofweek and bar_index >= (investBarIndex+intervalDays) and inTradeWindow
ma(smoothing, src, length) =>
if smoothing == "EMA"
ta.ema(src, length)
else
if smoothing == "SMA"
ta.sma(src, length)
calInvestRate(deviation) =>
float result = 0
if deviation >= 0
result := sellSlope * deviation + sellOffset
result := math.abs(result) > maxSellRate ? -maxSellRate : result
else
result := buySlope * deviation + 1
result := math.abs(result) > maxBuyRate ? maxBuyRate : result
result
// 当前仓位净值
positionValue() => strategy.position_size * close
// 当前可动用的本金
capitalValue() => strategy.equity - positionValue() > 0 ? strategy.equity - positionValue() : 0
// 目标单笔投资的数量(order qty)
orderQty(orderPercent) =>
float resultQty = 0
targetOrderValue = strategy.equity * math.abs(orderPercent)
if capitalValue() <= 0
resultQty := 0
else if capitalValue() > 0 and capitalValue() > targetOrderValue
resultQty := targetOrderValue / close
else if capitalValue() <= targetOrderValue
resultQty := capitalValue() / close
resultQty := math.round_to_mintick(resultQty)
if resultQty > 0
resultQty := resultQty < minPositionSize ? 0 : resultQty
closeOrderQty(orderPercent) =>
float resultQty = 0
targetCloseValue = strategy.equity * math.abs(orderPercent)
if positionValue() <= 0
resultQty := 0
else if positionValue() > 0 and positionValue() > targetCloseValue
resultQty := targetCloseValue / close
else if positionValue() <= targetCloseValue
resultQty := positionValue() / close
resultQty := math.round_to_mintick(resultQty)
if resultQty > 0
resultQty := resultQty < minPositionSize ? 0 : resultQty
//// Main ////
movingAverage = ma(smoothing, close, maPeriod)
plot(movingAverage, "MA", linewidth = 2, color = color.new(color.black, 0), display = display.all)
deviation = (close - movingAverage) / movingAverage
investRate = calInvestRate(deviation)
orderPercent = defInvestRatio * investRate
orderQty = orderQty(orderPercent)
plot(orderQty, "orderQty", display = display.data_window)
closeOrderQty = closeOrderQty(orderPercent)
plot(closeOrderQty, "closeOrderQty", display = display.data_window)
if isInvestDay()
if investRate > 0
if orderQty > 0
orderPer = orderQty * close / strategy.equity
strategy.order("Buy", strategy.long, qty = orderQty, comment = "Buy " + str.tostring(orderPer*100, "0.00") + "%")
investBarIndex := bar_index
else
if closeOrderQty > 0
closeOrderPer = closeOrderQty * close / strategy.equity
strategy.close("Buy", qty = closeOrderQty, comment = "Sell " + str.tostring(closeOrderPer*100, "0.00") + "%")
investBarIndex := bar_index
if settleOnEnd and not inTradeWindow and inTradeWindow[1]
strategy.cancel_all()
strategy.close_all(comment="Date Range Exit")
// for debug
ror = 100 * (close - strategy.position_avg_price)/strategy.position_avg_price
var float maxLoss = 0
if ror < 0 and maxLoss > ror
maxLoss := ror
var float maxGain = 0
if ror > 0 and maxGain < ror
maxGain := ror
plot(ror, "positionReturn%", color = color.new(color.red, 0), style = plot.style_columns, display = display.data_window)
plot(maxLoss, "positionMaxFloatLoss%", color = color.new(color.red, 0), style = plot.style_columns, display = display.data_window + display.status_line)
plot(maxGain, "positionMaxFloatGain%", color = color.new(color.green, 0), style = plot.style_columns, display = display.data_window + display.status_line)
plot(strategy.max_drawdown, "max_drawdown", color = color.new(color.blue, 60), style = plot.style_histogram, display = display.all)
plot(100 * deviation, "deviation%", display = display.data_window)
plot(investRate, "investRate", display = display.data_window)
plot(100*orderPercent, "orderPercent%", display = display.data_window)
plot(100*positionValue()/strategy.equity, "positionPercent%", color = color.new(color.red, 0), display = display.data_window)
plot(strategy.position_avg_price, "positionAvgPrice", linewidth = 1, color = color.new(color.green, 0), display = display.all)
plot(strategy.position_size, "strategy.position_size", display = display.data_window)
plot(strategy.equity, "strategy.equity", display = display.data_window)
plot(strategy.openprofit, "strategy.openprofit", display = display.data_window)
plot(strategy.netprofit, "strategy.netProfit", display = display.data_window)
plot(positionValue(), "positionValue()", display = display.data_window)
plot(capitalValue(), "capitalValue()", display = display.data_window)
|
Multi Trend Cross Strategy Template | https://www.tradingview.com/script/5SHl70y7-Multi-Trend-Cross-Strategy-Template/ | TradeAutomation | https://www.tradingview.com/u/TradeAutomation/ | 304 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @version=5
// Author = TradeAutomation
strategy(title="Multi Trend Cross Strategy Template", shorttitle="Multi Trend Cross Strategy", process_orders_on_close=true, overlay=true, commission_type=strategy.commission.cash_per_contract, commission_value=0.0035, initial_capital = 1000000, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
// Backtest Date Range Inputs //
StartTime = input.time(defval=timestamp('01 Jan 2000 05:00 +0000'), group="Date Range", title='Start Time')
EndTime = input.time(defval=timestamp('01 Jan 2099 00:00 +0000'), group="Date Range", title='End Time')
InDateRange = time>=StartTime and time<=EndTime
// Trend Selector //
TrendSelectorInput = input.string(title="Fast Trend Selector", defval="EMA", group="Core Settings", options=["ALMA", "DEMA", "DSMA", "EMA", "HMA", "JMA", "KAMA", "Linear Regression (LSMA)", "RMA", "SMA", "SMMA", "Price Source", "TEMA", "TMA", "VAMA", "VIDYA", "VMA", "VWMA", "WMA", "WWMA", "ZLEMA"], tooltip="Select your fast trend")
TrendSelectorInput2 = input.string(title="Slow Trend Selector", defval="EMA", group="Core Settings", options=["ALMA", "DEMA", "DSMA", "EMA", "HMA", "JMA", "KAMA", "Linear Regression (LSMA)", "RMA", "SMA", "SMMA", "Price Source", "TEMA", "TMA", "VAMA", "VIDYA", "VMA", "VWMA", "WMA", "WWMA", "ZLEMA"], tooltip="Select your slow trend")
src = input.source(close, "Price Source", group="Core Settings", tooltip="This is the price source being used for the trends to calculate based on")
length = input.int(10, "Fast Trend Length", group="Core Settings", step=5, tooltip="A long is entered when the selected fast trend crosses over the selected slow trend")
length2 = input.int(200, "Slow Trend Length", group="Core Settings", step=5, tooltip="A long is entered when the selected fast trend crosses over the selected slow trend")
LineWidth = input.int(1, "Line Width", group="Core Settings", tooltip="This is the width of the line plotted that represents the selected trend")
// Individual Moving Average / Regression Setting //
AlmaOffset = input.float(0.85, "ALMA Offset", group="Individual Trend Settings", tooltip="This only applies when ALMA is selected")
AlmaSigma = input.float(6, "ALMA Sigma", group="Individual Trend Settings", tooltip="This only applies when ALMA is selected")
ATRFactor = input.float(3, "ATR Multiplier For SuperTrend", group="Individual Trend Settings", tooltip="This only applies when SuperTrend is selected")
ATRLength = input.int(12, "ATR Length For SuperTrend", group="Individual Trend Settings", tooltip="This only applies when SuperTrend is selected")
ssfLength = input.int(20, "DSMA Super Smoother Filter Length", minval=1, tooltip="This only applies when EDSMA is selected", group="Individual Trend Settings")
ssfPoles = input.int(2, "DSMA Super Smoother Filter Poles", options=[2, 3], tooltip="This only applies when EDSMA is selected", group="Individual Trend Settings")
JMApower = input.int(2, "JMA Power Parameter", group="Individual Trend Settings", tooltip="This only applies when JMA is selected")
phase = input.int(-45, title="JMA Phase Parameter", step=10, minval=-110, maxval=110, group="Individual Trend Settings", tooltip="This only applies when JMA is selected")
KamaAlpha = input.float(3, "KAMA's Alpha", minval=1,step=0.5, group="Individual Trend Settings", tooltip="This only applies when KAMA is selected")
LinRegOffset = input.int(0, "Linear Regression Offset", group="Individual Trend Settings", tooltip="This only applies when Linear Regression is selected")
VAMALookback =input.int(12, "VAMA Volatility lookback", group="Individual Trend Settings", tooltip="This only applies when VAMA is selected")
// Trend Indicators With Library Functions //
ALMA = ta.alma(src, length, AlmaOffset, AlmaSigma)
EMA = ta.ema(src, length)
HMA = ta.hma(src, length)
LinReg = ta.linreg(src, length, LinRegOffset)
RMA = ta.rma(src, length)
SMA = ta.sma(src, length)
VWMA = ta.vwma(src, length)
WMA = ta.wma(src, length)
ALMA2 = ta.alma(src, length2, AlmaOffset, AlmaSigma)
EMA2 = ta.ema(src, length2)
HMA2 = ta.hma(src, length2)
LinReg2 = ta.linreg(src, length2, LinRegOffset)
RMA2 = ta.rma(src, length2)
SMA2 = ta.sma(src, length2)
VWMA2 = ta.vwma(src, length2)
WMA2 = ta.wma(src, length2)
// Additional Trend Indicators Built In And/Or Open Sourced //
//DEMA
de1 = ta.ema(src, length)
de2 = ta.ema(de1, length)
DEMA = 2 * de1 - de2
de3 = ta.ema(src, length2)
de4 = ta.ema(de3, length2)
DEMA2 = 2 * de3 - de4
// Ehlers Deviation-Scaled Moving Average - DSMA [Everget]
PI = 2 * math.asin(1)
get2PoleSSF(src, length) =>
arg = math.sqrt(2) * PI / length
a1 = math.exp(-arg)
b1 = 2 * a1 * math.cos(arg)
c2 = b1
c3 = -math.pow(a1, 2)
c1 = 1 - c2 - c3
var ssf = 0.0
ssf := c1 * src + c2 * nz(ssf[1]) + c3 * nz(ssf[2])
get3PoleSSF(src, length) =>
arg = PI / length
a1 = math.exp(-arg)
b1 = 2 * a1 * math.cos(1.738 * arg)
c1 = math.pow(a1, 2)
coef2 = b1 + c1
coef3 = -(c1 + b1 * c1)
coef4 = math.pow(c1, 2)
coef1 = 1 - coef2 - coef3 - coef4
var ssf = 0.0
ssf := coef1 * src + coef2 * nz(ssf[1]) + coef3 * nz(ssf[2]) + coef4 * nz(ssf[3])
zeros = src - nz(src[2])
avgZeros = (zeros + zeros[1]) / 2
// Ehlers Super Smoother Filter
ssf = ssfPoles == 2
? get2PoleSSF(avgZeros, ssfLength)
: get3PoleSSF(avgZeros, ssfLength)
// Rescale filter in terms of Standard Deviations
stdev = ta.stdev(ssf, length)
scaledFilter = stdev != 0
? ssf / stdev
: 0
alpha1 = 5 * math.abs(scaledFilter) / length
EDSMA = 0.0
EDSMA := alpha1 * src + (1 - alpha1) * nz(EDSMA[1])
get2PoleSSF2(src, length2) =>
arg = math.sqrt(2) * PI / length2
a1 = math.exp(-arg)
b1 = 2 * a1 * math.cos(arg)
c2 = b1
c3 = -math.pow(a1, 2)
c1 = 1 - c2 - c3
var ssf2 = 0.0
ssf2 := c1 * src + c2 * nz(ssf2[1]) + c3 * nz(ssf2[2])
get3PoleSSF2(src, length2) =>
arg = PI / length2
a1 = math.exp(-arg)
b1 = 2 * a1 * math.cos(1.738 * arg)
c1 = math.pow(a1, 2)
coef2 = b1 + c1
coef3 = -(c1 + b1 * c1)
coef4 = math.pow(c1, 2)
coef1 = 1 - coef2 - coef3 - coef4
var ssf2 = 0.0
ssf2 := coef1 * src + coef2 * nz(ssf2[1]) + coef3 * nz(ssf2[2]) + coef4 * nz(ssf2[3])
// Ehlers Super Smoother Filter
ssf2 = ssfPoles == 2
? get2PoleSSF2(avgZeros, ssfLength)
: get3PoleSSF2(avgZeros, ssfLength)
// Rescale filter in terms of Standard Deviations
stdev2 = ta.stdev(ssf2, length2)
scaledFilter2 = stdev2 != 0
? ssf2 / stdev2
: 0
alpha12 = 5 * math.abs(scaledFilter2) / length2
EDSMA2 = 0.0
EDSMA2 := alpha12 * src + (1 - alpha12) * nz(EDSMA2[1])
//JMA [Everget]
phaseRatio = phase < -100 ? 0.5 : phase > 100 ? 2.5 : phase / 100 + 1.5
beta = 0.45 * (length - 1) / (0.45 * (length - 1) + 2)
alpha = math.pow(beta, JMApower)
var JMA = 0.0
var e0 = 0.0
e0 := (1 - alpha) * src + alpha * nz(e0[1])
var e1 = 0.0
e1 := (src - e0) * (1 - beta) + beta * nz(e1[1])
var e2 = 0.0
e2 := (e0 + phaseRatio * e1 - nz(JMA[1])) * math.pow(1 - alpha, 2) + math.pow(alpha, 2) * nz(e2[1])
JMA := e2 + nz(JMA[1])
beta2 = 0.45 * (length2 - 1) / (0.45 * (length2 - 1) + 2)
alpha2 = math.pow(beta2, JMApower)
var JMA2 = 0.0
var e02 = 0.0
e02 := (1 - alpha2) * src + alpha2 * nz(e02[1])
var e12 = 0.0
e12 := (src - e02) * (1 - beta2) + beta2 * nz(e12[1])
var e22 = 0.0
e22 := (e02 + phaseRatio * e12 - nz(JMA2[1])) * math.pow(1 - alpha2, 2) + math.pow(alpha2, 2) * nz(e22[1])
JMA2 := e22 + nz(JMA2[1])
//KAMA [Everget]
var KAMA = 0.0
fastAlpha = 2.0 / (KamaAlpha + 1)
slowAlpha = 2.0 / 31
momentum = math.abs(ta.change(src, length))
volatility = math.sum(math.abs(ta.change(src)), length)
efficiencyRatio = volatility != 0 ? momentum / volatility : 0
smoothingConstant = math.pow((efficiencyRatio * (fastAlpha - slowAlpha)) + slowAlpha, 2)
KAMA := nz(KAMA[1], src) + smoothingConstant * (src - nz(KAMA[1], src))
var KAMA2 = 0.0
momentum2 = math.abs(ta.change(src, length2))
volatility2 = math.sum(math.abs(ta.change(src)), length2)
efficiencyRatio2 = volatility2 != 0 ? momentum2 / volatility2 : 0
smoothingConstant2 = math.pow((efficiencyRatio2 * (fastAlpha - slowAlpha)) + slowAlpha, 2)
KAMA2 := nz(KAMA2[1], src) + smoothingConstant2 * (src - nz(KAMA2[1], src))
//SMMA
var SMMA = 0.0
SMMA := na(SMMA[1]) ? ta.sma(src, length) : (SMMA[1] * (length - 1) + src) / length
var SMMA2 = 0.0
SMMA2 := na(SMMA2[1]) ? ta.sma(src, length2) : (SMMA2[1] * (length2 - 1) + src) / length2
//TEMA
t1 = ta.ema(src, length)
t2 = ta.ema(t1, length)
t3 = ta.ema(t2, length)
TEMA = 3 * (t1 - t2) + t3
t12 = ta.ema(src, length2)
t22 = ta.ema(t12, length2)
t32 = ta.ema(t22, length2)
TEMA2 = 3 * (t12 - t22) + t32
//TMA
TMA = ta.sma(ta.sma(src, math.ceil(length / 2)), math.floor(length / 2) + 1)
TMA2 = ta.sma(ta.sma(src, math.ceil(length2 / 2)), math.floor(length2 / 2) + 1)
//VAMA [Duyck]
mid=ta.ema(src,length)
dev=src-mid
vol_up=ta.highest(dev,VAMALookback)
vol_down=ta.lowest(dev,VAMALookback)
VAMA = mid+math.avg(vol_up,vol_down)
mid2=ta.ema(src,length2)
dev2=src-mid2
vol_up2=ta.highest(dev2,VAMALookback)
vol_down2=ta.lowest(dev2,VAMALookback)
VAMA2 = mid2+math.avg(vol_up2,vol_down2)
//VIDYA [KivancOzbilgic]
var VIDYA=0.0
VMAalpha=2/(length+1)
ud1=src>src[1] ? src-src[1] : 0
dd1=src<src[1] ? src[1]-src : 0
UD=math.sum(ud1,9)
DD=math.sum(dd1,9)
CMO=nz((UD-DD)/(UD+DD))
VIDYA := na(VIDYA[1]) ? ta.sma(src, length) : nz(VMAalpha*math.abs(CMO)*src)+(1-VMAalpha*math.abs(CMO))*nz(VIDYA[1])
var VIDYA2=0.0
VMAalpha2=2/(length2+1)
ud12=src>src[1] ? src-src[1] : 0
dd12=src<src[1] ? src[1]-src : 0
UD2=math.sum(ud12,9)
DD2=math.sum(dd12,9)
CMO2=nz((UD2-DD2)/(UD2+DD2))
VIDYA2 := na(VIDYA2[1]) ? ta.sma(src, length2) : nz(VMAalpha2*math.abs(CMO2)*src)+(1-VMAalpha2*math.abs(CMO2))*nz(VIDYA2[1])
//VMA [LazyBear]
sc = 1/length
pdm = math.max((src - src[1]), 0)
mdm = math.max((src[1] - src), 0)
var pdmS = 0.0
var mdmS = 0.0
pdmS := ((1 - sc)*nz(pdmS[1]) + sc*pdm)
mdmS := ((1 - sc)*nz(mdmS[1]) + sc*mdm)
s = pdmS + mdmS
pdi = pdmS/s
mdi = mdmS/s
var pdiS = 0.0
var mdiS = 0.0
pdiS := ((1 - sc)*nz(pdiS[1]) + sc*pdi)
mdiS := ((1 - sc)*nz(mdiS[1]) + sc*mdi)
d = math.abs(pdiS - mdiS)
s1 = pdiS + mdiS
var iS = 0.0
iS := ((1 - sc)*nz(iS[1]) + sc*d/s1)
hhv = ta.highest(iS, length)
llv = ta.lowest(iS, length)
d1 = hhv - llv
vi = (iS - llv)/d1
var VMA=0.0
VMA := na(VMA[1]) ? ta.sma(src, length) : sc*vi*src + (1 - sc*vi)*nz(VMA[1])
sc2 = 1/length2
pdm2 = math.max((src - src[1]), 0)
mdm2 = math.max((src[1] - src), 0)
var pdmS2 = 0.0
var mdmS2 = 0.0
pdmS2 := ((1 - sc2)*nz(pdmS2[1]) + sc2*pdm2)
mdmS2 := ((1 - sc2)*nz(mdmS2[1]) + sc2*mdm2)
s2 = pdmS2 + mdmS2
pdi2 = pdmS2/s2
mdi2 = mdmS2/s2
var pdiS2 = 0.0
var mdiS2 = 0.0
pdiS2 := ((1 - sc2)*nz(pdiS2[1]) + sc2*pdi2)
mdiS2 := ((1 - sc2)*nz(mdiS2[1]) + sc2*mdi2)
d2 = math.abs(pdiS2 - mdiS2)
s12 = pdiS2 + mdiS2
var iS2 = 0.0
iS2 := ((1 - sc2)*nz(iS2[1]) + sc2*d2/s12)
hhv2 = ta.highest(iS2, length)
llv2 = ta.lowest(iS2, length)
d12 = hhv2 - llv2
vi2 = (iS2 - llv2)/d12
var VMA2=0.0
VMA2 := na(VMA2[1]) ? ta.sma(src, length2) : sc2*vi2*src + (1 - sc2*vi2)*nz(VMA2[1])
//WWMA
var WWMA=0.0
WWMA := (1/length)*src + (1-(1/length))*nz(WWMA[1])
var WWMA2=0.0
WWMA2 := (1/length2)*src + (1-(1/length2))*nz(WWMA2[1])
//Zero Lag EMA [KivancOzbilgic]
EMA1a = ta.ema(src,length)
EMA2a = ta.ema(EMA1a,length)
Diff = EMA1a - EMA2a
ZLEMA = EMA1a + Diff
EMA12 = ta.ema(src,length2)
EMA22 = ta.ema(EMA12,length2)
Diff2 = EMA12 - EMA22
ZLEMA2 = EMA12 + Diff2
// Trend Mapping and Plotting //
FastTrend = TrendSelectorInput == "ALMA" ? ALMA : TrendSelectorInput == "DEMA" ? DEMA : TrendSelectorInput == "DSMA" ? EDSMA : TrendSelectorInput == "EMA" ? EMA : TrendSelectorInput == "HMA" ? HMA : TrendSelectorInput == "JMA" ? JMA : TrendSelectorInput == "KAMA" ? KAMA : TrendSelectorInput == "Linear Regression (LSMA)" ? LinReg : TrendSelectorInput == "RMA" ? RMA : TrendSelectorInput == "SMA" ? SMA : TrendSelectorInput == "SMMA" ? SMMA : TrendSelectorInput == "Price Source" ? src : TrendSelectorInput == "TEMA" ? TEMA : TrendSelectorInput == "TMA" ? TMA : TrendSelectorInput == "VAMA" ? VAMA : TrendSelectorInput == "VIDYA" ? VIDYA : TrendSelectorInput == "VMA" ? VMA : TrendSelectorInput == "VWMA" ? VWMA : TrendSelectorInput == "WMA" ? WMA : TrendSelectorInput == "WWMA" ? WWMA : TrendSelectorInput == "ZLEMA" ? ZLEMA : SMA
SlowTrend = TrendSelectorInput2 == "ALMA" ? ALMA2 : TrendSelectorInput2 == "DEMA" ? DEMA2 : TrendSelectorInput2 == "DSMA" ? EDSMA2 : TrendSelectorInput2 == "EMA" ? EMA2 : TrendSelectorInput2 == "HMA" ? HMA2 : TrendSelectorInput2 == "JMA" ? JMA2 : TrendSelectorInput2 == "KAMA" ? KAMA2 : TrendSelectorInput2 == "Linear Regression (LSMA)" ? LinReg2 : TrendSelectorInput2 == "RMA" ? RMA2 : TrendSelectorInput2 == "SMA" ? SMA2 : TrendSelectorInput2 == "SMMA" ? SMMA2 : TrendSelectorInput2 == "Price Source" ? src : TrendSelectorInput2 == "TEMA" ? TEMA2 : TrendSelectorInput2 == "TMA" ? TMA2 : TrendSelectorInput2 == "VAMA" ? VAMA2 : TrendSelectorInput2 == "VIDYA" ? VIDYA2 : TrendSelectorInput2 == "VMA" ? VMA2 : TrendSelectorInput2 == "VWMA" ? VWMA2 : TrendSelectorInput2 == "WMA" ? WMA2 : TrendSelectorInput2 == "WWMA" ? WWMA2 : TrendSelectorInput2 == "ZLEMA" ? ZLEMA2 : SMA2
plot(FastTrend, color=color.green, linewidth=LineWidth)
plot(SlowTrend, color=color.red, linewidth=LineWidth)
//Short & Long Options
Long = input.bool(true, "Model Long Trades", group="Core Settings")
Short = input.bool(false, "Model Short Trades", group="Core Settings")
// Entry & Exit Functions //
if (InDateRange and Long==true and FastTrend>SlowTrend)
strategy.entry("Long", strategy.long, alert_message="Long")
if (InDateRange and Long==true and FastTrend<SlowTrend)
strategy.close("Long", alert_message="Close Long")
if (InDateRange and Short==true and FastTrend<SlowTrend)
strategy.entry("Short", strategy.short, alert_message="Short")
if (InDateRange and Short==true and FastTrend>SlowTrend)
strategy.close("Short", alert_message="Cover Short")
if (not InDateRange)
strategy.close_all(alert_message="End of Date Range")
|
Volatility System | https://www.tradingview.com/script/3hhs0XbR/ | EduardoMattje | https://www.tradingview.com/u/EduardoMattje/ | 176 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © EduardoMattje
//@version=5
strategy("Volatility System", overlay=false, margin_long=0, margin_short=0, default_qty_type=strategy.percent_of_equity,
default_qty_value=100, process_orders_on_close=true, initial_capital=20000)
// Inputs
var averageLength = input.int(14, "Average length", 2)
var multiplier = input.float(2.0, "Multiplier", 0.0, step=0.1)
// Calculations
atr = ta.atr(averageLength) * multiplier
closingChange = ta.change(close, 1)
atrPenetration(int signal) =>
res = closingChange * signal > atr[1]
longCondition = atrPenetration(1)
shortCondition = atrPenetration(-1)
// Order calls
if (longCondition)
strategy.entry(strategy.direction.long, strategy.long)
if (shortCondition)
strategy.entry(strategy.direction.short, strategy.short)
// Visuals
plot(atr, "ATR", color.white, 2)
plot(math.abs(closingChange), "Absolute close change", color.red)
|
Sine Wave Theory | https://www.tradingview.com/script/kRGoqyRB-Sine-Wave-Theory/ | Gentleman-Goat | https://www.tradingview.com/u/Gentleman-Goat/ | 319 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Gentleman-Goat
//@version=5
strategy("Sine Wave Theory",overlay=false, precision = 2, initial_capital = 1000,shorttitle = "SINE_W_T")
var bar_change_wave_direction = input.int(defval=1,title="Starting Wave Direction",group="Bar Change")
bar_change_sine_wave_number = input.int(defval=28,title="Sine Wave #",group="Bar Change")
bar_change_sine_wave_res = input.timeframe(defval="D",title="Resolution",group="Bar Change")
bar_change_trade = input.bool(defval=true,title="Trade",group="Bar Change")
var volume_wave_direction = input.int(defval=1,title="Starting Wave Direction",group="Volume")
avg_volume_length = input.int(7,title="Lookback Length",group="Volume")
volume_sine_wave_number = input.int(defval=28,title="Sine Wave #",group="Volume")
volume_sine_wave_res = input.timeframe(defval="D",title="Resolution",group="Volume")
volume_trade = input.bool(defval=false,title="Trade",group="Volume")
var coin_flip_wave_direction = input.int(defval=1,title="Starting Wave Direction",group="Coin Flip")
coin_flip_sine_wave_number = input.int(defval=28,title="Sine Wave #",group="Coin Flip")
coin_flip_seed = input.int(defval=1,title="Seed #",group="Coin Flip")
coin_flip_trade = input.bool(defval=false,title="Trade",group="Coin Flip")
avg_volume = ta.sma(volume,avg_volume_length)
//Green or Red Candle
bar_color = close>open ? color.green : color.red
bar_color_time_adj = request.security(syminfo.tickerid, bar_change_sine_wave_res, bar_color)
//Above or Below Average
volume_state = (volume>avg_volume) ? color.blue : color.purple
volume_state_time_adj = request.security(syminfo.tickerid, volume_sine_wave_res, volume_state)
//Coinflip
coin_flip = math.random(0,100,coin_flip_seed)>=50 ? color.teal : color.yellow
var bar_change_wave_count = 0
var volume_wave_count = 0
var coin_flip_wave_count = 0
//Wave Counters
if(volume_state_time_adj[1] != volume_state_time_adj)
volume_wave_count := volume_wave_count + volume_wave_direction
if(bar_color_time_adj[1] != bar_color_time_adj)
bar_change_wave_count := bar_change_wave_count + bar_change_wave_direction
if(coin_flip[1] != coin_flip)
coin_flip_wave_count := coin_flip_wave_count + coin_flip_wave_direction
//Direction changers
if(math.abs(bar_change_wave_count) == bar_change_sine_wave_number and bar_color_time_adj[1] != bar_color_time_adj)
bar_change_wave_direction := bar_change_wave_direction * -1
if(math.abs(volume_wave_count) == volume_sine_wave_number and volume_state_time_adj[1] != volume_state_time_adj)
volume_wave_direction := volume_wave_direction * -1
if(math.abs(coin_flip_wave_count) == coin_flip_sine_wave_number and coin_flip[1] != coin_flip)
coin_flip_wave_direction := coin_flip_wave_direction * -1
//Entry positions
if(bar_change_wave_count==bar_change_sine_wave_number and bar_change_trade==true)
strategy.entry(id="short",direction=strategy.short)
if(bar_change_wave_count==bar_change_sine_wave_number*-1 and bar_change_trade==true)
strategy.entry(id="long",direction=strategy.long)
if(volume_wave_count==volume_sine_wave_number and volume_trade==true)
strategy.entry(id="short-volume",direction=strategy.short)
if(volume_wave_count==volume_sine_wave_number*-1 and volume_trade==true)
strategy.entry(id="long-volume",direction=strategy.long)
if(coin_flip_wave_count==coin_flip_sine_wave_number and coin_flip_trade==true)
strategy.entry(id="short-coinflip",direction=strategy.short)
if(coin_flip_wave_count==coin_flip_sine_wave_number*-1 and coin_flip_trade==true)
strategy.entry(id="long-coinflip",direction=strategy.long)
hline(0, title='Center', color=color.white, linestyle=hline.style_dashed, linewidth=1)
plot(bar_change_wave_count,title="Bar Change", color=bar_color, linewidth=2)
plot(volume_wave_count,title="Volume Average Change", color=volume_state, linewidth=2)
plot(coin_flip_wave_count,title="Coin Flip Change", color=coin_flip, linewidth=2)
|
Double Inside Bar & Trend Strategy - Kaspricci | https://www.tradingview.com/script/0Q7aNBdV/ | Kaspricci | https://www.tradingview.com/u/Kaspricci/ | 109 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Kaspricci
//@version=5
strategy(
title = "Double Inside Bar & Trend Strategy - Kaspricci",
shorttitle = "Double Inside Bar & Trend",
overlay=true,
initial_capital = 100000,
currency = currency.USD,
default_qty_type = strategy.percent_of_equity,
default_qty_value = 100,
calc_on_every_tick = true,
close_entries_rule = "ANY")
// ================================================ Entry Inputs ======================================================================
headlineEntry = "Entry Seettings"
maSource = input.source(defval = close, group = headlineEntry, title = "MA Source")
maType = input.string(defval = "HMA", group = headlineEntry, title = "MA Type", options = ["EMA", "HMA", "SMA", "SWMA", "VWMA", "WMA"])
maLength = input.int( defval = 45, minval = 1, group = headlineEntry, title = "HMA Length")
float ma = switch maType
"EMA" => ta.ema(maSource, maLength)
"HMA" => ta.hma(maSource, maLength)
"SMA" => ta.sma(maSource, maLength)
"SWMA" => ta.swma(maSource)
"VWMA" => ta.vwma(maSource, maLength)
"WMA" => ta.wma(maSource, maLength)
plot(ma, "Trend MA", color.purple)
// ================================================ Trade Inputs ======================================================================
headlineTrade = "Trade Seettings"
stopLossType = input.string(defval = "ATR", group = headlineTrade, title = "Stop Loss Type", options = ["ATR", "FIX"])
atrLength = input.int( defval = 50, minval = 1, group = headlineTrade, inline = "ATR", title = " ATR: Length ")
atrFactor = input.float( defval = 2.5, minval = 0, step = 0.05, group = headlineTrade, inline = "ATR", title = "Factor ", tooltip = "multiplier for ATR value")
takeProfitRatio = input.float( defval = 2.0, minval = 0, step = 0.05, group = headlineTrade, title = " TP Ration", tooltip = "Multiplier for Take Profit calculation")
fixStopLoss = input.float( defval = 10.0, minval = 0, step = 0.5, group = headlineTrade, inline = "FIX", title = " FIX: Stop Loss ") * 10 // need this in ticks
fixTakeProfit = input.float( defval = 20.0, minval = 0, step = 0.5, group = headlineTrade, inline = "FIX", title = "Take Profit", tooltip = "in pips") * 10 // need this in ticks
useRiskMagmt = input.bool( defval = true, group = headlineTrade, inline = "RM", title = "")
riskPercent = input.float( defval = 1.0, minval = 0., step = 0.5, group = headlineTrade, inline = "RM", title = "Risk in % ", tooltip = "This will overwrite quantity from startegy settings and calculate the trade size based on stop loss and risk percent") / 100
// ================================================ Filter Inputs =====================================================================
headlineFilter = "Filter Setings"
// date filter
filterDates = input.bool(defval = false, group = headlineFilter, title = "Filter trades by dates")
startDateTime = input.time(defval = timestamp("2022-01-01T00:00:00+0000"), group = headlineFilter, title = " Start Date & Time")
endDateTime = input.time(defval = timestamp("2099-12-31T23:59:00+0000"), group = headlineFilter, title = " End Date & Time ")
dateFilter = not filterDates or (time >= startDateTime and time <= endDateTime)
// session filter
filterSession = input.bool(title = "Filter trades by session", defval = false, group = headlineFilter)
session = input.session(title = " Session", defval = "0045-2245", group = headlineFilter)
sessionFilter = not filterSession or time(timeframe.period, session, timezone = "CET")
// ================================================ Trade Entries and Exits =====================================================================
// calculate stop loss
stopLoss = switch stopLossType
"ATR" => nz(math.round(ta.atr(atrLength) * atrFactor / syminfo.mintick, 0), 0)
"FIX" => fixStopLoss
// calculate take profit
takeProfit = switch stopLossType
"ATR" => math.round(stopLoss * takeProfitRatio, 0)
"FIX" => fixTakeProfit
doubleInsideBar = high[2] > high[1] and high[2] > high[0] and low[2] < low[1] and low[2] < low[0]
// highlight mother candel and inside bar candles
bgcolor(doubleInsideBar ? color.rgb(33, 149, 243, 80) : na)
bgcolor(doubleInsideBar ? color.rgb(33, 149, 243, 80) : na, offset = -1)
bgcolor(doubleInsideBar ? color.rgb(33, 149, 243, 80) : na, offset = -2)
var float buyStopPrice = na
var float sellStopPrice = na
if (strategy.opentrades == 0 and dateFilter and sessionFilter and doubleInsideBar and barstate.isconfirmed)
buyStopPrice := high[0] // high of recent candle (second inside bar)
sellStopPrice := low[0] // low of recent candle (second inside bar)
tradeID = str.tostring(strategy.closedtrades + strategy.opentrades + 1)
quantity = useRiskMagmt ? math.round(strategy.equity * riskPercent / stopLoss, 2) / syminfo.mintick : na
commentTemplate = "{0} QTY: {1,number,#.##} SL: {2} TP: {3}"
if (close > ma)
longComment = str.format(commentTemplate, tradeID + "L", quantity, stopLoss / 10, takeProfit / 10)
strategy.entry(tradeID + "L", strategy.long, qty = quantity, stop = buyStopPrice, comment = longComment)
strategy.exit(tradeID + "SL", tradeID + "L", profit = takeProfit, loss = stopLoss, comment_loss = "SL", comment_profit = "TP")
if (close < ma)
shortComment = str.format(commentTemplate, tradeID + "S", quantity, stopLoss / 10, takeProfit / 10)
strategy.entry(tradeID + "S", strategy.short, qty = quantity, stop = sellStopPrice, comment = shortComment)
strategy.exit(tradeID + "SL", tradeID + "S", profit = takeProfit, loss = stopLoss, comment_loss = "SL", comment_profit = "TP")
// as soon as the first pending order has been entered the remaing pending order shall be cancelled
if strategy.opentrades > 0
currentTradeID = str.tostring(strategy.closedtrades + strategy.opentrades)
strategy.cancel(currentTradeID + "S")
strategy.cancel(currentTradeID + "L")
|
Altered OBV On MACD | https://www.tradingview.com/script/Hj9zfkcD-Altered-OBV-On-MACD/ | stocktechbot | https://www.tradingview.com/u/stocktechbot/ | 133 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © stocktechbot
//@version=5
strategy("Altered OBV On MACD", overlay=true, margin_long=100, margin_short=100)
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © stocktechbot
//@version=5
//SMA Tredline
out = ta.sma(close, 200)
outf = ta.sma(close, 50)
outn = ta.sma(close, 90)
outt = ta.sma(close, 21)
outthree = ta.sma(close, 9)
//sma plot
offset = input.int(title="Offset", defval=0, minval=-500, maxval=500)
plot(out, color=color.blue, title="MA200", offset=offset)
plot(outf, color=color.maroon, title="MA50", offset=offset)
plot(outn, color=color.orange, title="MA90", offset=offset)
plot(outt, color=color.olive, title="MA21", offset=offset)
plot(outthree, color=color.fuchsia, title="MA9", offset=offset)
fast_length = input(title="Fast Length", defval=12)
slow_length = input(title="Slow Length", defval=26)
chng = 0
obv = ta.cum(math.sign(ta.change(close)) * volume)
if close < close[1] and (open < close)
chng := 1
else if close > close[1]
chng := 1
else
chng := -1
obvalt = ta.cum(math.sign(chng) * volume)
//src = input(title="Source", defval=close)
src = obvalt
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9)
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"])
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"])
// Calculating
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal
//hline(0, "Zero Line", color=color.new(#787B86, 50))
//plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)))
//plot(macd, title="MACD", color=col_macd)
//plot(signal, title="Signal", color=col_signal)
[macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9)
//BUY Signal
mafentry =ta.sma(close, 50) > ta.sma(close, 90)
//matentry = ta.sma(close, 21) > ta.sma(close, 50)
matwohun = close > ta.sma(close, 200)
twohunraise = ta.rising(out, 2)
twentyrise = ta.rising(outt, 2)
macdrise = ta.rising(macd,2)
macdlong = ta.crossover(macd, signal)
longCondition=false
if macdlong and macdrise
longCondition := true
if (longCondition)
strategy.entry("My Long Entry Id", strategy.long)
//Sell Signal
mafexit =ta.sma(close, 50) < ta.sma(close, 90)
matexit = ta.sma(close, 21) < ta.sma(close, 50)
matwohund = close < ta.sma(close, 200)
twohunfall = ta.falling(out, 3)
twentyfall = ta.falling(outt, 2)
shortmafall = ta.falling(outthree, 1)
macdfall = ta.falling(macd,1)
macdsell = macd < signal
shortCondition = false
if macdfall and macdsell and (macdLine < signalLine) and ta.falling(low,2)
shortCondition := true
if (shortCondition)
strategy.entry("My Short Entry Id", strategy.short)
|
Catching the Bottom (by Coinrule) | https://www.tradingview.com/script/ckVsOuxq-Catching-the-Bottom-by-Coinrule/ | Coinrule | https://www.tradingview.com/u/Coinrule/ | 318 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Coinrule
//@version=5
strategy("V3 - Catching the Bottom",
overlay=true,
initial_capital=1000,
process_orders_on_close=true,
default_qty_type=strategy.percent_of_equity,
default_qty_value=30,
commission_type=strategy.commission.percent,
commission_value=0.1)
showDate = input(defval=true, title='Show Date Range')
timePeriod = time >= timestamp(syminfo.timezone, 2022, 4, 1, 0, 0)
notInTrade = strategy.position_size <= 0
//==================================Buy Conditions============================================
//RSI
length = input(14)
vrsi = ta.rsi(close, length)
buyCondition1 = vrsi < 40
//RSI decrease
decrease = 3
buyCondition2 = (vrsi < vrsi[1] - decrease)
//sellCondition1 = request.security(syminfo.tickerid, "15", buyCondition2)
//EMAs
fastEMA = ta.sma(close, 50)
slowEMA = ta.sma(close, 100)
buyCondition3 = ta.crossunder(fastEMA, slowEMA)
//buyCondition2 = request.security(syminfo.tickerid, "15", buyCondition3)
if(buyCondition1 and buyCondition2 and buyCondition3 and timePeriod)
strategy.entry(id='Long', direction = strategy.long)
//==================================Sell Conditions============================================
sellCondition1 = vrsi > 65
EMA9 = ta.sma(close, 9)
EMA50 = ta.sma(close, 50)
sellCondition2 = ta.crossover(EMA9, EMA50)
if(sellCondition1 and sellCondition2 and timePeriod)
strategy.close(id='Long')
//Best on: ETH 5mins (7.59%), BNB 5mins (5.42%), MATIC 30mins (15.61%), XRP 45mins (10.14%) ---> EMA
//Best on: MATIC 2h (16.09%), XRP 15m (5.25%), SOL 15m (4.28%), AVAX 5m (3.19%)
|
Subsets and Splits