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

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

Related

Pandas: Product price calculation by carrier

I have a tariff 'tarifas' of the Sudoeste and Termaco carriers
dataframe and a products 'dpx' dataframe
tarifas = {
'Sudoeste': {
'PR': {
'Capital': {'frete_minimo': 47.40,'rate': 0.35,'pedagio_frac': 2.83,'gris': 0.0012,'taxa': 3.36},
'Interior': {'frete_minimo': 48.34,'rate': 0.36,'pedagio_frac': 2.83,'gris': 0.0012,'taxa': 3.36},},}
'Termaco': {
'CE':{
'Capital': {'frete_minimo': 52.69,'Exce_50': 1.06,'pedagio_frac': 2.64,'gris': 0.0011,'taxa': 42.71},
'Interior': {'frete_minimo': 68.76,'Exce_50': 1.39,'pedagio_frac': 2.64,'gris': 0.0011,'taxa': 42.71},},}
I have a function to calculate the delivery freight of a product to a certain region, but it is giving an error.
def calcular_frete(dpx, tarifas):
for index, row in dpx.iterrows():
uf = row['Estado do Destinatário']
regiao = row['regiao']
peso_taxado = row['Peso Taxado']
valor_mercadoria = row['Valor da Mercadoria']
for transportadora, tarifas_transp in tarifas.items():
tarifas = tarifas_transp[uf][regiao]
frete_minimo = tarifas['frete_minimo']
exce_50 = tarifas.get('Exce_50', 0)
pedagio_frac = tarifas['pedagio_frac']
gris = tarifas['gris']
taxa = tarifas['taxa']
rate = tarifas['rate']
if transportadora =='Sudoeste':
if peso_taxado > 50:
valor_frete = frete_minimo + (peso_taxado - 50) * rate + (peso_taxado / 100) * pedagio_frac + (valor_mercadoria * gris) + (valor_mercadoria * taxa)
else:
valor_frete = frete_minimo + (peso_taxado / 100) * pedagio_frac + (valor_mercadoria * gris) + (valor_mercadoria * taxa)
When I call the function to calculate shipping calcular_frete(dpx, tarifas), it results in KeyError: 'SC' in 'tarifas = tarifas_transp[uf][regiao]'
What can I do?

Error in FUN(X[[i]], ...) : object 'Year' not found when plotting ordination in ggplot

I am having an issue with the ggplot code line where R doesn't like the "group = Year".
Here is what my data looks like:
> head(data.scores.pa)
NMDS1 NMDS2 NMDS3 Site Year Elevation Fire history
1 -0.737547 0.73473457 0.7575643 BF 2004 1710 Burnt
......
> head(spp.scrs2)
species MDS1 MDS2 pval
1 Acrothamnus.montanus 0.8383 -0.02382347 1e-04
........
> head(vec.sp.df.pa)
MDS1 MDS2 species pvals
Elevation 0.834847 0.747474 Elevation 0.005
Here is the code I am using:
>xy <- ggplot(data.scores.pa, aes(x = NMDS1, y = NMDS2, group = Year)) +
geom_point(size = 3, aes(shape = Fire history, colour = Year))+
stat_ellipse(mapping = NULL, data = NULL, geom = "path", position = "identity", type = "t", level = 0.95, segments = 51, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) +
geom_segment(data=vec.sp.df.pa, aes(x=0,xend=MDS1,y=0,yend=MDS2),
arrow = arrow(length = unit(0.5,"cm")),colour="grey")+
geom_text_repel(data=vec.sp.df.pa,aes(x=MDS1,y=MDS2,label=species),size=2)+
geom_segment(data=spp.scrs2,aes(x=0,xend=MDS1,y=0,yend=MDS2),
arrow = arrow(length = unit(0.5, "cm")),colour="black")+
geom_text_repel(data=spp.scrs2, aes(x=MDS1,y=MDS2,label=species),size=2)+
annotate("text", x = -1.6, y = 1, label = paste0("3D stress: ", format(ord.pa$stress, digits = 4)), hjust = 0) +
theme_cowplot() + scale_color_brewer(palette = "BrBG", direction = 1) +
theme(panel.border = element_rect(colour = "black"))+
ggtitle("All Sites - distance data using Bray-Curtis")+
labs(x = "NMDS1", y = "NMDS2")
> Error in FUN(X[[i]], ...) : object 'Year' not found
However, when I remove the geom_segment and geom_text_repel code lines it fixes the problem and I am able to plot the graph...
Is anyone able to provide some insight into this issue?
Thank you!

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.

Repeating 2 backgrounds in Corona SDK

Here's a problem: I'm making a simple physics game using Corona SDK and very simple module: http://developer.coronalabs.com/code/move-camera So I've got fish object with physics body and in each frame (enterFrame event) I'm centering camera on it
camera.x = -fish.x + screenWidth / 2
And I've got two backgrounds bg1 and bg2, which tiled each after other (bg1 bg2 bg1 bg2 etc) will make nice moving-world effect without user knowing that there are only 2 backgrounds. The problem is I can't get right calculations of their positions to make such effect. I googled a lot, but can't find anything to fit my needs.
Here's a free art, which I'm using http://www.vickiwenderlich.com/2013/02/free-game-art-flying-goldfish/ There you can find these two backgrounds.
It's also possible that fish can go slightly in opposite direction (generally it's moving to the right so to make world-moving effect backgrounds has to move to the left) so it would be nice if it'll in calculations.
I figured out something like this (however it doesn't work but maybe I'm close):
local function updateFrame(event)
local m
local dfx = lfx - fish.x
lfx = fish.x
camera.x = -fish.x + screenWidth / 2
--print("dfx = " .. dfx)
bg1.x = bg1.x + dfx
bg2.x = bg2.x + dfx
s = s + dfx
if mAbs(s) > screenWidth then
m = sgn(s)
if m ~= 0 then
s = s - m * screenWidth
if m < 0 then
bg1.x = bg1.x - 2 * m * screenWidth
else
bg2.x = bg2.x - 2 * m * screenWidth
end
end
end
end
Runtime:addEventListener( "enterFrame", updateFrame );
s = screenLeft - screenWidth
where s is the sum of pixels moved and if it's over screenWidth I jump with one of the backgrounds, lfx is the last fish x location, dfx is a difference between last and current fish location and that's it.
If you can help me with my calculations or give me new ones or just give some interesting links please write them right here.
Any help will be appreciated,
Regards
local road = display.newImageRect( "Images/roadBg1.png",2247/4,559/4 )
road:setReferencePoint( display.CenterLeftReferencePoint )
road.x = 0
road.y = baseline - 20
local road2 = display.newImageRect( "Images/roadBg1.png",2247/4,559/4 )
road2:setReferencePoint( display.CenterLeftReferencePoint )
road2.x = 2247/4
road2.y = baseline - 20
local tPrevious = system.getTimer()
local function move(event)
local tDelta = event.time - tPrevious
tPrevious = event.time
local xOffset = ( 0.2 * tDelta )
road.x = road.x - xOffset
road2.x = road2.x - xOffset
if (road.x + road.contentWidth) < 0 then
road:translate( 2247/4 * 2, 0)
end
if (road2.x + road2.contentWidth) < 0 then
road2:translate( 2247/4 * 2, 0)
end
Runtime:addEventListener( "enterFrame", move )
or see the sample code of jungle scene game.
Location: SampleApps/Sprites/JungleScene
Try this:
local bg1 = display.newImageRect( "bg_1.png" ,480 ,320)
bg1.x = display.contentWidth/2; bg1.y = display.contentHeight/2
local bg2 = display.newImageRect( "bg_2.png" ,480 ,320 )
bg2.x = bg1.x + bg1.width; bg2.y = display.contentHeight/2
local speed = 30
function move()
bg1.x = bg1.x-speed;
bg2.x = bg2.x-speed;
if(bg1.x + bg1.width/2 < 0)then bg1.x = bg1.width*3/2-speed
elseif(bg2.x + bg2.width/2 < 0)then bg2.x = bg2.width*3/2-speed end
end
Runtime:addEventListener( "enterFrame", move )
Keep coding............ :)
Thanks #krs and #Malar, combining your answers I figured out how to do this:
local function updateFrame(event)
local speed = fish.x - lfx
lfx = fish.x
camera.x = -fish.x + screenWidth / 2
bg1.x = bg1.x - speed
bg2.x = bg2.x - speed
if bg1.x + bg1.width < 0 then
bg1.x = bg1.x + screenWidth * 2
end
if bg2.x + bg2.width < 0 then
bg2.x = bg2.x + screenWidth * 2
end
if bg1.x - bg1.width > 0 then
bg1.x = bg1.x - screenWidth * 2
end
if bg2.x - bg2.width > 0 then
bg2.x = bg2.x - screenWidth * 2
end
end
Runtime:addEventListener( "enterFrame", updateFrame );
Starting positions:
bg1.x = screenLeft
bg2.x = bg1.x + bg1.width
And the last most important change:
I put bg1, bg2 and camera into a group and other objects into camera group:
local camera = require("camera")
group = display.newGroup()
group:insert(bg1)
group:insert(bg2)
camera:insert(fish)
camera:insert(ground)
group:insert(camera)
So we have ground and fish, which can move forever, but the backgrounds are only moving from -screenWidth to screenWidth.
All these things combined works like a charm!

