Deleting new lines once the price crosses it after the line was created - line

I have been creating new lines in pinescript that extend and want to delete them when the future price hits or crosses the line price. Any help will be appreciated.
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//#version=4
study("My RS", overlay=true)
float d = 1.0
t = time("60")
start = na(t[1]) or t > t[1]
ticker = syminfo.ticker
src=input(title="Source", type=input.source, defval=open)
float d_r = na
float d_s = na
if (start)
d_r := src + d
d_s := src - d
line lr = na
line ls = na
// drawing r/s lines every hour
if (start)
lr := line.new(x1 = bar_index, y1 = d_r, x2 = bar_index - 1, y2 = d_r, extend = extend.left, color = color.red, width = 2, style = line.style_dashed)
ls := line.new(x1 = bar_index, y1 = d_s, x2 = bar_index - 1, y2 = d_s, extend = extend.left, color = color.lime, width = 2, style = line.style_dashed)
// want to delete lines when the future price crosses the line, which is not working for me
for i = 0 to 100
if not na(lr[i]) and close < high[i]
line.delete(lr[i])
if not na(ls[i]) and close < low[i]
line.delete(ls[i])

you need to get the coordinate of the lines, so use inside a loop if line.get_y1(id[i]) < close if it true, line.delete(id[i]).
Is this what're you looking for?

Related

How to create fixed lines that do not change as the timeframe changes

I am developing a strategy that allows me to buy long on certain price levels set on the past daily timeframe (close[1]). My algorithm builds a grid of 5 lines starting from the closing price of the dayli timeframe (D). I do not think I have done anything wrong in the code, I have been checking for several hours. The problem is that the lines in my grid do not remain fixed on the dayli levels but change as the timeframe changes. So if I switch from D to 1H or less my grid adjusts to that timeframe. I wonder how this is possible as all the inputs I have written refer exclusively to the Dayli timeframe ?
//#version=5
strategy("",
overlay = true,
calc_on_every_tick = true,
initial_capital = 1000,
commission_type = strategy.commission.percent,
commission_value = 0.03,
pyramiding = 1,
default_qty_value = 100,
default_qty_type = strategy.percent_of_equity,
process_orders_on_close = true,
close_entries_rule = 'ANY')
openingDayPrice = request.security(syminfo.ticker,
"D", open[1],
gaps = barmerge.gaps_off)
closingDayPrice = request.security(syminfo.ticker,
"D", close[1],
gaps = barmerge.gaps_off)
var float dcaLongStart = 0
var float dcaLongEnd = 0
isDcaLong = if closingDayPrice > close[2]
dcaLongStart := closingDayPrice
dcaLongEnd := openingDayPrice
else
dcaLongStart := 0
dcaLongEnd := 0
startDcaLong = float(dcaLongStart)
endDcaLong = float(dcaLongEnd)
numbersOfLevels = 5
difference = float(startDcaLong - endDcaLong)
valuePerDCA = difference / numbersOfLevels
valueDCA1 = valuePerDCA * 1
level1 = startDcaLong - valueDCA1
valueDCA2 = valuePerDCA * 2
level2 = startDcaLong - valueDCA2
valueDCA3 = valuePerDCA * 3
level3 = startDcaLong - valueDCA3
valueDCA4 = valuePerDCA * 4
level4 = startDcaLong - valueDCA4
valueDCA5 = valuePerDCA * 5
level5 = startDcaLong - valueDCA5
var line _firstLine = na
var line _secondLine = na
var line _thirdLine = na
var line _fourthLine = na
var line _fifthLine = na
var line _sixLine = na
var line _sevenLine = na
if isDcaLong
_firstLine := line.new(bar_index, startDcaLong, bar_index + 1, startDcaLong, extend = extend.right, color = color.purple, width = 1)
line.delete(_firstLine[1])
_secondLine := line.new(bar_index, endDcaLong, bar_index + 1, endDcaLong, extend = extend.right, color = color.purple, width = 1)
line.delete(_secondLine[1])
_thirdLine := line.new(bar_index, level1, bar_index + 1, level1, extend = extend.right, color = color.purple, width = 1)
line.delete(_thirdLine[1])
_fourthLine := line.new(bar_index, level2, bar_index + 1, level2, extend = extend.right, color = color.purple, width = 1)
line.delete(_fourthLine[1])
_fifthLine := line.new(bar_index, level3, bar_index + 1, level3, extend = extend.right, color = color.purple, width = 1)
line.delete(_fifthLine[1])
_sixLine := line.new(bar_index, level4, bar_index + 1, level4, extend = extend.right, color = color.purple, width = 1)
line.delete(_sixLine[1])

