pivot point color conditionally: support and resistances according with higher high etc - pivot

I have 2 simple script, the first that plot the label shapes of higher high, higher low, etc with relative colors:
leftbars = input(title='LeftBars', defval=10)
rightbars = input(title='Rightbars', defval=5)
ph = ta.pivothigh(leftbars, rightbars)
pl = ta.pivotlow(leftbars, rightbars)
// Higher Highs and Higher Lows
hl = ta.valuewhen(ph, ph, 0) < ta.valuewhen(ph[1], ph[1], 0)
hh = ta.valuewhen(ph, ph, 0) > ta.valuewhen(ph[1], ph[1], 0)
plotshape(hh, title='Higher High', style=shape.square, location=location.abovebar, color=color.new(color.green, 75), text='[HH]', offset=-rightbars, size=size.auto)
plotshape(hl, title='Higher Low', style=shape.square, location=location.abovebar, color=color.new(color.red, 75), text='[HL]', offset=-rightbars, size=size.auto)
// Lower Lows and Lower Highs
ll = ta.valuewhen(pl[1], pl[1], 0) > ta.valuewhen(pl, pl, 0)
lh = ta.valuewhen(pl[1], pl[1], 0) < ta.valuewhen(pl, pl, 0)
plotshape(ll, title='Lower Low', style=shape.square, location=location.belowbar, color=color.new(color.red, 75), text='[LL]', offset=-rightbars, size=size.auto)
plotshape(lh, title='Lower High', style=shape.square, location=location.belowbar, color=color.new(color.green, 75), text='[LH]', offset=-rightbars, size=size.auto)
and the second that plot the lines at pivot points as support and resistances with fixed colors:
piv_hig = ta.pivothigh(high, leftbars, rightbars)
piv_low = ta.pivotlow(low, leftbars, rightbars)
top = ta.valuewhen(piv_hig, high[rightbars], 0)
bottom = ta.valuewhen(piv_low, low[rightbars], 0)
resist = plot(top, color=top != top[1] ? na : color.green, offset=-rightbars)
support = plot(bottom, color=bottom != bottom[1] ? na : color.red, offset=-rightbars)
What I'm trying to do is to merge the two scripts avoiding the labels hh, hl, etc, and coloring the support and resistance lines according with the colors and conditions of the first script. I thinked was simply but really I am not able ( obviously I'm a beginner)
At first I tried to plot the condition (hh, hl , ll , lh) but it's impossible because one is bool and the other require float:
resistance_hl = plot(hl, color=top != top[1] ? na : color.red, offset=-rightbars)
I tried to set color conditionally but nothing:
resistance_hl = plot(top, color=top != top[1] ? na : color_condition, offset=-rightbars)
I tried to apply the condition to the plotted value:
resistance_hl = plot(top and hl, color=top != top[1] ? na : color.red, offset=-rightbars)
I tried to change color=top != top[1] with color=top < top[1] and other various similar attempts but nothing.
I think I need to use line.new but I never used it and I'm trying to understand, but I'm not a coder so I proceed by trial.
any simple suggestions for the right way to follow?
can someone help me?
Thanks in advance

Related

Multiple long orders with separate take profit and stop loss