Stopping at a point

I have a space ship that I want to turn to a destination angle. Currently it works like 90% of the time, but sometimes, it 'jumps' to the destination angle rather than moving smoothly. Here is my code:
a = System.Math.Sin(.destStoppingAngle + System.Math.PI)
b = System.Math.Cos(.destStoppingAngle + System.Math.PI)
c = System.Math.Sin(.msngFacing)
d = System.Math.Cos(.msngFacing)
det = a * d - b * c
If det > 0 Then
.msngFacing = .msngFacing - .ROTATION_RATE * TV.TimeElapsed
If det < 0.1 Then
.msngFacing = .destStoppingAngle
.turning = False
End If
Else
.msngFacing = .msngFacing + .ROTATION_RATE * TV.TimeElapsed
If det > 0.1 Then
.msngFacing = .destStoppingAngle
.turning = False
End If
End If
I would do it like this. First you need a function to lerp an angle (C code, port it yourself):
float lerpangle(float from, float to, float frac) {
float a;
if ( to - from > 180 ) {
to -= 360;
}
if ( to - from < -180 ) {
to += 360;
}
a = from + frac * (to - from);
return a;
}
Then, when starting the rotation you have the duration and stoppingangle as your own parameters. Get the startingangle from your object and startingtime (in something decently precise, milliseconds) and save them. The rotation then goes like this:
current_rotation = lerpangle(startingangle, stoppingangle,
(time.now - startingtime) / duration)