3
s7s
typescript
9 months ago
11 kB
19
Indexable
//@version=6
strategy("IU Martingale Strategy", overlay=true, initial_capital = 100000, margin_long = 0, margin_short = 0)
// User Settings / Inputs :-{
pos_ = input.int (1 , "Starting Position = ")
profit_value = input.float(1000 , "Profit Points = ")
loss_value = input.float(1000 , "Loss Points = ")
show_table = input.bool (true , "Show Risk Matric Table")
// -- }
// ---- Variables :-{
var qty = pos_size
var loss_array = array.new<int>()
var int loosing_streak = 0
var int max_qty = 0
var float max_loss = 0.00
// -- }
// martingale calculations :-{
if strategy.wintrades > strategy.wintrades[1]
qty := pos_size
loss_array.clear()
if strategy.losstrades > strategy.losstrades[1]
qty := qty * 2
loss_array.push(qty)
// -- }
// ---- Risk Matrics :-{
if loss_array.size() > 0
if loss_array.size() >= loosing_streak
loosing_streak := loss_array.size()
max_qty := loss_array.last()
max_loss := max_qty * loss_value
// -- }
// ---- Going Long :-{
long_cond = close > open and strategy.position_size == 0
if long_cond and strategy.position_size == 0
strategy.entry("long", strategy.long, comment = "Long Entry", qty = qty)
// -- }
// Long SL and TP :-{
var float long_SL = na
var float long_TP = na
if strategy.position_size > 0
long_SL := strategy.position_avg_price - loss_value
long_TP := strategy.position_avg_price + profit_value
strategy.exit("long", "long", limit = long_TP, stop = long_SL)
// ---- Plotting long and short :-{
// ---- SL,TP
// ---- for long positions :-{
long_SL_plot = plot(strategy.position_size[1] > 0 ? long_SL : na , 'Long SL', color.red , style = plot.style_linebr)
long_TP_plot = plot(strategy.position_size[1] > 0 ? long_TP[1] : na, 'Long TP', color.green, style = plot.style_linebr)
// -- }
// ---- Filling stop loss
// ---- and take profits :-{
entry_plot = plot(strategy.position_size[1] != 0 ? strategy.position_avg_price[1] : na,
color = color.new(color.silver, 20), style = plot.style_linebr)
// -- }
// ---- for long :-{
fill(entry_plot, long_SL_plot , color =color.new(color.red, 85) , title = 'Long SL plot')
fill(entry_plot, long_TP_plot , color = color.new(color.green, 85), title = 'Long TP plot')
// -- }
// ---- Table part :-{
if barstate.islastconfirmedhistory and show_table
var my_table = table.new(position.top_right,5,5,bgcolor = na, frame_width = 3,frame_color = color.new(color.purple, 20), border_color =na, border_width = 3)
title = "<<<< Risk Matrics >>>>"
my_table.cell(0, 0, title, text_color = color.red, bgcolor = na )
my_table.cell(1, 0, "", text_color = color.red, bgcolor = na )
my_table.merge_cells(0, 0,1,1)
-------- texts ---------- \\
loosing_streak_string = str.tostring(loosing_streak) + " '📉'"
max_qty_sring = str.tostring(max_qty) + " 📦"
max_loss_string = str.tostring(max_loss) + " 🪙"
-------- column 1 -------- \\
my_table.cell(0, 2, "Loosing Streak = ", text_color = color.white, bgcolor = na )
my_table.cell(0, 3, "Max Quantity = ", text_color = color.white, bgcolor = na )
my_table.cell(0, 4, "Max Risk = ", text_color = color.white, bgcolor = na )
-------- column 2 -------- \\
my_table.cell(1, 2, loosing_streak_string, text_color = color.white, bgcolor = na)
my_table.cell(1, 3, max_qty_sring , text_color = color.white, bgcolor = na)
my_table.cell(1, 4, max_loss_string , text_color = color.white, bgcolor = na)
// -- }
//@version=6
strategy('Up/Down Vol strategy', overlay = true)
// User Input :-{
RTR = input.float(2.00, 'RTR 1:?')
lowerTimeframeTooltip = 'The indicator scans lower timeframe data to approximate Up/Down volume.' +
'By default, the timeframe is chosen automatically. These inputs override this with a custom timeframe.' +
' \n\nHigher timeframes provide more historical data, but the data will be less precise.'
useCustomTimeframeInput = input.bool(false, 'Use custom timeframe', tooltip = lowerTimeframeTooltip)
lowerTimeframeInput = input.timeframe('1', 'Timeframe')
// -- }
// indicator calculation :-{
upAndDownVolume() =>
posVol = 0.0
negVol = 0.0
switch
close > open =>
posVol := posVol + volume
posVol
close < open =>
negVol := negVol - volume
negVol
close >= close[1] =>
posVol := posVol + volume
posVol
close < close[1] =>
negVol := negVol - volume
negVol
[posVol, negVol]
lowerTimeframe = switch
useCustomTimeframeInput => lowerTimeframeInput
timeframe.isseconds => '1S'
timeframe.isintraday => '1'
timeframe.isdaily => '5'
=> '60'
[upVolumeArray, downVolumeArray] = request.security_lower_tf(syminfo.tickerid, lowerTimeframe, upAndDownVolume())
upVolume = array.sum(upVolumeArray) +
downVolume = array.sum(downVolumeArray) -
delta = upVolume + downVolume
var cumVol = 0.
cumVol := cumVol + nz(volume) 0
if barstate.islastconfirmedhistory and cumVol == 0
runtime.error('The data vendor doesn\'t provide volume data for this symbol.')
// -- }
// Entry exit conditions :-{
long = upVolume > 1.5 * -1 * downVolume
long_insider = long and long[1] and long[2]
atr = ta.atr(14)
// ------ long entry :-{
if long_insider and strategy.position_size == 0
strategy.entry('long', strategy.long, comment = 'long Entry')
// -- }
// ---- Stop Loss and Take Profit :-{
// ---- long and short SL :-{
long_SL = ta.valuewhen(strategy.position_size > 0 and strategy.position_size[1] == 0 , low[1] - atr, 0)
// -- }
// ----- long and short TP :-{
long_TP = (strategy.position_avg_price - long_SL) * RTR + strategy.position_avg_price
// -- }
// Stting long and short SL / TP :-{
if strategy.position_size > 0
strategy.exit("long", "long", stop = long_SL, limit = long_TP, comment = "Long Exit")
// -- }
// plotting long and short SL/TP :-{
//-------- long and short SL/TP :-{
long_SL_plot = plot(strategy.position_size[1] > 0 ? long_SL : na, 'Long SL' , color.red , style = plot.style_linebr)
long_TP_plot = plot(strategy.position_size[1] > 0 ? long_TP[1] : na, 'Long TP' , color.green, style = plot.style_linebr)
// -- }
// ---- Filling stop loss and take profits :-{
entry_plot = plot(strategy.position_size[1] != 0 ? strategy.position_avg_price[1]: na, color = color.new(color.blue, 50)
, style = plot.style_linebr)
// -- }
// -- for long :-{
fill(entry_plot,long_SL_plot ,long_SL , strategy.position_avg_price[1], top_color = color.new(#FF2400, 50), bottom_color = color(na))
fill(entry_plot, long_TP_plot , long_TP[1], strategy.position_avg_price[1], bottom_color = color(na), top_color = color.new(#03C03C, 50))
// -- }
// -- }
// -- :- {
// -- }
// Declaring empty matrix
var ohlc = matrix.new<float><string>()
//
if barstate.isconfirmed
if ohlc.rows() == lookback
ohlc.add_row(0,array.from(open, high,low,close))
ohlc.remove_row(ohlc.rows() - 1)
else
for i = 0 to (lookback - 1)
ohlc.add_row(array_id=array.from(open[i], high[i], low[i], close[i]))
count = 0
for row in ohlc
if row.get(3) >= row.get(0)
count += 1
log.info("\n{0} green bar(s)", count)
for i = 0 to (lookback - 1)
log.info("\nRow at {0} : {1}\n", i, ohlc.row(i))
// --
// ----
//@version=5
indicator('Nadaraya-Watson: Rational Quadratic Kernel (Non-Repainting)', overlay=true,timeframe="")
// Settings :-{
src = input.source(close, 'Source')
// ---- 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')
h = input.float(8.0,'Lookback Window',minval=3.)
// ---- 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')
r = input.float(8.,'Relative Weighting', step=0.25)
// ---- tooltip
// Bar index on which to start regression. The first bars of a chart are often highly volatile, and omission of these initial bars often leads to a better overall fit. Recommended range: 5-25')
x_0 = input.int(25, "Start Regression at Bar",
// ---- tooltip
// ---- Uses a crossover based mechanism to determine colors. This often results in less color transitions overall.",
smoothColors= input.bool(false, "Smooth Colors", inline='1', group='Colors' )
// ---- tooltip
// ---- Lag for crossover detection. Lower values result in earlier crossovers. Recommended range: 1-2",
lag= input.int(2, "Lag", inline='1', group='Colors')
size=array.size(array.from(src))
//
// size of the data series
// -- }
// Further Reading : :-{
// The Kernel Cookbook :
// Advice on Covariance
// functions
// David Duvenaud Published June 2014.
// Estimation of the bandwidth parameter in Nadaraya-Watson kernel non-parametric regression based on universal threshold level. Ali T, Heyam Abd Al-Majeed Hayawi, Botani I. Published February 26, 2021
// -- }
// Function :-{
kernel_regression(_src,_size,_h)=>
float _currentWeight= 0.
float _cumulativeWeight= 0.
for i = 0 to _size + x_0
y = _src[i]
w = math.pow(1 + (math.pow(i, 2)/ ((math.pow(_h, 2) * 2 * r))), -r)
_currentWeight += y*w
_cumulativeWeight += w
_currentWeight/_cumulativeWeight
// Estimations
yhat1 = kernel_regression(src, size, h)
yhat2 = kernel_regression(src, size, h-lag)
// -- }
// Rates of Change :-{
bool wasBearish = yhat1[2] > yhat1[1]
bool wasBullish = yhat1[2] < yhat1[1]
bool isBearish = yhat1[1] > yhat1
bool isBullish = yhat1[1] < yhat1
bool isBearishChange = isBearish and wasBullish
bool isBullishChange = isBullish and wasBearish
// -- }
// Crossovers :-{
bool isBullishCross = ta.crossover(yhat2, yhat1)
bool isBearishCross = ta.crossunder(yhat2, yhat1)
bool isBullishSmooth = yhat2 > yhat1
bool isBearishSmooth = yhat2 < yhat1
// -- }
// Colors:-{
color c_bullish = input.color(#3AFF17, 'Bullish Color', group='Colors')
color c_bearish = input.color(#FD1707, 'Bearish Color', group='Colors')
color colorByCross = isBullishSmooth ? c_bullish : c_bearish
color colorByRate = isBullish ? c_bullish : c_bearish
color plotColor = smoothColors ? colorByCross : colorByRate
// -- }
// Plot:-{
plot(yhat1, "Rational Quadratic Kernel Estimate", color=plotColor, linewidth=2)
// -- }
// Alert Variables:-{
bool alertBullish = smoothColors ? isBearishCross : isBearishChange
bool alertBearish = smoothColors ? isBullishCross : isBullishChange
// -- }
// Alerts for Color Changes:-{
alertcondition(condition=alertBullish, title='Bearish Color Change', message='Nadaraya-Watson: {{ticker}} ({{interval}}) turned Bearish â–¼')
alertcondition(condition=alertBearish, title='Bullish Color Change', message='Nadaraya-Watson: {{ticker}} ({{interval}}) turned Bullish â–²')
// -- }
// Non-Displayed Plot :-{
// Outputs (i.e., for use in other indicators)
plot(alertBearish ? -1 : alertBullish ? 1 : 0, "Alert Stream", display=display.none)
// -- }
Editor is loading...