A bit new with coding. Hope to find some help.
I am trying to get each long position to have its own take profit and stop loss.
What ends up happening is, whenever the next long position is triggered, the previous TP and SL get recalculated and I end up with all positions having only one TP and SL levels.
Thanks
Played around with exit code and lastEntryPriceLong but not a big coder, soo... any help would be appreciated.
//////// Long Position 0 (1) ////////
if longCondition and longConditionATR and longConditionEMA and barRangeCondition and strategy.opentrades == 0
strategy.entry('Long', strategy.long)
lastEntryPriceLong = strategy.opentrades.entry_price(0)
var float LongTP = na
var float LongSL = na
if (strategy.position_size[1] != strategy.position_size)
LongTP := lastEntryPriceLong*2 - low[1]
LongSL := lastEntryPriceLong - (lastEntryPriceLong - low[1] + atr*2)
inTradeLong = strategy.position_size > 0
plot(inTradeLong ? LongTP : na, color=color.green, style=plot.style_circles)
plot(inTradeLong ? LongSL : na, color=color.red, style=plot.style_circles)
strategy.exit('Close Long', 'Long', stop=LongSL, limit=LongTP)
//////// Long Position 1 (2) ////////
if longCondition and longConditionATR and longConditionEMA and barRangeCondition and strategy.opentrades == 1
strategy.entry('Long1', strategy.long)
lastEntryPriceLong1 = strategy.opentrades.entry_price(1)
var float LongTP1 = na
var float LongSL1 = na
if (strategy.position_size[1] != strategy.position_size)
LongTP1 := lastEntryPriceLong1*2 - low[1]
LongSL1 := lastEntryPriceLong1 - (lastEntryPriceLong1 - low[1] + atr*2)
inTradeLong1 = strategy.position_size > 0
plot(inTradeLong1 ? LongTP1 : na, color=color.green, style=plot.style_circles)
plot(inTradeLong1 ? LongSL1 : na, color=color.red, style=plot.style_circles)
strategy.exit('Close Long1', 'Long1', stop=LongSL1, limit=LongTP1)
You can see Example here
Thanks
.
strategy.exit is in the root scope. So, it gets executed on each bar overwriting earlier entry.
You need to do few things here:
Move strategy.exit and the related calculations inside if condition where you have strategy.entry. This way, exit and entry are set together.
Use an auto incrementing Id instead of same id for all. You can do it using
var id= 1
if(longCondition)
entryId = Long+str.tostring(id)
exitId = ExitLong+str.tostring(id)
id+=1
strategy.entry(entryId, strategy.long, ...)
strategy.exit(exitId, entryId, ...)
In strategy definition, set close_entry_rule to ANY. This will let each trade track it's own exit based on id instead of closing order based on FIFO or FILO.
https://www.tradingview.com/pine-script-reference/v5/#fun_strategy

Project Tango Point Cloud strange crash, and dense depth map

