in pine-script in DCA strategy between two strategy.entry determining candle range - pine-script-v5

In pine script V5, our DCA strategy is opening long positions by too close candles.
As opening new position after last position, I want to determine the ranges among candles. For instance, after providing ten candles circumstance, it must be able to open new positions.
Waiting for your help..
Best Regards..

You can save to an int (let's say entryIndex) the bar_index when opening a deal, and afterwards check
if (bar_index - entryIndex >= 10)

Related

Using request.security data to use for calculations

I want to achieve the following...
For every candle, I want to calculate the "max range" of the previous x candles.
I then want to use this max range values and compare it with the ATR of the daily timeframe, to get the "max range" value as a percentage of the daily ATR
Point 1, was the easy part and I was able to achieve that with the below code.
// USER INPUTS
iLookBack = input.int(defval = 4, title = "Lookback Period")
// MAX RANGE OF THE LAST x CANDLES
maxRange = math.abs(ta.highest(iLookBack) - ta.lowest(iLookBack))
plot(maxRange, color = color.aqua)
Below a picture of it.
Point 2 is where I got stuck, and where your help is needed.
I tried fetching the daily ATR data using the request.security function
datr = request.security(syminfo.tickerid,"D", ta.atr(14))
On the current day, I get a DATR reading on all candles of the day.
But on the prior day, I only get a DATR reading on the FIRST CANDLE OF THE DAY.
So far so good...
But when using the DATR data and trying to plot the result of the calculation (below) I only get the result of the calculation plotted for the 1st candle of the day.
plot(maxRange/datr)
And the result is looking like this..
This is not what I want..
What I want is, that for every candle, I want to compare the "maxRange" with the DATR reading. And that this result is being plotted.
My guess is, that the data fetched using the request.security function is only valid for ONE candle at the lower timeframe? I'm actually not sure.
I looked up the documentation but couldn't find the answer to my problem..
I hope my problem is clear. And what I'm trying to achieve is making sense to you.
Thank you very much in advance.

Finding strat point when signal become perodic

I am trying to find the Mean of three cycles after the signal become periodic and reach to steady state. I have a signal that is not periodic at the beginning but after some time it became periodic. I want to find the Mean of the next three cycles which each cycle has five points.
Now I did that by opening the plot and find the point where the signal become periodic then I enter that point to MATLAB, then I got the results. The program working fine but I have a big problem. I have 500,000 data records and its impossible to open each one and find the starting point where the signal become periodic. Is there any way that I can find starting point without opening the plot because each case has a different starting point where the signal become periodic?
I used below code now
close all,clear variables,clear all;
clc;
prompt = 'Enter Strating Point?';
N= input(prompt);
Result=mean(mean(1,N:N+4)+mean(1,N+5:N+9)+mean(1,N+10:N+14));
I attached sample of data, Column one is the signal and column two is the time.
https://www.dropbox.com/sh/27lebrp1lwnmm3l/AABIhN1tzUSJQjjED954Yvyka?dl=0
Thank you!
Full edit:
%inputs: time and y (the response), both same length vectors
ppc = 5; % points per cycle
A = zeros(ppc,1);
for i = 1:ppc
A(i) = mean(y(i:ppc:length(y)));
end
[~,b] = min(A);
possidx = (length(time)+b-ppc):-ppc:b; %idx of lowest points
lowlist = fliplr(y(possidx));% lowest points
for i = 2:length(lowlist) %start from behind
se = std(lowlist(1:i))/sqrt(i); %calculate SE for all current points
if se > 0.05 %depending on your filed you might wanna change it to a lower value
periodstart = time(possidx(i-1)); %lowest point of first period
break
end
end
What it does: the first loop finds which group of points is always at the bottom. So adjust ppc to 10 if you have 10 points per cycle. The points per cycle don't have to be exactly the same for each cycle if you have a lot of them, it should still be reasonably accurate.
Then we add from behind one by one these lowest points and calculate the standard error. Once it is greater than 0.05 we are outside of the periods.
I felt so free to use standard error because that is something i know and that makes sense in this situation. I set the threshold to 0.05 because it's standard in many fields, alter it if it is different in your field.

Economic model and hazard damage in matlab

first, i want to say i am relatively new with matlab and so i am not yet very good in it.
I have the variables A,K and L and the constant alpha. Out of this, i want to model the income Y.
Y=A^alpha*K*L;
L changes at a growth rate of 0.09;
dL/dt= rl;
with L population growth; L0 (1950)=500;
I need to model this for 50 years, how can i do this in matlab? so, L has to grow every year, but with the stuff i tried i get always one output value, not 50 values (one for every year): how i have to code this in matlab?
at the moment, I have this, but it gives just the L0*(1+r) for every year
for i = 1:50
dL(i)=(1+r).*L
end
and the growth rate is continuus, but in one year I have due to an event (financial crisis for example) include a population decrease of 7% in one year, for example after year 30. Thereafther, the population will grow at same rate as before. How i can do this in matlab?
thanks for answering.
Actually it works, i had made a mistake by defining the loop from i:50, it must be from n:50

Periodic to incremental (data reduction)

It's some time I was thinking about solving this problem. I have a registration of angular data (Angle(~20000,1)) variating between 0 and 355 (a potentiometer attached to a rotary testing machine), and I wanted to convert it in an incremental form, since I want the final total angular displacement. The main issue is that between 355 and the next 0 there are no jumps but a fast decrement (with strongly negative slope in time vs angle space). I've tried 2 ways up to now:
Calculate the Angslope=diff(Angle), extract with find the indexes j1=find(Angslope>0.2 & Angslope<0.2) to avoid the negative slopes due to the inversion of angular signal, then try to apply those indexes to the original Angle(n,1), as Angle2=Angle(j1). The trouble is the n-1 length of Angslope and the fact that somehow there is not a simple shift of my indexes of one position.
For cycles and logical, wanting to exclude data if the previous one is < the current value,etc
Angle2=zeros(size(Angle,1),1);
for i=2:size(Angle,1)
if Angle(i,1)<Angle(i-1,1)
Angle2(i,1)=NaN;
else Angle2(i,1)=Angle(i,1);
end
end
Which works good, but I don't know how to "match up" the single increment steps I obtain!
Any help or simple comment would be of great help!!
You are probably looking for the unwrap function. For this you have to convert your angles into radians, but that's not a big deal.
You can get the increments in one line:
Inc = diff(unwrap(Angle*pi/180))*180/pi;
and your total angular displacement:
Tot = sum(Inc);
Best,

recording 'bursts' of samples at 300 samples per sec

I am recording voltage changes over a small circuit- this records mouse feeding. When the mouse is eating, the circuit voltage changes, I convert that into ones and zeroes, all is well.
BUT- I want to calculate the number and duration of 'bursts' of feeding- that is, instances of circuit closing that occur within 250 ms (75 samples) of one another. If the gap between closings is larger than 250ms I want to count it as a new 'burst'
I guess I am looking for help in asking matlab to compare the sample number of each 1 in the digital file with the sample number of the next 1 down- if the difference is more than 75, call the first 1 the end of one bout and the second one the start of another bout, classifying the difference as a gap, but if it is NOT, keep the sample number of the first 1 and compare it against the next and next and next until there is a 75-sample difference
I can compare each 1 to the next 1 down:
n=1; m=2;
for i = 1:length(bouts4)-1
if bouts4(i+1) - bouts4(i) >= 75 %250 msec gap at a sample rate of 300
boutend4(n) = bouts4(i);
boutstart4(m)= bouts4(i+1);
m = m+1;
n = n+1;
end
I don't really want to iterate through i for both variables though...
any ideas??
-DB
You can try the following code
time_diff = diff(bouts4);
new_feeding = time_diff > 75;
boutend4 = bouts4(new_feeding);
boutstart4 = [0; bouts4(find(new_feeding) + 1)];
That's actually not too bad. We can actually make this completely vectorized. First, let's start with two signals:
A version of your voltages untouched
A version of your voltages that is shifted in time by 1 step (i.e. it starts at time index = 2).
Now the basic algorithm is really:
Go through each element and see if the difference is above a threshold (in your case 75).
Enumerate the locations of each one in separate arrays
Now onto the code!
%// Make those signals
bout4a = bouts4(1:end-1);
bout4b = bouts4(2:end);
%// Ensure column vectors - you'll see why soon
bout4a = bout4a(:);
bout4b = bout4b(:);
% // Step #1
loc = find(bouts4b - bouts4a >= 75);
% // Step #2
boutend4 = [bouts4(loc); 0];
boutstart4 = [0; bouts4(loc + 1)];
Aside:
Thanks to tail.b.lo, you can also use diff. It basically performs that difference operation with the copying of those vectors like I did before. diff basically works the same way. However, I decided not to use it so you can see how exactly your code that you wrote translates over in a vectorized way. Only way to learn, right?
Back to it!
Let's step through this slowly. The first two lines of code make those signals I was talking about. An original one (up to length(bouts) - 1) and another one that is the same length but shifted over by one time index. Next, we use find to find those time slots where the time index was >= 75. After, we use these locations to access the bouts array. The ending array accesses the original array while the starting array accesses the same locations but moved over by one time index.
The reason why we need to make these two signals column vector is the way I am appending information to the starting vector. I am not sure whether your data comes in rows or columns, so to make this completely independent of orientation, I'm going to make sure that your data is in columns. This is because if I try to append a 0, if I do it to a row vector I have to use a space to denote that I'm going to the next column. If I do it for a column vector, I have to use a semi-colon to go to the next row. To completely avoid checking to see whether it's a row or column vector, I'm going to make sure that it's a column vector no matter what.
By looking at your code m=2. This means that when you start writing into this array, the first location is 0. As such, I've artificially placed a 0 at the beginning of this array and followed that up with the rest of the values.
Hope this helps!