Merge

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

//@version=5

indicator("Renko Emulation with Trend Magic", overlay=true, format=format.price, precision=2)

// Inputs for Renko Emulation

brickSize = input.float(50.0, title="Brick Size", minval=0.01, step=0.1)

// Renko Calculation

var float renkoLevel = na

var bool brickDirection = true // true = up, false = down

if na(renkoLevel)

renkoLevel := close

brickUp = renkoLevel + brickSize

brickDown = renkoLevel - brickSize

if close >= brickUp

renkoLevel := renkoLevel + brickSize

brickDirection := true

else if close <= brickDown


renkoLevel := renkoLevel - brickSize

brickDirection := false

// Line Plot with Color Based on Close

renkoLineColor = close > renkoLevel ? color.green : color.red

plot(renkoLevel, color=renkoLineColor, linewidth=2, title="Renko Line")

// Inputs for Trend Magic

period = input.int(20, title="CCI Period")

coeff = input.float(1.0, title="ATR Multiplier")

AP = input.int(5, title="ATR Period")

src = input.source(close, title="Source")

// Trend Magic Calculation

ATR = ta.sma(ta.tr, AP)

upT = low - ATR * coeff

downT = high + ATR * coeff

var float MagicTrend = na

MagicTrend := ta.cci(src, period) >= 0 ? (upT < nz(MagicTrend[1]) ? nz(MagicTrend[1]) : upT) : (downT > nz(MagicTrend[1]) ? nz(MagicTrend[1]) : downT)
trendColor = ta.cci(src, period) >= 0 ? #0022FC : #FC0400

plot(MagicTrend, color=trendColor, linewidth=3, title="Magic Trend")

// Alerts

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!")

//@version=5
strategy('Strategy tester', overlay=true, initial_capital=1000000, default_qty_type=strategy.percent_of_equity)

// Input parameters
atrLength = input(14, title='ATR Length') // ATR calculation length
atrMultiplierTP = input(10, title='ATR Multiplier (Take Profit)') // Take Profit multiplier
atrMultiplierSL = input(50, title='ATR Multiplier (Stop Loss)') // Stop Loss multiplier

// Calculate ATR
atrValue = ta.atr(atrLength)

// Variables to store entry prices


var float longEntryPrice = na
var float shortEntryPrice = na

// Calculate Take Profit and Stop Loss levels


var float longTakeProfit = na
var float longStopLoss = na
var float shortTakeProfit = na
var float shortStopLoss = na
var float lastHigh = na
var float lastLow = na

length = 5
highestHigh = ta.highest(high, length)
lowestLow = ta.lowest(low, length)
length2 = 5
stopLossLow = ta.lowest(low, length)
stoplossHigh = ta.highest(high, length)

// Get user input


res = input.timeframe(title="EMA Timeframe", defval="30")
len1 = input.int(title="EMA Length", defval=28)
col = input.bool(title="Color EMA", defval=true)
smooth = input.bool(title="Smooth", defval=false)

// Calculate EMA
ema = ta.ema(close, len1)
emaStep = request.security(syminfo.tickerid, res, ema[barstate.isrealtime ? 1 : 0])[barstate.isrealtime ? 0 : 1]
emaSmooth = request.security(syminfo.tickerid, res, ema[barstate.isrealtime ? 1 : 0], gaps=barmerge.gaps_on)[barstate.isrealtime ? 0 :
1]

// Draw EMA
plot(smooth ? emaSmooth : emaStep, color=col ? (close > emaStep ? color.green : color.red) : color.black, linewidth=2, title="HTF EMA")

var float long_tsl = 0

// banker

// ____ __ ___ ________ ___________ ___________ __ ____ ___


// / __ )/ / / | / ___/ /// ___/ |/ _< / // / / __ |_ \
// / __ / / / /| |/ / / ,< / / / /| | / / / / // /_/ / / __/ /
// / // / // ___ / // /| / // ___ |/ / / /__ _/ // / __/
// //// |\// |\// |// // // \/_/

// USER INPUTS --------------------------------------------------------------------------------------------------------{


//@variable: period to use in calculations
int period = input.int(17, minval = 17, inline = "m")
//@variable: width of main line
int width = input.int(2, "Width", [1, 2], inline = "m")
//@variable: mode for trend detection ("Normal" or "Sensitive ")
string mode = input.string("Normal", "Mode:", ["Normal", "Sensitive "])
//@variable: whether to show volatility bands on the chart
bool show_bnd = input.bool(true, "Volatility Bands")
//@variable: whether to show price deviation on the chart
bool show_dev = input.bool(false, "Price Deviation")
//@variable: whether to show regular mean reversion signals
bool show_ws = input.bool(false, "Mean Reversion")
//@variable: whether to show strong mean reversion signals
bool show_ss = input.bool(false, "Strong Mean Reversion")