I am trying to use Project Tango C API, but the application crashed with no error if number of point cloud are more than ~6.5k (after some testing) with the following code
int width = mImageSource->getDepthImageSize().x;
int height = mImageSource->getDepthImageSize().y;
double fx = mImageSource->calib.intrinsics_d.projectionParamsSimple.fx;
double fy = mImageSource->calib.intrinsics_d.projectionParamsSimple.fy;
double cx = mImageSource->calib.intrinsics_d.projectionParamsSimple.px;
double cy = mImageSource->calib.intrinsics_d.projectionParamsSimple.py;
memset(inputRawDepthImage->GetData(MEMORYDEVICE_CPU), -1, sizeof(short)*width*height);
for (int i = 0; i < XYZ_ij->xyz_count; i++) {
float X = XYZ_ij->xyz[i*3][0];
float Y = XYZ_ij->xyz[i*3][1];
float Z = XYZ_ij->xyz[i*3][2];
if (Z < EPSILON || (X < EPSILON && -X < EPSILON) || (Y < EPSILON && -Y < EPSILON) || X != X || Y != Y || Z != Z)
continue;
int x_2d = (int)(fx*X/Z+cx);
int y_2d = (int)(fy*Y/Z+cy);
if (x_2d >=0 && x_2d < width && y_2d >= 0 && y_2d < height && (x_2d != 0 || x_2d != 0)) {
inputRawDepthImage->GetData(MEMORYDEVICE_CPU)[x_2d + y_2d*width] = (short) (Z*1000);
} else {
continue;
}
}
However, if I use for (int i = 0; i < XYZ_ij->xyz_count && i < 6500; i++) everything works fine. I am just wondering if there is an upper bound for access point cloud with C API or I did something wrong?
(width is 320, height is 180, and other intrinsics are loaded from Tango API)
In addition, Google mentioned to use nearest- neighbor filter to get dense depth map in bottom of this page, is there an interface in Tango API for this? Or would anyone suggest an open source implementation for it.
I am also wondering if there is anyway to "pull" colored image(1280x720) in onXYZijAvailable because I need a dense synchronized colored point cloud. Do I need to apply external matrix to align both coordinate frame, or I only need to subsample color image (assume their coordinate system are the same)?
Thank you for any advice!
In your code that looks up the depth sample coordinates...
for (int i = 0; i < XYZ_ij->xyz_count; i++) {
float X = XYZ_ij->xyz[i*3][0];
float Y = XYZ_ij->xyz[i*3][1];
float Z = XYZ_ij->xyz[i*3][2];
...you should be using an index of i, not i*3. It is a 2D array so you don't have to manage the stride for the higher dimension yourself.
The SDK does not provide a call to fill in locations with no depth samples, probably because there are many approaches with different tradeoffs. The Wikipedia page on nearest neighbor search is a reasonable place to start. There is an interface to FLANN in OpenCV.
The SDK will only deliver the latest color image to you. If you want a prior image (e.g. with a timestamp close to your depth samples) you will have to manage that yourself. Because you can never get a color image at exactly the same timestamp with your depth samples (as the same camera is used in different modes for both), you theoretically should apply the extrinsic pose to align them. In practice if the motion is small over the 0.5 frame time or less between the timestamps, I think most people are going to ignore it.

Libgdx: how to draw a rounded border around a TiledMap with dynamic dimensions?

In libgdx I have a TiledMap that I fill with different Cells:
cell.setTile(new StaticTiledMapTile(reg1));
cell.setTile(new StaticTiledMapTile(reg2));
cell.setTile(new StaticTiledMapTile(reg...));
where reg is a texture region.
I render with:
render = new OrthogonalTiledMapRenderer(map);
render.setView(cam);
render.render();
Throughout the game, the number of columns, number of rows and size of the cells will vary, so they must remain dynamic.
Now, around this TiledMap, I want to add a rounded border. Below I am showing some examples in png of how I am planning to do it : from left to right, first is a top border, then a top-right corner, then a right border. Each of these png files has square dimensions.
What I want to achieve below, here is a zoom to the top right corner of the TiledMap:
I am planning to use these pngs as TextureRegions that I can set as cells in my TiledMap, something like that:
for (int x = 0; x < numcol+2; x++) {
for (int y = 0; y < numrow+2; y++) {
Cell cell = new Cell();
if (y==numrow+1) {
cell.setTile(new StaticTiledMapTile(b_mid_top));
}
if (y==0) {
cell.setTile(new StaticTiledMapTile(b_mid_bottom));
}
etc.
I am having multiple issues with the dimension of the pngs: as I mentioned, the size of the cells may vary throughout the game. To my knowledge there is no way to resize a cell or a textureregion from a png as I would need.
So I could use Image, resize them dynamically, add them as actors to a stage and draw the stage, but I fear I might loose the benefit of using a TiledMap. Also, I would have to deal with stage coordinates on the one hand and TiledMap coordinates on the other and it doesn't sound the best approach.
So I am a bit lost!
What is the best approach to draw my border around my TiledMap?
I am ready to abandon any of my current ideas for a better one. I am not very experienced with Libgdx so sorry if I have done some silly mistake.
I think the idea is good. In case the tilesize changes the bordersize changes too. You can't create a different sized tile as frame around it. In case you want to create always the same frame, you can use a simple Ninepatch with the size of the Map.
create something like this:
NinePatch p = new NinePatch(texture, 5, 5, 5, 5); // the edge sizes are 5px here.
Inside of the render method you draw it at the size of the tilemap. you can optain the sizes from the Map object:
p.draw(batch, 0, 0, tilesize*tilecountx, tilesize*tilecounty);
If you do not liket his idea you can go for the second version. Create a new TiledMap with the boarder as tiles you need to copy the whole Tilemap with an offset of 1 tile (since you need to have 1 tile space) and create a new tilemap with 2 rows and cols more.
Should look for example like this:
map = new TiledMap(); // the map with the bordercells
MapLayers layers = map.getLayers();
for (int l = 0; l < map1.getLayers().getCount(); l++) {
// create a new layer which is bigger
TiledMapTileLayer newlayer = new TiledMapTileLayer(
((TiledMapTileLayer) map1.getLayers().get(0)).getWidth() + 2,
((TiledMapTileLayer) map1.getLayers().get(0)).getHeight() + 2,
(int) ((TiledMapTileLayer) map1.getLayers().get(0))
.getTileWidth(), (int) ((TiledMapTileLayer) map1
.getLayers().get(0)).getTileHeight());
// now add the cells here
for (int x = 0; x < newlayer.getWidth(); x++) {
for (int y = 0; y < newlayer.getHeight(); y++) {
//add the right tile regions here!
if(x == 0 && y == 0){
Cell cell = new Cell();
cell.setTile(new StaticTiledMapTile(first edge));
newlayer.setCell(x, y, cell);
continue;
}
if(x == newlayer.getWidth()-1 && y == 0){
Cell cell = new Cell();
cell.setTile(new StaticTiledMapTile(second edge));
newlayer.setCell(x, y, cell);
continue;
}
if(x == 0 && y == newlayer.getHeight()-1){
Cell cell = new Cell();
cell.setTile(new StaticTiledMapTile(third edge));
newlayer.setCell(x, y, cell);
continue;
}
if(x == newlayer.getWidth()-1 && y == newlayer.getHeight()-1){
Cell cell = new Cell();
cell.setTile(new StaticTiledMapTile(fourth edge));
newlayer.setCell(x, y, cell);
continue;
}
if(x == 0){
Cell cell = new Cell();
cell.setTile(new StaticTiledMapTile(textureregion for bottom here));
newlayer.setCell(x, y, cell);
continue;
}
if(y == 0){
Cell cell = new Cell();
cell.setTile(new StaticTiledMapTile(textureregion for first col));
newlayer.setCell(x, y, cell);
continue;
}
if(x == newlayer.getWidth()-1){
Cell cell = new Cell();
cell.setTile(new StaticTiledMapTile(textureregion for toprow));
newlayer.setCell(x, y, cell);
continue;
}
if(y == newlayer.getHeight()-1){
Cell cell = new Cell();
cell.setTile(new StaticTiledMapTile(textureregion for last col));
newlayer.setCell(x, y, cell);
continue;
}
//last but not least if none of this fit add the tile from the old map
//dont forget the offsett
newlayer.setCell(x, y, ((TiledMapTileLayer)map1.getLayers().get(l)).getCell(x-1, y-1)); //map1 is the original map without the borders
}
}
layers.add(newlayer);
}
If you really have different tilesizes i would just add an Bordertexture for every tilesize you have in case you are using the TiledMap version. If you like to resize a Texture take a Sprite for it. A Sprite offers the .setSize(w,h) and also extends the TextureRegion. To create a Static TiledMapTile you can also add the Sprite as Texture. So if you take the idea use a Sprite and size it to the tile size before you create the StaticTiledMapTile.

How to compare Hough Line positions in OpenCV?

Using VC++ and Open CV. Here's what I'm trying to do:
find the first three nearly-horizontal hough lines and draw them.
find all the nearly-vertical lines and draw them
if any vertical line is above the horizontal line then a FLAG is set to 0
if there is no vertical Hough line above (all are below) the horizontal line then FLAG=1
int n, i,c=0;
int flag = 0;
cvCanny( src, dst, 50, 150, 3 );
lines = cvHoughLines2( dst, storage, CV_HOUGH_PROBABILISTIC, 1, CV_PI/180, 10, 5, 5 );
n = lines->total;
for( i = 0; i < n; i++ )
{
CvPoint* line = (CvPoint*)cvGetSeqElem(lines,i);
CvPoint pt1, pt2, hpt1, hpt2, vpt1, vpt2;
int hy = 0, vy = 0;
pt1 = line[0];
pt2 = line[1];
theta = atan( (double)(pt2.y - pt1.y)/(pt2.x - pt1.x) ); /*slope of line*/
degree = theta*180/CV_PI;
if( fabs(degree) < 8) //checking for near horizontal line
{
c++;
if( c > 0 && c <5) /*main horizontal lines come first*/
{
cvLine( out, pt1, pt2, CV_RGB(255, 255,255), 1, CV_AA, 0 );
hpt1 = line[0];
hpt2 = line[1];
if( hpt1.y > hpt2.y ) //finds out lower end-point
hy = hpt1.y;
else
hy = hpt2.y;
}
}
if( fabs(degree) > 70 ) /*near vertical lines*/
{
cvLine( out, pt1, pt2, CV_RGB(255, 255,255), 1, CV_AA, 0 );
vpt1 = line[0];
vpt2 = line[1];
if( vpt1.y > vpt2.y ) //finds upper end-pt of vertical line
vy = vpt1.y;
else
vy = vpt2.y;
if( vy >= hy ) //if vert line is lower than horizontal line
flag = 1;
else
flag = 0;
}
}
display( out, "hough lines" );
return flag;
}
However for an image even if vertical lines are detected above the horizontal line -still the flag is returning 1. So am i counting along the axis wrongly? Please help me out.
The if( fabs(degree) > 70 ) and if( fabs(degree) < 8 ) lines look wrong. An angle of about 180 means almost horizontal ... you probably want to change that, and bear in mind the periodicity of angles (so about 360 is also almost horizontal). A way to nicely handle that would be to use if (fabs(cos(angle - desired_angle)) > 0.996), which means roughly "if angle and desired_angle are within 5 degrees of each other, disregarding direction". 0.996 is roughly the cosine of 5 degrees, if you need it more exact put more digits there - 0.9961946980917455 is a nearer match.
Also, your loop order is off. You don't find the first three nearly-horizontal hough lines and draw them. find all the nearly-vertical lines and draw them if any vertical line is above the horizontal line in this sequence, you loop over all lines, in any order, and process them independently - the vertical ones could come before the horizontal ones, so you wouldn't know what to check for.
Third,
if( hpt1.y > hpt2.y ) //finds out lower end-point
hy = hpt1.y;
else
hy = hpt2.y;
vs
if( vpt1.y > vpt2.y ) //finds upper end-pt of vertical line
vy = vpt1.y;
else
vy = vpt2.y;
You use the same code to find the lower coordinate as to find the higher one. Do you think that could work?
Fourth,
if( vy >= hy ) //if vert line is lower than horizontal line
flag = 1;
else
flag = 0;
The value of flag depends on the LAST pass through this piece of code. This doesn't match the any in your description.
A much easier approche is to not use the PPHL (progressive probabilistic Hough Lines algorithm) but the SHL (standard HL) ! So that you get the polar form of a line with angle and radius ! You can then just check the angle, without calculating it yourself.
If the output angle is around 0° or 180° it's a vertical line, and if it's around 90° it's a horizontal line....

How to calculate easy to read color for a random backcolor?

in my current tool there is a colored box with some numbers in it. The backcolor of the box is defined by some sort of list but can also be altered by the user. The forecolor (== fontcolor of the numbers) cannot, and i want to make sure that the user can always read the numbers, so i´d like to adjust the forecolor of the numbers anytime the backcolor changes.
Atm i use code like this:
if(Math.Abs(foreColor.GetBrightness() - backColor.GetBrightness()) <= 0.5f)
{
if(foreColor.GetBrightness() > 0.5f)
{
foreColor = Color.Black;
}
else
{
foreColor = Color.White;
}
}
but that is only a workaround for the problem, there are quite a lot of colors (mostly yellows) leading to a bad to read display. Anyone touched a similar problem and found a good solution?
For each color component (assume a range of [0, 255] per component), if it's below 128, saturate it to 255; otherwise make it zero:
fg.r = bg.r < 128 ? 255 : 0;
fg.g = bg.g < 128 ? 255 : 0;
fg.b = bg.b < 128 ? 255 : 0;
This will essentially place the foreground color as far into the octant opposite the background color as possible.
Here is another way to do this, while using only black and white as forecolor:
foreColor = Color.Black;
int changeToWhite = 0;
if(backColor.R <= 128)
{
changeToWhite++;
}
if(backColor.G <= 128)
{
changeToWhite++;
}
if(backColor.B <= 128)
{
changeToWhite++;
}
if(changeToWhite > 1)
{
foreColor = Color.White;
}
Notice the slight adjustment: <=
This ensures the calculated color will be white in cases in some "close calls" you get from the default windows color picker.
This one works perfectly.
gray = ((backColor.R*38 + backColor.G*75 + backColor.B*15) >> 7);
foreColor = gray < 128 ? Color.White : Color.Black;

Resources