Amibroker AFL: How to plot Custom Anchored VWAP (AVWAP) passing any specific date to it - stock

Below is the code for Anchored VWAP which will select Date based on my mouse click, my query is how to plot Anchored VWAP passing date as a parameter, so it will be constant across all symbols.
Eg: I want to pass "2021-03-26" as Date parameter so it will plot AVWAP starting from "2021-03-26" date.
_SECTION_BEGIN("CustomAVWAP");
dn = DateTime();
sd = SelectedValue( dn );
start = dn == sd;
mp = C;
PV = mp * V;
CV = Cum( V );
VSS = CV - ValueWhen( start, CV );
denom = IIf( VSS == 0, 1, VSS );
num = Cum( PV ) - ValueWhen( start, Cum( PV ) );
M = IIf( BarsSince( start ), num/denom, mp );
Plot( C, Date() + " Close", colorBrightGreen, styleBar );
Plot( M, "PSVWAP", colorBrightGreen, styleThick );
_SECTION_END();

Related

I want to find the highest price since entry in pine script?

I want to find the highest price and exit when current price is lower than highest price. The code to find the highest price is copied from here. how can I make a simpler code that finds highest price since entry? I also want to close the deal if current price is lower than a specific price. Please help me.
// SETTING //
length1=input(1)
length3=input(3)
length7=input(7)
length20=input(20)
length60=input(60)
length120=input(120)
ma1= sma(close,length1)
ma3= sma(close,length3)
ma7= sma(close,length7)
ma20=sma(close,length20)
ma60=sma(close,length60)
ma120=sma(close,length120)
rsi=rsi(close,14)
// BUYING VOLUME AND SELLING VOLUME //
BV = iff( (high==low), 0, volume*(close-low)/(high-low))
SV = iff( (high==low), 0, volume*(high-close)/(high-low))
vol = iff(volume > 0, volume, 1)
dailyLength = input(title = "Daily MA length", type = input.integer, defval = 50, minval = 1, maxval = 100)
weeklyLength = input(title = "Weekly MA length", type = input.integer, defval = 10, minval = 1, maxval = 100)
//-----------------------------------------------------------
Davgvol = sma(volume, dailyLength)
Wavgvol = sma(volume, weeklyLength)
//-----------------------------------------------------------
length = input(20, minval=1)
src = input(close, title="Source")
mult = input(2.0, minval=0.001, maxval=50, title="StdDev")
mult2= input(1.5, minval=0.001, maxval=50, title="exp")
mult3= input(1.0, minval=0.001, maxval=50, title="exp1")
basis = sma(src, length)
dev = mult * stdev(src, length)
upper = basis + dev
lower = basis - dev
dev2= mult2 * stdev(src, length)
Supper= basis + dev2
Slower= basis - dev2
dev3= mult3 * stdev(src, length)
upper1= basis + dev3
lower1= basis - dev3
offset = input(0, "Offset", type = input.integer, minval = -500, maxval = 500)
plot(basis, "Basis", color=#FF6D00, offset = offset)
p1 = plot(upper, "Upper", color=#2962FF, offset = offset)
p2 = plot(lower, "Lower", color=#2962FF, offset = offset)
fill(p1, p2, title = "Background", color=color.rgb(33, 150, 243, 95))
//----------------------------------------------------
exit=(close-strategy.position_avg_price / strategy.position_avg_price*100)
bull=(low>upper and BV>SV and BV>Davgvol)
bux =(close<Supper and close>Slower and volume<Wavgvol)
bear=(close<Slower and close<lower and SV>BV and SV>Wavgvol)
hi=highest(exit,10)
// - INPUTS
ShowPivots = input(true, title="Show Pivot Points")
ShowHHLL = input(true, title="Show HH,LL,LH,HL markers on Pivots Points")
left = input(5, minval=1, title="Pivot Length Left Hand Side")
right = input(5, minval=1, title="Pivot Length Right Hand Side")
ShowSRLevels = input(true, title="Show S/R Level Extensions")
maxLvlLen = input(0, minval=0, title="Maximum S/R Level Extension Length (0 = Max)")
ShowChannel = input(false, title="Show Levels as a Fractal Chaos Channel")
//
ShowFB = input(true, title="Show Fractal Break Alert Arrows")
// Determine pivots
pvtLenL = left
pvtLenR = right
// Get High and Low Pivot Points
pvthi_ = pivothigh(high, pvtLenL, pvtLenR)
pvtlo_ = pivotlow(low, pvtLenL, pvtLenR)
// Force Pivot completion before plotting.
pvthi = pvthi_
pvtlo = pvtlo_
// ||-----------------------------------------------------------------------------------------------------||
// ||--- Higher Highs, Lower Highs, Higher Lows, Lower Lows -------------------------------------------||
valuewhen_1 = valuewhen(pvthi, high[pvtLenR], 1)
valuewhen_2 = valuewhen(pvthi, high[pvtLenR], 0)
higherhigh = na(pvthi) ? na : valuewhen_1 < valuewhen_2 ? pvthi : na
valuewhen_3 = valuewhen(pvthi, high[pvtLenR], 1)
valuewhen_4 = valuewhen(pvthi, high[pvtLenR], 0)
lowerhigh = na(pvthi) ? na : valuewhen_3 > valuewhen_4 ? pvthi : na
valuewhen_5 = valuewhen(pvtlo, low[pvtLenR], 1)
valuewhen_6 = valuewhen(pvtlo, low[pvtLenR ], 0)
higherlow = na(pvtlo) ? na : valuewhen_5 < valuewhen_6 ? pvtlo : na
valuewhen_7 = valuewhen(pvtlo, low[pvtLenR], 1)
valuewhen_8 = valuewhen(pvtlo, low[pvtLenR ], 0)
lowerlow = na(pvtlo) ? na : valuewhen_7 > valuewhen_8 ? pvtlo : na
// If selected Display the HH/LL above/below candle.
plotshape(ShowHHLL ? higherhigh : na, title='HH', style=shape.triangledown, location=location.abovebar, color=color.new(color.green,50), text="HH", offset=-pvtLenR)
plotshape(ShowHHLL ? higherlow : na, title='HL', style=shape.triangleup, location=location.belowbar, color=color.new(color.green,50), text="HL", offset=-pvtLenR)
plotshape(ShowHHLL ? lowerhigh : na, title='LH', style=shape.triangledown, location=location.abovebar, color=color.new(color.red,50), text="LH", offset=-pvtLenR)
plotshape(ShowHHLL ? lowerlow : na, title='LL', style=shape.triangleup, location=location.belowbar, color=color.new(color.red,50), text="LL", offset=-pvtLenR)
plot(ShowPivots and not ShowHHLL ? pvthi : na, title='High Pivot', style=plot.style_circles, join=false, color=color.green, offset=-pvtLenR, linewidth=3)
plot(ShowPivots and not ShowHHLL ? pvtlo : na, title='Low Pivot', style=plot.style_circles, join=false, color=color.red, offset=-pvtLenR, linewidth=3)
//Count How many candles for current Pivot Level, If new reset.
counthi = 0
countlo = 0
counthi := na(pvthi) ? nz(counthi[1]) + 1 : 0
countlo := na(pvtlo) ? nz(countlo[1]) + 1 : 0
pvthis = 0.0
pvtlos = 0.0
pvthis := na(pvthi) ? pvthis[1] : high[pvtLenR]
pvtlos := na(pvtlo) ? pvtlos[1] : low[pvtLenR]
hipc = pvthis != pvthis[1] ? na : color.new(color.red,50)
lopc = pvtlos != pvtlos[1] ? na : color.new(color.green,50)
// Show Levels if Selected
plot(ShowSRLevels and not ShowChannel and (maxLvlLen == 0 or counthi < maxLvlLen) ? pvthis : na, color=hipc, linewidth=1, offset=-pvtLenR , title="Top Levels",style=plot.style_circles)
plot(ShowSRLevels and not ShowChannel and (maxLvlLen == 0 or countlo < maxLvlLen) ? pvtlos : na, color=lopc, linewidth=1, offset=-pvtLenR , title="Bottom Levels",style=plot.style_circles)
// Show Levels as a Fractal Chaos Channel
plot(ShowSRLevels and ShowChannel ? pvthis : na, color=color.green, linewidth=1, style=plot.style_stepline, offset=0, title="Top Chaos Channel", trackprice=false)
plot(ShowSRLevels and ShowChannel ? pvtlos : na, color=color.red, linewidth=1, style=plot.style_stepline, offset=0, title="Bottom Chaos Channel", trackprice=false)
// //
float fixedHH = fixnan(higherhigh)
// add offset = -pvtLenR to move the plot to the left and match the HH points.
plot(fixedHH)
bool lowerThanHH = close < fixedHH
float closeHHDiff = abs(fixedHH - close)
if barstate.islast
label.new(bar_index, high + 3*tr, tostring(closeHHDiff), xloc.bar_index, color = color.gray, style = label.style_label_down)
// STRATEGY LONG //
if (bull and close>ma3 and ma20>ma60)
strategy.entry("Long",strategy.long,1)
if (higherhigh*0.80==close)`enter code here`
strategy.close("Long",1)
imInATrade = strategy.position size != 0
highestPriceAfterEntry = valuewhen(imInATrade, high, 0)
The code above finds the highest price after entry or when you're in a trade.

Tradingview pine editor. Issue with ATR TP/SL coding from entry

I need to code Take profit and Stop loss with Average true range from the past. I have an issue my code is calculating latest ATR and i cannot find a way to lock ATR number from the entry. ATR is calculating after candle close that means while candle is active it doesn't exist. Adding picture where I have marked what I'm looking for and what pine is calculating.
Paint shows what I'm looking for, original pine shows code calculations
//#version=2
strategy("Heiwa",initial_capital=1000,default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, commission_value = 0.15, overlay=true)
//WADARINDICATOR----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
sensitivity = input(200, title="Sensitivity")
fastLength=input(20, title="FastEMA Length")
slowLength=input(40, title="SlowEMA Length")
channelLength=input(20, title="BB Channel Length")
mult=input(2.0, title="BB Stdev Multiplier")
deadZone=input(20, title="No trade zone threshold")
calc_macd(source, fastLength, slowLength) =>
fastMA = ema(source, fastLength)
slowMA = ema(source, slowLength)
fastMA - slowMA
calc_BBUpper(source, length, mult) =>
basis = sma(source, length)
dev = mult * stdev(source, length)
basis + dev
calc_BBLower(source, length, mult) =>
basis = sma(source, length)
dev = mult * stdev(source, length)
basis - dev
t1 = (calc_macd(close, fastLength, slowLength) - calc_macd(close[1], fastLength, slowLength))*sensitivity
t2 = (calc_macd(close[2], fastLength, slowLength) - calc_macd(close[3], fastLength, slowLength))*sensitivity
e1 = (calc_BBUpper(close, channelLength, mult) - calc_BBLower(close, channelLength, mult))
//e2 = (calc_BBUpper(close[1], channelLength, mult) - calc_BBLower(close[1], channelLength, mult))
trendUp = (t1 >= 0) ? t1 : 0
trendDown = (t1 < 0) ? (-1*t1) : 0
Waddardtdis = input(50, minval=1)
//WADARINDICATOR----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//ATR---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
atrBandDays = input(15, minval=1, title="Days for ATR", type=integer)
atrBand = atr(atrBandDays)
atrPlus1 = close + atrBand
atrPlus2 = close + atrBand*2
atrPlus3 = close + atrBand*3
atrStop = close - atrBand*2
plot(atrPlus1, color=green)
plot(atrPlus2, color=orange)
plot(atrPlus3, color=red)
plot(atrStop, color=blue)
//ATR---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//Heikinashi---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
haTicker = heikinashi(tickerid)
haOpen = security(haTicker, period, open)
haClose = security(haTicker, period, close)
//Heikinashi---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
longCondition = haClose > haOpen and haOpen > haClose[1] and trendUp>e1
exitCondition = haClose < haOpen and trendDown>Waddardtdis
strategy.entry("Long", strategy.long, when=longCondition)
strategy.exit("TP1", "Long", qty_percent = 60, limit=atrPlus1)
strategy.exit("TP2", "Long", qty_percent = 20, limit=atrPlus2)
strategy.exit("TP3", "Long", qty_percent = 20, limit=atrPlus3)
strategy.exit("SL", "Long", stop = atrStop)
strategy.close ( "Long", when = exitCondition)
I'd just preserve the atr value at entry, like that:
entryAtr = entryAtr[1]
if (longCondition)
strategy.entry("Long", strategy.long)
entryAtr := atrBand // save the value to use it for exit

ggplot: how to remove unused factor levels from a facet?

The following code
d1 = data.frame(y=1:2,group=factor(c('A','B'), levels=c('A','B','C')), fac = 'f1')
d2 = data.frame(y=1:3,group=factor(c('A','B','C'), levels=c('A','B','C')), fac = 'f2')
d = rbind(d1,d2)
library(ggplot2)
ggplot( d, aes(x=group, y=y) ) + geom_point(size=3) + facet_grid( ~ fac)
Results in the following plot. How can I remove the unused factor level C from the facet 'f1'?
Setting scales = free in facet grid will do the trick:
facet_grid( ~ fac, scales = "free")

GAMS: Why is the value of the parameter pp(ss,ii) coming out as zero?

I have written the following code below in GAMS and it may not be the best in the world but I don't see why it keeps returning the value of the parameter pp(ss,ii) as all zeros when it should be a matrix of exactly 2 ones in each row.
Could you please help me?
set
ii set of bays /1*10/
ss set of solutions /1*45/
Parameters
H Number of bays /10/
C Number of cranes /2/
r Safety Margin /1/
p(ii)
pp(ss,ii)
;
p(ii) = 0;
Scalar i; i=1;
Scalar j; j=i;
Scalar k; k=C;
Scalar qq;
Scalar q;
Scalar kk;
Scalar m;
Scalar n;
Scalar stop /0/;
Scalar stop1 /0/;
Scalar stop2 /0/;
Scalar F /1/;
Scalar k1 /0/;
Scalar k2 /0/;
while ((i <= H-(C-1)*r-1*(C-1)),
while((j<=H and stop=0),
if (sum(ii, p(ii)) = C,
stop = 1;
);
loop(ii$(ord(ii)=j),
p(ii) = 1;
);
j = j+r+1;
);
if (sum(ii, p(ii)) = C,
loop((ss,ii)$(ord(ss)=F),
pp(ss,ii) = p(ii);
);
);
F = F+1;
qq=0;
for (q = 1 to H-(C-1)*r-1*(C-1)-1,
loop (ii$((ord(ii) = q) and (stop1 = 0)),
if ((p(ii) = 1) ,
qq=1;
stop1 = 1;
);
);
);
* if (qq=0,
* if (p(ii)$(ord(ii)= H-(C-1)*r-1*(C-1))=1 and p(ii)$(ord(ii)=H) = 1,
* abort "finished";
* );
*
* );
k1 = 0;
k2 = 0;
if(qq=0,
loop(ii$(ord(ii)= H-(C-1)*r-1*(C-1)),
if (p(ii) = 1,
k1 = 1;
);
);
loop(ii$(ord(ii)=H),
if (p(ii) = 1,
k2 = 1;
);
);
abort$(k1 + k2 = 2) "Finished";
);
if (j-r-1 = H,
loop(ii$(ord(ii)=H-(C-k)*r-(C-k)) ,
if(k = C,
k = k-1;
elseif (p(ii)= 1),
k = k-1;
);
);
if(k=1,
loop(ii,
p(ii)=0;
);
i = i+1;
j = i;
k = C;
else
loop(ii$(ord(ii)=H),
p(ii) = 0;
);
m=1;
n=0;
while((n<k),
loop(ii$(ord(ii)=m),
if(p(ii) = 1,
n = n+1;
);
m = m+1;
);
);
loop(ii$(ord(ii) = m-1),
p(ii) = 0;
);
loop(ii$(ord(ii) = m),
p(ii) = 1;
);
j = m+r+1;
);
else
loop(ii$(ord(ii) = j-r-1),
p(ii)=0;
);
loop(ii$(ord(ii) = j-r),
p(ii)= 1;
);
j=j+1;
);
);
Display pp;
On how to hunt errors in rather complex code:
first look up where you assigne values to your variable. You set pp = p; one time.
look up if p is right. Display says p is zero too.
during the pre solve process you can add aditional "display" statements in the middle of you code - to get the values at this points.
This gives you the hint that there are some values in p - but when you put the display statement after if (sum(ii, p(ii)) = C, you wont get any display calls -> sum(p) <> C ?
A closer Look into the p before the if and you'll see that there are three values inside which are more than two.
At the last step its simple to see the error in you code. It's the position of you stop = 1; criteria. Its placed at the beginning of the while loop. The loop will still continue in the current iteration and create a third value.
Solution:
Change the criteria to if (sum(ii, p(ii)) = C-1, or put the criteria at the end of the while loop.

WoW LUA: MSP, combining GTAL?

While I understand it's best to start from the basics, I like to dabble. This is killing me though. In WoW, I use ElvUI and MyRolePlay (MRP) and the result is an issue with the enhanced tooltip. I've done quite a bit of editing to the code and the only thing left is trying to get this last line formatting properly - the entirety (3 variables) on one line. I don't understand what gtal is (or the "L"), but it seems to create a new line. Is there a way to combine the gtal lines, while retaining the RGB colors for both respectively? I've tried to stay within the code style (since I'm having trouble bringing in new code) but due to how the author calls for colors on the variables, I couldn't manage to get the final %s its own color value without making a brand new line.
local dC = GetQuestDifficultyColor(level);
local cC = RAID_CLASS_COLORS[ classunloc ];
Best I could come up with,
gtal( format( L["|r%s|cffffffff %s"], e, emptynil( mrp.DisplayTooltip.RA( f.RA ) ) or race, class), dC.r, dC.g, dC.b )
gtal( format( L["|r%s"], class), cC.r, cC.g, cC.b )
There's no information on gtal in the mod or anywhere else that I could find. I hear the author is impossible to approach. But I was hoping someone got the idea here.
Result of the two gtal lines Perfect, if only the last word was on the line above it!
If it helps, the block all this is in is
local dC = GetQuestDifficultyColor(level);
local cC = RAID_CLASS_COLORS[ classunloc ];
if level ~= nil and level < 0 then
e = L["|cffffffff(Boss)"]
else
e = format( L["|r%d|cffffffff"], level )
end
if mspsupported then
gtal( format( L["|r%s|cffffffff %s"], e, emptynil( mrp.DisplayTooltip.RA( f.RA ) ) or race, class), dC.r, dC.g, dC.b )
gtal( format( L["|r%s"], class), cC.r, cC.g, cC.b )
n = nil
t = nil
if f.FR and f.FR ~= "" and f.FR ~= "0" then
n = mrp.DisplayTooltip.FR( f.FR ) .. " "
end
and finally, this is what the original gtal looked like
gtal( format( L["%s %s |r%s|cffffffff (Player)"], e, emptynil( mrp.DisplayTooltip.RA( f.RA ) ) or race, class), r, g, b )
r, g, b = 1.0, 1.0, 1.0
Update - this is what works here, since if this were ever helpful to anyone else:
local dC = GetQuestDifficultyColor(level);
local cC = RAID_CLASS_COLORS[ classunloc ];
if level ~= nil and level < 0 then
e = L["|cffffffff(Boss)"]
else
e = format( L["|r%d|cffffffff"], level )
end
if mspsupported then
local classStr = format("|cff%02x%02x%02x%s|r", cC.r * 255, cC.g * 255, cC.b * 255, class)
local str = format( L["|r%s |cffffffff%s|r %s"], e, emptynil( mrp.DisplayTooltip.RA( f.RA ) ) or race, classStr)
gtal(str, dC.r, dC.g, dC.b)
gtal is defined in UI_Tooltip.lua:
--[[
EPIC KLUDGE!
Special local functions to overwrite and add the current tooltip.
]]
-- Single string
local function gtal( n, r, g, b )
local l = GameTooltip.mrpLines + 1
GameTooltip.mrpLines = l
r, g, b = (r or 1.0), (g or 1.0), (b or 1.0)
--if GameTooltip.mrpLines <= GameTooltip.orgLines then
-- Replace original line with ours, or add a new one if not there
if _G["GameTooltipTextLeft"..tostring(l)] then
if _G["GameTooltipTextLeft"..tostring(l)]:IsVisible() then
if _G["GameTooltipTextRight"..tostring(l)] then
_G["GameTooltipTextRight"..tostring(l)]:Hide()
end
_G["GameTooltipTextLeft"..tostring(l)]:SetText( n )
_G["GameTooltipTextLeft"..tostring(l)]:SetTextColor( r, g, b )
else
GameTooltip:AddLine( n, r, g, b )
end
else
GameTooltip:AddLine( n, r, g, b )
end
end
L is conventionally your localization table lookup, used here in case you want a different format string for a different language.
In this case, it looks like gtal always adds a line, so you need to do your work all in the same line. Fortunately, WoW gives you inline color overrides that you can use! See UI Escape Sequences - that's what's going on with |cxxxxxxxx and whatnot in the strings. You probably want something like:
-- Build a color-formatted class string
local classStr = format("|c%02x%02x%02x%s|r", cC.r, cC.g, cC.b, class)
-- Build your tooltip line, which consists of `$e $race $class`
local str = format( L["|r%s |cffffffff%s|r %s"], e, emptynil( mrp.DisplayTooltip.RA( f.RA ) ) or race, classStr)
-- Add the line to the tooltip
gtal(str, dC.r, dC.g, dC.b)