//@variable: colors for trend direction (up and down)


color up1 = input.color(#12fa8a, group = "Color", inline = "c")
color dn1 = input.color(#1693f8, group = "Color", inline = "c")
//}

// CALCULATION --------------------------------------------------------------------------------------------------------{
//@variable: HMA of hl2 (high+low)/2 as the source of trend analysis
series float src1 = ta.hma(hl2, 25)
//@variable: simple moving average of high-low as a volatility measure
series float vlt = ta.sma(high - low, 100)
//@variable: array to store the moving average values over the period
var AVG = array.new<float>(period, float(na))

// Condition to update the AVG array based on the selected mode


if mode == "Normal"
? bar_index == 122
: bar_index % period == 0
AVG.push(close) // Add the close price to the AVG array

// Update AVG array based on the period and price comparison


if bar_index % period == 0
if close > AVG.last() // If the current close is greater than the last stored value in AVG
AVG.push(low - vlt) // Add the low price minus volatility to the array

if close < AVG.last() // If the current close is lower than the last stored value in AVG
AVG.push(high + vlt) // Add the high price plus volatility to the array

//@variable: average of the last 10 values in AVG


series float avg = math.sum(AVG.last(), 10) / 10

//@variable: upper and lower volatility bands


series float upper = avg + vlt
series float lower = avg - vlt

//@variable: trend color based on the relationship between the source and the average
color trend_color = src1 > avg
? (avg == avg[1] or avg < avg[1] ? color.new(up1, 40) : up1)
: (avg == avg[1] or avg > avg[1] ? color.new(dn1, 40) : dn1)

//@variable: alternate trend color based on the source vs. average


color trend_color1 = src1 > avg ? up1 : dn1
//@variable: oscillator showing the difference between the source and the average
series float osc = src1 - avg
//@variable: normalized oscillator using standard deviation
series float osc1 = (osc - 0) / ta.stdev(osc, 50)
//}

// PLOTTING -----------------------------------------------------------------------------------------------------------{

// Plotting the moving average with trend color

// Plotting the lower and upper volatility bands

// Plotting the oscillator if show_dev is enabled

// Plotting mean reversion up signals

// Plotting mean reversion down signals

// Plotting strong mean reversion up signals

// Displaying a final label indicating the trend direction if not showing deviation
if barstate.islast and not show_dev
label.delete(label.new(bar_index + 5, 0,
close > avg ? "Trend Up" : "Trend Down",
style = label.style_label_left,
color = color(na),
textcolor = chart.fg_color)[1]
)

// signals
//}
//functions
xrf(values, length) =>
r_val = float(na)
if length >= 1
for i = 0 to length by 1
if na(r_val) or not na(values[i])
r_val := values[i]
r_val
r_val

xsa(src,len,wei) =>
sumf = 0.0
ma = 0.0
out = 0.0
sumf := nz(sumf[1]) - nz(src[len]) + src
ma := na(src[len]) ? na : sumf/len
out := na(out[1]) ? ma : (src*wei+out[1]*(len-wei))/len
out

//set up a simple model of banker fund flow trend


fundtrend = ((3*xsa((close- ta.lowest(low,27))/(ta.highest(high,27)-ta.lowest(low,27))*100,5,1)-2*xsa(xsa((close-
ta.lowest(low,27))/(ta.highest(high,27)-ta.lowest(low,27))*100,5,1),3,1)-50)*1.032+50)
//define typical price for banker fund
typ = (2*close+high+low+open)/5
//lowest low with mid term fib # 34
lol = ta.lowest(low,34)
//highest high with mid term fib # 34
hoh = ta.highest(high,34)
//define banker fund flow bull bear line
bullbearline = ta.ema((typ-lol)/(hoh-lol)*100,13)
//define banker entry signal
bankerentry = ta.crossover(fundtrend,bullbearline) and bullbearline<25
//overbought and oversold threshold lines
// Input parameters
long_stop_loss_percent = input.float(1.0, title="Stop Loss %", step=0.1) / 100
equity_gain_percent = input.float(1.0, title="Equity Gain % to Breakeven", step=0.1) / 100

// Simulate trade entry price


// Calculate 1% move in favor

source = input(defval=close, title='Source')

// Smooth Average Range

per1 = input.int(defval=27, minval=1, title='Fast period')


mult1 = input.float(defval=2.6, minval=0.1, title='Fast range')

per2 = input.int(defval=55, minval=1, title='Slow period')


mult2 = input.float(defval=2, minval=0.1, title='Slow range')

smoothrng(x, t, m) =>
wper = t * 2 - 1
avrng = ta.ema(math.abs(x - x[1]), t)
smoothrng = ta.ema(avrng, wper) * m
smoothrng
smrng1 = smoothrng(source, per1, mult1)
smrng2 = smoothrng(source, per2, mult2)
smrng = (smrng1 + smrng2) / 2

// Range Filter

rngfilt(x, r) =>
rngfilt = x
rngfilt := x > nz(rngfilt[1]) ? x - r < nz(rngfilt[1]) ? nz(rngfilt[1]) : x - r : x + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : x + r
rngfilt
filt = rngfilt(source, smrng)

upward = 0.0
upward := filt > filt[1] ? nz(upward[1]) + 1 : filt < filt[1] ? 0 : nz(upward[1])
downward = 0.0
downward := filt < filt[1] ? nz(downward[1]) + 1 : filt > filt[1] ? 0 : nz(downward[1])

hband = filt + smrng


lband = filt - smrng

longCond = bool(na)
shortCond = bool(na)
longCond := source > filt and source > source[1] and upward > 0 or source > filt and source < source[1] and upward > 0
shortCond := source < filt and source < source[1] and downward > 0 or source < filt and source > source[1] and downward > 0

CondIni = 0
CondIni := longCond ? 1 : shortCond ? -1 : CondIni[1]

long = longCond and CondIni[1] == -1


short = shortCond and CondIni[1] == 1

// Plotting

//banker fund Weak rebound with blue candle

if ta.crossover(fundtrend, bullbearline) and fundtrend < 35 and close > emaStep


longEntryPrice := close
longTakeProfit := longEntryPrice + atrValue*atrMultiplierTP
longStopLoss := longEntryPrice - atrValue * atrMultiplierSL
strategy.entry("long", strategy.long, qty=25)
long_tsl := longEntryPrice - (atrValue*atrMultiplierSL)
strategy.exit("long",stop=longStopLoss, comment_loss="stoploss long")

if ta.crossunder(fundtrend,bullbearline) and fundtrend > 65 and close < emaStep


shortEntryPrice := close
shortTakeProfit := shortEntryPrice - atrValue*atrMultiplierTP
shortStopLoss := shortEntryPrice + atrValue * atrMultiplierSL
strategy.entry("short", strategy.short, qty=25)
strategy.exit("short", stop=shortStopLoss, comment_loss="stoploss short")

if ta.crossunder(fundtrend, 90)
strategy.close("long")

if ta.crossover(fundtrend, 10)
strategy.close("short")

target_price = longEntryPrice + atrValue

// Stop-loss level
var float stop_loss_price = na
if not na(longEntryPrice) and strategy.position_size > 0
// Initial stop-loss at a % below the entry price
// Move stop-loss to breakeven once 1% equity gain is reached
if close >= target_price
stop_loss_price := longEntryPrice
//strategy.exit("long", stop= stop_loss_price, comment_loss="lost stop long")

if not na(shortEntryPrice) and strategy.position_size < 0


if close <= shortEntryPrice - atrValue
stop_loss_price := shortEntryPrice
//strategy.exit("short", stop=stop_loss_price,comment_loss="lost stop short")

// Condition to check if loss exceeds 1% of initial capit

// shortEntryPrice := close
// stop_loss_in_ticks = (atrValue*atrMultiplierSL) / syminfo.mintick
// if stoplossHigh > high[1]
// stop_loss_in_ticks = (stoplossHigh - close) /syminfo.mintick

//take_profit_in_ticks = (atrValue*atrMultiplierTP)/syminfo.mintick
//strategy.order("short", strategy.short, qty=strategy.initial_capital * 0.01)
//strategy.exit("short", loss = stop_loss_in_ticks, comment_loss = "stoploss", profit = take_profit_in_ticks, comment_profit =
"takeprofit")

// Parameters
// Number of candles to look back

// Calculate the highest high of the last 30 candles

// strategy.order("short", strategy.short, 1.0)


// shortStopLoss := close + (atrValue * atrMultiplierSL)
// strategy.exit("short", stop=shortStopLoss)

// strategy.entry("short", strategy.short, 1.0)


// shortEntryPrice := close
// shortStopLoss := close + (atrValue * atrMultiplierSL)
// strategy.exit("short", stop = shortStopLoss)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy