How to access the last indicator values - pivot

I've got an indicator which shows pivot points:
//#version=4
study("Trend", overlay=false)
leftBars = input(3)
rightBars = input(3)
ph = pivothigh(high, leftBars, rightBars)
pl = pivotlow(low, leftBars, rightBars)
How can I check if the last ph was higher than the ph before? (I'd like to check for an uptrend or downtrend)

You can try the following code (including your original, as you see):
//#version=4
study("Trend", overlay=false)
leftBars = input(3)
rightBars = input(3)
ph = pivothigh(high, leftBars, rightBars)
pl = pivotlow(low, leftBars, rightBars)
//INIT VARIABLES
var int ph_uptrend_flag = 0
var float ph_valid = 0
var float ph_valid_old = 1e99 // use any very high non meaningful number here for initialization only
ph_non_na = nz(ph,0) // stores 0's instead of na's for non-pivot-pointed bars
// re-calculate uptrend flag every time a new pivot comes in, otherwise keep last known value for uptrend flag
if ph_non_na != 0
ph_valid := ph_non_na
ph_uptrend_flag := ph_valid > ph_valid_old ? 1 : 0
ph_valid_old := ph_valid
else
ph_valid := ph_valid
ph_valid_old := ph_valid_old
//plot uptrend flag and mark background accordingly
plot(ph_uptrend_flag,title="ph uptrend indication",linewidth=4,color=color.white)
//plot(ph,title="ph value",color=color.lime,style=8) //plot ph values (better used with overlay=true)

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

Draw line below/above line.new

Here is a script i'm using for detecting pivot point.
I'd like to draw a line at the close of the new detected pivot point, each time new pivot point are detected (and deleting other lines)
i try to change the line.new value to get the "close" but it didn't work
See the picture below, the blue lines i draw is what i'm searching to do :D
enter image description here
indicator("Pivot Points", overlay=true)
// Get user input
var devTooltip = "Deviation is a multiplier that affects how much the price should deviate from the previous pivot in order for the bar to become a new pivot."
var depthTooltip = "The minimum number of bars that will be taken into account when analyzing pivots."
threshold_multiplier = input.float(title="Deviation", defval=2.5, minval=0, tooltip=devTooltip)
depth = input.int(title="Depth", defval=10, minval=1, tooltip=depthTooltip)
deleteLastLine = input.bool(title="Delete Last Line", defval=false)
bgcolorChange = input.bool(title="Change BgColor", defval=false)
// Calculate deviation threshold for identifying major swings
dev_threshold = ta.atr(10) / close * 100 * threshold_multiplier
// Prepare pivot variables
var line lineLast = na
var int iLast = 0 // Index last
var int iPrev = 0 // Index previous
var float pLast = 0 // Price last
var isHighLast = false // If false then the last pivot was a pivot low
// Custom function for detecting pivot points (and returning price + bar index)
pivots(src, length, isHigh) =>
l2 = length * 2
c = nz(src[length])
ok = true
for i = 0 to l2
if isHigh and src[i] > c // If isHigh, validate pivot high
ok := false
if not isHigh and src[i] < c // If not isHigh, validate pivot low
ok := false
if ok // If pivot is valid, return bar index + high price value
[bar_index[length], c]
else // If pivot is invalid, return na
[int(na), float(na)]
// Get bar index & price high/low for current pivots
[iH, pH] = pivots(high, depth / 2, true)
[iL, pL] = pivots(low, depth / 2, false)
// Custom function for calculating price deviation for validating large moves
calc_dev(base_price, price) => 100 * (price - base_price) / price
// Custom function for detecting pivots that meet our deviation criteria
pivotFound(dev, isHigh, index, price) =>
if isHighLast == isHigh and not na(lineLast) // Check bull/bear direction of new pivot
// New pivot in same direction as last (a pivot high), so update line upwards (ie. trend-continuation)
if isHighLast ? price > pLast : price < pLast // If new pivot is above last pivot, update line
line.set_xy2(lineLast, index, price)
[lineLast, isHighLast]
else
[line(na), bool(na)] // New pivot is not above last pivot, so don't update the line
else // Reverse the trend/pivot direction (or create the very first line if lineLast is na)
if math.abs(dev) > dev_threshold
// Price move is significant - create a new line between the pivot points
id = line.new(iLast, pLast, index, price, color=color.gray, width=1, style=line.style_dashed)
[id, isHigh]
else
[line(na), bool(na)]
// If bar index for current pivot high is not NA (ie. we have a new pivot):
if not na(iH)
dev = calc_dev(pLast, pH) // Calculate the deviation from last pivot
[id, isHigh] = pivotFound(dev, true, iH, pH) // Pass the current pivot high into pivotFound() for validation & line update
if not na(id) // If the line has been updated, update price & index values and delete previous line
if id != lineLast and deleteLastLine
line.delete(lineLast)
lineLast := id
isHighLast := isHigh
iPrev := iLast
iLast := iH
pLast := pH
else
if not na(iL) // If bar index for current pivot low is not NA (ie. we have a new pivot):
dev = calc_dev(pLast, pL) // Calculate the deviation from last pivot
[id, isHigh] = pivotFound(dev, false, iL, pL) // Pass the current pivot low into pivotFound() for validation & line update
if not na(id) // If the line has been updated, update price values and delete previous line
if id != lineLast and deleteLastLine
line.delete(lineLast)
lineLast := id
isHighLast := isHigh
iPrev := iLast
iLast := iL
pLast := pL
**// Get starting and ending high/low price of the current pivot line
startIndex = line.get_x1(lineLast)
startPrice = line.get_y1(lineLast)
endIndex = line.get_x2(lineLast)
endPrice = line.get_y2(lineLast)
// Draw top & bottom of impulsive move
topLine = line.new(startIndex, startPrice, endIndex, startPrice, extend=extend.right, color=color.red)
bottomline = line.new(startIndex, endPrice, endIndex, endPrice, extend=extend.right, color=color.green)
line.delete(topLine[1])
line.delete(bottomline[1])**
//plot(startPrice, color=color.green)
//plot(endPrice, color=color.red)
// Do what you like with these pivot values :)
// Keep in mind there will be an X bar delay between pivot price values updating based on Depth setting
dist = math.abs(startPrice - endPrice)
plot(dist, color=color.new(color.purple,100))
bullish = endPrice > startPrice
offsetBG = -(depth / 2)
bgcolor(bgcolorChange ? bullish ? color.new(color.green,90) : color.new(color.red,90) : na, offset=offsetBG)
Thank you
Changing the code
**// Get starting and ending high/low price of the current pivot line
startIndex = line.get_x1(lineLast)
startPrice = line.get_y1(lineLast)
endIndex = line.get_x2(lineLast)
endPrice = line.get_y2(lineLast)
// Draw top & bottom of impulsive move
topLine = line.new(startIndex, startPrice, endIndex, startPrice, extend=extend.right, color=color.red)
bottomline = line.new(startIndex, endPrice, endIndex, endPrice, extend=extend.right, color=color.green)
line.delete(topLine[1])
line.delete(bottomline[1])**

Pinescript/TradingView: Set max pyramiding (multiple stacked entries of the same direction) but greater than 1

I'm writing a study (not a strategy) with alerts on the lower 5-min TF that allow for multiple entries (and a single close) of the same direction. Ideally, a max of 3 longs or 3 shorts before closing, or otherwise keep waiting for opposite entry or a close. (note I am not looking for code that limits to 1 entry/exit at a time). This is what I have thus far from what web research has suggested, but for some reason it doesn't seem to work (in my charts, plots appear very sparingly) -- I think I have pinpointed it to the security() function condition based on a higher TF data. When isolating the pyramiding by itself, it seems fine. When isolating the security function to check whether the data is being passed in, it plots fine. Please let me know if there is an alternative max-pyramiding logic or how to get it working with the higher TF data. Thanks in advance, any help appreciated.
// == ORDER CONDITIONS ==
longCond = security(tickerid,'60',someHFCond1)
shortCond = security(tickerid,'60',someHFCond2)
// Count your long short conditions for more control with Pyramiding
sectionLongs = 0
sectionLongs := nz(sectionLongs[1])
sectionShorts = 0
sectionShorts := nz(sectionShorts[1])
if longCond
sectionLongs := sectionLongs + 1
sectionShorts := 0
if shortCond
sectionLongs := 0
sectionShorts := sectionShorts + 1
// Pyramiding
pyrl = input(3,title="Max Pyramiding (stackable entries, default=3)",minval=1)
longCondition = longCond and sectionLongs <= pyrl
shortCondition = shortCond and sectionShorts <= pyrl
// Get the price of the last opened long or short
last_open_longCondition = na
last_open_shortCondition = na
last_open_longCondition := longCondition ? close : nz(last_open_longCondition[1])
last_open_shortCondition := shortCondition ? close : nz(last_open_shortCondition[1])
// Check if your last position was a long or a short
last_longCondition = na
last_shortCondition = na
last_longCondition := longCondition ? time : nz(last_longCondition[1])
last_shortCondition := shortCondition ? time : nz(last_shortCondition[1])
in_longCondition = last_longCondition > last_shortCondition
in_shortCondition = last_shortCondition > last_longCondition
// Take profit
Ltakeprofit = last_open_longCondition * (1+profittarget)
Stakeprofit = last_open_shortCondition * (1-profittarget)
long_tp = high[1] > Ltakeprofit and longCondition == 0 and in_longCondition == 1 and not longCondition[1]
short_tp = low[1] < Stakeprofit and shortCondition == 0 and in_shortCondition == 1 and not shortCondition[1]
// Create a single close for all the different closing conditions.
long_close = long_tp or long_sl ? 1 : 0
short_close = short_tp or short_sl ? 1 : 0
// Get the time of the last close
last_long_close = na
last_long_close := long_close ? time : nz(last_long_close[1])
last_short_close = na
last_short_close := short_close ? time : nz(last_short_close[1])
// Alerts & Signals
bton(b) => b ? 1 : 0
plotshape(longCondition , title="buy alert", color=green, textcolor=green, transp=0,
style=shape.triangleup, location=location.belowbar, size=size.small,text="LONG",offset=0)
plotshape(shortCondition, title="sell alert", color=red, textcolor=red, transp=0,
style=shape.triangledown, location=location.abovebar, size=size.small,text="SHORT",offset=0)
plotshape(long_tp and last_longCondition > nz(last_long_close[1]), text ="Close", title="Take Profit Long", style=shape.triangledown,
location=location.abovebar, color = green, size=size.tiny, editable = false, transp = 0,offset=0)
plotshape(short_tp and last_shortCondition > nz(last_short_close[1]) , text ="Cover", title="Take Profit Short", style=shape.triangleup,
location=location.belowbar, color = red, size=size.tiny, editable = false, transp = 0,offset=0)
This shows your pyramiding control working just fine:
//#version=4
study("", "", true)
// == ORDER CONDITIONS ==
barUp = close > open
longCond = barUp and barUp[1]
shortCond = not barUp and not barUp[1]
// Count your long short conditions for more control with Pyramiding
sectionLongs = 0
sectionLongs := nz(sectionLongs[1])
sectionShorts = 0
sectionShorts := nz(sectionShorts[1])
if longCond
sectionLongs := sectionLongs + 1
sectionShorts := 0
label.new(bar_index, low - tr, tostring(sectionLongs, "▲\n#"), xloc.bar_index, yloc.price, color.green, label.style_none, color.green, size.large)
if shortCond
sectionLongs := 0
sectionShorts := sectionShorts + 1
label.new(bar_index, na, tostring(sectionShorts, "#\n▼"), xloc.bar_index, yloc.abovebar, color.maroon, label.style_none, color.maroon, size.large)
// Pyramiding
pyrl = input(3,title="Max Pyramiding (stackable entries, default=3)",minval=1)
longCondition = longCond and sectionLongs <= pyrl
shortCondition = shortCond and sectionShorts <= pyrl
bgcolor(longCondition ? color.lime : shortCondition ? color.red : na)
plotchar(sectionLongs, "sectionLongs", "", location.top)
plotchar(sectionShorts, "sectionShorts", "", location.top)

Variable issue in GameMaker 2

Making a game in GameMaker and I'm having a problem where the variable is not set and I'm not sure why. When pressing down on either W,A,S, or D and clicking LMB it works but crashes if I pressing down on W,A,S, or D then let go and afterwards click LMB.
Code:
var look
var bullet
if (keyboard_check(ord("A"))){
x = x - 5;
sprite_index = spr_west_hiro
image_xscale = 3
image_yscale = 3
look = 180
} else if (keyboard_check(ord("D"))){
x = x + 5;
sprite_index = spr_east_hiro
image_xscale = 3
image_yscale = 3
look = 0
} else if (keyboard_check(ord("S"))){
y = y + 5;
sprite_index = spr_south_hiro
image_xscale = 3
image_yscale = 3
look = 270
} else if (keyboard_check(ord("W"))){
y = y - 5;
sprite_index = spr_north_hiro
image_xscale = 3
image_yscale = 3
look = 90
}
//------------------------------------------------------------------------------
if (keyboard_check_released(ord("A"))){
sprite_index = spr_idlewest_hiro
image_xscale = 3
image_yscale = 3
look = 180
} else if (keyboard_check_released(ord("D"))){
sprite_index = spr_idleast_hiro
image_xscale = 3
image_yscale = 3
look = 0
} else if (keyboard_check_released(ord("S"))){
sprite_index = spr_idlesouth_hiro
image_xscale = 3
image_yscale = 3
look = 270
} else if (keyboard_check_released(ord("W"))){
sprite_index = spr_idlenorth_hiro
image_xscale = 3
image_yscale = 3
look = 90
}
//--------------------------------------------------------------------------------
if (mouse_check_button_pressed(mb_left)){
var bullet = instance_create_layer(x,y, "Instances", obj_bullet)
bullet.direction = look
}
Error:
ERROR!!! :: ############################################################################################
FATAL ERROR in
action number 1
of Step Event0
for object obj_hiro:
local variable look(100001, -2147483648) not set before reading it.
at gml_Object_obj_hiro_Step_0 (line 61) - bullet.direction = look
############################################################################################
--------------------------------------------------------------------------------------------
stack frame is
gml_Object_obj_hiro_Step_0 (line 61)
I have reviewed the code multiple times and I am still stumped. Particularly because of the fact that it seems as though the variable doesn't save the coefficient set to it despite the fact that it should when W,A,S or D is pressed down then released.
Firstly, you would want to assign a value to your look variable, as otherwise it will remain not set to anything if no buttons had been pressed.
Secondly, you may want to do so in Create event, as you probably want your character to shoot in last pressed direction, not just "somewhere"

Updating a string inside a callback

The following code is a graphic rendering of the Earth globe spinning eastward. I have two push buttons, Spin and Stop. Both share the same callback function, hAnimaCallback. In particular, this latter does not work. I pretend to use the strings (names) of the push buttons to create a switch that stops the movement. However, I can not get to change the string name inside the while loop and I do not understand why my method is wrong.
function example
fh = figure('Menu','none','Toolbar','none','Units','characters');
T = 0:pi/100:2*pi;
Y = zeros(numel(T),3);
Y(:,1) = 7000*cos(T);
Y(:,2) = 7000*sin(T);
hPanAni = uipanel('parent',fh,'Units','characters','Position',...
[22.6 10.4 53 23],'title','Controls','FontSize',11,...
'FontAngle','italic','FontWeight','bold');
hIniAni = uicontrol(hPanAni,'Style','pushbutton','Units','normalized',...
'Position',[0.14 0.64 0.5 0.12],'String','Spin',...
'FontSize',10,'Callback',#hAnimaCallback);
hFinAni = uicontrol(hPanAni,'Style','pushbutton','Units','normalized',...
'Position',[0.14 0.26 0.5 0.12],'String','Stop',...
'FontSize',10,'Callback',#hAnimaCallback);
hPantSim = uipanel('Parent',fh,'Units','characters',...
'Position',[107.87 8 157.447 42],'BorderType','none','title',...
'Screen','FontSize',11,'FontAngle','italic',...
'FontWeight','bold');
hPantSimInt = uipanel('Parent',hPantSim,'Units','normalized','Position',...
[0 0 1 1],'BorderType','line','BackgroundColor','black');
ah4 = axes('Parent',hPantSimInt,'Units','normalized','Position',...
[0 0 1 1],'Color','none','Visible','off','DataAspectRatio',...
[1 1 1],'NextPlot','add');
rotate3d(ah4);
hgrot = hgtransform('Parent',ah4);
Resf = 6378;
maptext = imread('tierra.jpg');
[X, map] = rgb2ind(maptext,128);
[x,y,z] = sphere(50);
x = Resf*x;
y = Resf*y;
z = Resf*z;
props.FaceColor= 'texture';
props.EdgeColor = 'none';
props.Parent = hgrot;
props.Cdata = flipud(X); % it is necesary to do this for getting the
% appropiate image on the sphere
hsurf = surface(x,y,z,props);
colormap(map);
axis equal;
view([71 14]);
set(gcf,'Renderer','opengl')
drawnow;
line('parent',ah4,'XData',Y(:,1),'YData',Y(:,2),'ZData',...
Y(:,3),'Color','red','LineWidth',2);
line('parent',ah4,'XData',Y(end,1),'YData',Y(end,2),...
'ZData',Y(end,3),'Marker','o','MarkerSize',6,'MarkerFaceColor','b');
axis square equal vis3d;
view(3);
handles.XLim = get(ah4,'XLim');
handles.YLim = get(ah4,'YLim');
handles.ZLim = get(ah4,'ZLim');
xmin = handles.XLim(1);
ymin = handles.YLim(1);
zmin = handles.ZLim(1);
xmax = handles.XLim(2);
ymax = handles.YLim(2);
zmax = handles.ZLim(2);
set(ah4, 'XLim', [xmin xmax],'YLim', [ymin ymax],'Zlim',[zmin zmax]);
az = 0;
function hAnimaCallback(hObject,evt)
while (ishandle(fh))
state = get(hObject,'String'), % state should change between the states of
% Spin and Stop but this does not occur
if (strcmp(state,'Stop'))
break;
else
az = az + 0.01745329252;
set(hgrot,'Matrix',makehgtform('zrotate',az));
drawnow;
end
end
end
end
It seems like you are running into some kind of race condition because of the repeated drawnow calls in the while loop. The state changes to Stop, when you press the Stop button, but it is to quick to notice. Basically, the while loop is running as fast as MATLAB can run. Instead of drawnow using a pause(0.1) command seems to work (with a little bit code logic changes):
az = 0;
spin = false;
function hAnimaCallback(hObject,~)
state = get(hObject,'String')
if strcmp(state, 'Spin')
spin = true;
else
spin = false;
end
while (spin)
az = az + 0.01745329252;
set(hgrot,'Matrix',makehgtform('zrotate',az));
pause(0.1);
end
end

Resources