Pinescript conditional line end/delete

I’m trying to create lines that auto plot at certain intervals using the line.new() function. So for example every new monthly open there will be lines plotted 5% and 10% above and beneath price. They’re then extended to the right indefinitely.
I then want to have the lines end once high/low has breached the line. I can’t seem to figure how to do this using the line.delete() function, although I doubt this is the correct path to take anyway due to the fact this deletes the entire line rather than just end it at breach point.
Due to the fact lines are extended indefinitely/until price has breached, there may be instances in which lines are never touched and are only removed once the 500 max line limit is reached. So I haven’t figured a way to use array references for lines to find a solution - and the 40 plot limit for pine plots isn’t really a sufficient amount of lines.
If this isn’t possible then just deleting the entire line upon breach is a backup option but I haven’t figure how to do this either!
Any help is much appreciated, thanks in advance!
You can use additional arrays to track the price values and their crossed state more easily. Each element of the arrays corresponds to the values associated with the same line. We add, remove or modify them based on whether a particular line's price value has been crossed or the line limit has been exceeded.
//#version=5
indicator("Monthly Interval Lines", overlay = true, max_lines_count = 500)
var float[] interval_prices = array.new_float()
var line[] interval_lines = array.new_line()
var bool[] intervals_crossed = array.new_bool()
new_month = timeframe.change("M")
if new_month
array.unshift(interval_lines, line.new(x1 = bar_index, y1 = open * 1.05, x2 = bar_index + 1, y2 = open * 1.05, extend = extend.right, color = color.green))
array.unshift(interval_prices, open * 1.05)
array.unshift(intervals_crossed, false)
array.unshift(interval_lines, line.new(x1 = bar_index, y1 = open * 1.10, x2 = bar_index + 1, y2 = open * 1.10, extend = extend.right, color = color.green))
array.unshift(interval_prices, open * 1.10)
array.unshift(intervals_crossed, false)
array.unshift(interval_lines, line.new(x1 = bar_index, y1 = open * 0.95, x2 = bar_index + 1, y2 = open * 0.95, extend = extend.right, color = color.red))
array.unshift(interval_prices, open * 0.95)
array.unshift(intervals_crossed, false)
array.unshift(interval_lines, line.new(x1 = bar_index, y1 = open * 0.90, x2 = bar_index + 1, y2 = open * 0.90, extend = extend.right, color = color.red))
array.unshift(interval_prices, open * 0.90)
array.unshift(intervals_crossed, false)
size = array.size(intervals_crossed)
if size > 0
if size > 500
for i = size - 1 to 500
line.delete(array.pop(interval_lines))
array.pop(intervals_crossed)
size := array.size(intervals_crossed)
for i = 0 to size - 1
price_val = array.get(interval_prices, i)
already_crossed = array.get(intervals_crossed, i)
crossed_price_val = low < price_val and high > price_val
gapped_price_val = (close[1] < price_val and open > price_val) or (close[1] > price_val and open < price_val)
if not already_crossed and (crossed_price_val or gapped_price_val)
array.set(intervals_crossed, i, true)
interval_line = array.get(interval_lines, i)
line.set_extend(interval_line, extend.none)
line.set_x2(interval_line, bar_index)

Colours don't show up in bar plot using ggplot2

When I try to assign colours using colour = "" or fill = """, the graph changes its colour always to the same colour (some kind of weird orange tone). The specific code I used is this:
Plot <- ggplot(data, aes(ymin = 0)) + geom_rect(aes(xmin = left, xmax = right, ymax = a, colour = "#FDFEFE")).
Has anyone had this problem before? It doesn`t seem to matter whether I use the colour names or the HTML codes, the result stays the same.
Thank you!
I just wanted to add some explanation because this also tripped me up when I started using ggplot.
Some toy data:
data <- tibble(a = 1:10, left = 1:10 * 20, right = 1:10 * 20 + 10)
As explained by #stefan, you need to set the hard-coded color outside of the aestetics:
ggplot(data, aes(ymin = 0)) +
geom_rect(aes(xmin = left, xmax = right, ymax = a), fill = "#FDFEFE")
The aestetics are meant to link the plot to your data table. When you write this:
ggplot(data, aes(ymin = 0)) +
geom_rect(aes(xmin = left, xmax = right, ymax = a, fill = "#FDFEFE"))
It is like having the following:
data <- tibble(a = 1:10, left = 1:10 * 20, right = 1:10 * 20 + 10, col = "#FDFEFE")
ggplot(data, aes(ymin = 0)) +
geom_rect(aes(xmin = left, xmax = right, ymax = a, fill = col))
Except that ggplot understands "#FDFEFE" as a categorical value, not as a color. Having "#FDFEFE" or "banana" is the same to ggplot:
ggplot(data, aes(ymin = 0)) +
geom_rect(aes(xmin = left, xmax = right, ymax = a, fill = "banana"))
or
data <- tibble(a = 1:10, left = 1:10 * 20, right = 1:10 * 20 + 10, col = "banana")
ggplot(data, aes(ymin = 0)) +
geom_rect(aes(xmin = left, xmax = right, ymax = a, fill = col))
assign default colours to the categorical data.
As an extra, if you want to assign specific colors to different entries in the table, it is best to use a scale_*_manual layer:
data <- tibble(a = 1:10, left = 1:10 * 20, right = 1:10 * 20 + 10,
col = sample(c("banana", "orange", "coconut"), 10, replace = T))
ggplot(data, aes(ymin = 0)) +
geom_rect(aes(xmin = left, xmax = right, ymax = a, fill = col)) +
scale_fill_manual(values = c("banana" = "yellow2", "orange" = "orange2", "coconut" = "burlywood4"))
If you wanted to hard-code the colors in the table, you would have to use this column outside to the aestetics:
data <- tibble(a = 1:10, left = 1:10 * 20, right = 1:10 * 20 + 10,
col = sample(c("yellow2", "orange2", "burlywood4"), 10, replace = T))
ggplot(data, aes(ymin = 0)) +
geom_rect(aes(xmin = left, xmax = right, ymax = a), fill = data$col)
But it is best to use meaningful categorical values and assign the colors in the scale layer. This is what the grammar of graphics is all about!

Getting the charge of a single atom, per loop in MD Analysis

I have been trying to use the partial charge of one particular ion to go through a calculation within mdanalysis.
I have tried(This is just a snippet from the code that I know is throwing the error):
Cl = u.select_atoms('resname CLA and prop z <= 79.14')
Lz = 79.14 #Determined from system set-up
Q_sum = 0
COM = 38.42979431152344 #Determined from VMD
file_object1 = open(fors, 'a')
print(dcd, file = file_object1)
for ts in u.trajectory[200:]:
frame = u.trajectory.frame
time = u.trajectory.time
for coord in Cl.positions:
q= Cl.total_charge(Cl.position[coord][2])
coords = coord - (Lz/COM)
q_prof = q * (coords + (Lz / 2)) / Lz
Q_sum = Q_sum + q_prof
print(q)
But I keep getting an error associated with this.
How would I go about selecting this particular atom as it goes through the loop to get the charge of it in MD Analysis? Before I was setting q to equal a constant and the code ran fine so I know it is only this line that is throwing the error:
q = Cl.total_charge(Cl.position[coord][2])
Thanks for the help!
I figured it out with:
def Q_code(dcd, topo):
Lz = u.dimensions[2]
Q_sum = 0
count = 0
CLAs = u.select_atoms('segid IONS or segid PROA or segid PROB or segid MEMB')
ini_frames = -200
n_frames = len(u.trajectory[ini_frames:])
for ts in u.trajectory[ini_frames:]:
count += 1
membrane = u.select_atoms('segid PROA or segid PROB or segid MEMB')
COM = membrane.atoms.center_of_mass()[2]
q_prof = CLAs.atoms.charges * (CLAs.positions[:,2] + (Lz/2 - COM))/Lz
Q_instant = np.sum(q_prof)
Q_sum += Q_instant
Q_av = Q_sum / n_frames
with open('Q_av.txt', 'a') as f:
print('The Q_av for {} is {}'.format(s, Q_av), file = f)
return Q_av

Offset rotation matrix

I'm working with 2 imu's. I need to offset all frames with the first frame from the sensor. I have created a fictive scenario, where I precisely know the rotation and the wanted result. I need the two sensors to show the same result when their initial (start) orientation is subtracted.
import numpy as np
# Sensor 0,1 and 2 start orientation in degrees
s0_x = 30
s0_y = 0
s0_z = 0
s1_x = 0
s1_y = 40
s1_z = 0
s2_x = 10
s2_y = 40
s2_z= -10
# Change from start frame 1
x1 = 20
y1 = 10
z1 = 0
# Change from start frame 2
x2 = 60
y2 = 30
z2 = 30
GCS= [[1,0,0],[0,1,0],[0,0,1]]
sensor0 = [[s0_x, s0_y, s0_z], [s0_x, s0_y, s0_z], [s0_x, s0_y, s0_z]]
sensor1 = [[s1_x, s1_y, s1_z], [s1_x + x1, s1_y + y1, s1_z + z1],[s1_x + x1 + x2, s1_y + y1+ y2, s1_z + z1+ z2]]
sensor2 = [[s2_x, s2_y, s2_z], [s2_x + x1, s2_y + y1, s2_z + z1], [s2_x + x1+ x2, s2_y + y1+ y2, s2_z + z1+ z2]]
def Rot_Mat_X(theta):
r = np.array([[1,0,0],[0,np.cos(np.deg2rad(theta)),-np.sin(np.deg2rad(theta))],[0,np.sin(np.deg2rad(theta)),np.cos(np.deg2rad(theta))]])
return r
# rotation the rotation matrix around the Y axis (input in deg)
def Rot_Mat_Y(theta):
r = np.array([[np.cos(np.deg2rad(theta)),0,np.sin(np.deg2rad(theta))],
[0,1,0],
[-np.sin(np.deg2rad(theta)),0,np.cos(np.deg2rad(theta))]])
return r
# rotation the rotation matrix around the Z axis (input in deg)
def Rot_Mat_Z(theta):
r = np.array([[np.cos(np.deg2rad(theta)),-np.sin(np.deg2rad(theta)),0],
[np.sin(np.deg2rad(theta)),np.cos(np.deg2rad(theta)),0],
[0,0,1]])
return r
# Creating the rotation matrices
r_sensor0 = []
r_sensor1= []
r_sensor2= []
for i in range(len(sensor1)):
r_sensor1_z = np.matmul(Rot_Mat_X(sensor1[i][0]),GCS)
r_sensor1_zy = np.matmul(Rot_Mat_Y(sensor1[i][1]),r_sensor1_z)
r_R_Upperarm_medial_zyx = np.matmul(Rot_Mat_Z(sensor1[i][2]),r_sensor1_zy )
r_sensor1.append(r_R_Upperarm_medial_zyx )
r_sensor2_z = np.matmul(Rot_Mat_X(sensor2[i][0]),GCS)
r_sensor2_zy = np.matmul(Rot_Mat_Y(sensor2[i][1]),r_sensor2_z )
r_sensor2_zyx = np.matmul(Rot_Mat_Z(sensor2[i][2]),r_sensor2_zy )
r_sensor2.append(r_sensor2_zyx )
r_start_sensor1 = r_sensor1[0]
r_start_sensor2 = r_sensor2[0]
r_offset_sensor1 = []
r_offset_sensor2 = []
for i in range(len(sensor0)):
r_offset_sensor1.append(np.matmul(np.transpose(r_start_sensor1),r_sensor1[i]))
r_offset_sensor2.append(np.matmul(np.transpose(r_start_sensor2),r_sensor2[i]))
# result:
r_offset_sensor1[0] = [[1,0,0],[0,1,0],[0,0,1]]
r_offset_sensor1[1] = [[0.984,0.059,0.163],[0,0.939,-0.342],[-0.173,0.336,0.925]]
r_offset_sensor1[2] = [[0.748,0.466,0.471],[0.086,0.635,-0.767],[-0.657,0.615,0.434]]
r_offset_sensor2[0] = [[1,0,0],[0,1,0],[0,0,1]]
r_offset_sensor2[1] = [[0.984,0.086,0.150],[-0.03,0.938,-0.344],[-0.171,0.334,0.926]]
r_offset_sensor2[2] = [[0.748,0.541,0.383],[-0.028,0.603,-0.797],[-0.662,0.585,0.466]]
I expect the result of sensors 1 and 2 to be equal for all frames but it doesn't? And they should be:
frame[0] = [1,0,0],[0,1,0],[0,0,1]
frame[1] = [0.984,0,0.173],[0.059,0.939,-0.336],[-0.163,0.342,0.9254]
frame[2] = [0.750,-0.433,0.50],[0.625,0.216,-0.750],[0.216,0.875,0.433]