Creating Moving Average crossover in TradingView Pine Editor - algorithmic-trading

i want to create a pine script in trading view for a moving average crossover between a EMA of length 5 and SMMA (Smoothed Moving Average) of length 7
I was able to create for the 5 EMA but couldnt find how to input the smoothed moving average(SMMA). I was only able to input SImple moving Average (SMA) and not SMMA

Smoothed Moving Average (SMMA) is included in the Bullit-in script library
This:
//#version=5
indicator(title="Smoothed Moving Average", shorttitle="SMMA", overlay=true, timeframe="", timeframe_gaps=true)
len = input.int(7, minval=1, title="Length")
src = input(close, title="Source")
smma = 0.0
smma := na(smma[1]) ? ta.sma(src, len) : (smma[1] * (len - 1) + src) / len
plot(smma, color=#673AB7)
Here are recommendations on how to adapt a Bullit-in script
https://www.tradingview.com/script/J8kODTBn-Adapting-a-built-in-PineCoders/

Related

omega-k algorithm simulation in matlab

I want to simulate omega k algorithm to focus synthetic aperture radar raw data based on cumming's book, "Digital Processing of Synthetic Aperture Radar Data". First I simulated point target raw data in stripmap mode and do everything which is mentioned in the book. But my target doesn't focused. To make sure my raw data is made truly, I focused it with conventional RDA algorithm and my point target focused in true position which means that my raw data simulation routine is Ok.
Here is my matlab code for omega k algorithm:
%% __________________________________________________________________________
fr = linspace(-fs/2,fs/2,nfftr);
faz = linspace(-PRF/2,PRF/2,nffta);
fr_prime = sqrt((f0+fr).^2-(c*faz'/(2*vp)).^2)-f0;
Rref = rs(ceil(Ns/2));
theta_ref = 4*pi*Rref/c*(fr_prime+f0)+pi*fr.^2/kr;
%2D FFT
S_raw = fftshift(fft2(s_raw,nffta,nfftr));
%RFM
S_BC = S_raw.*exp(1j*theta_ref);
for idx = 1:Na
S_int(idx,:) = interp1(fr_prime(idx,:)+f0,S_BC(idx,:),fr+f0,'pchip');
end
S_c = S_int.*exp(-1j*4*pi*fr*Rref/c);
s_c = ifft2(S_c,Na,Nr);
%% __________________________________________________________________________
in this code:
f0 : center frequency
kr : Chirp Rate in Range
fs : Sampling frequency in range
vp : platform velocity
rs : range array (form near range to far range)
Rref : Reference range (Hear I take it as middle range cell)
Ns : number of range cells
Na : number of samples in Azimuth
s_c : Focused Image
three targets are positioned at [10 , Ns/2 , Ns-10] in range and Na/2 in azimuth.
here is my results:
Data after Bulk Compression in Time Domain
Data after stolt Interpolation in Time Domain
I examined several interpolation methods like sinc interp , linear interp , pchip and others, but non of them worked for me.
I appreciate everyone who could help me and tell me whats my mistake...
thank you...
In the accurate version of Omega-k, Cumming did not ask to multiply with a matched filter again after stolt interpolation. The focusing should be complete just with a 2D iFFT.

MATLAB image distinction/comparison

I have 1024 images, each of which has the size 150(y) x 270(x) which is stored as 3D array with the size of 150 x 270 x 1024
First 160 images are very similar to each other but not entirely identical;
however, after 160th image, pictures start to change drastically.
So, here is what I want to achieve:
I want to find the index of the image from which the images start to drastically change
I have tried to compare correlation between image #1 and other 1023 images by:
for ii = 1:1023
R(ii) = corr2(input(:,:,1),input(:,:,ii+1)); % input = 3D array (150 x 270 x 1024)
end
and see if there is any change in correlation coefficient at around 160th image, but wasn't successful.
What method can I use to detect changes in these images and to find the index at which my images start to change dramatically?
EDIT
following are some of the images I have (index in the title)
I guess the change is not as dramatic as I first described and when you look at image 160 and 161, the change is subtle but as it goes on, you can clearly see that the image definitely changes at the bottom part
These images are results of ultrasonic testing and wave propagation from PZT sensor starts at the bottom part of the image
Probably, this is not a full answer to your problem, but I hope I can give you some ideas to further work on. But before, I have to mention this: Image processing is two-dimensional signal processing! ;-)
After reading your question the 34th time (or so), I finally saw, that you're comparing "image" #1 with all others. Instead, you should compare neighbouring "images". I have put together the following script incorporating your approach of using corr2:
load('fullSet.mat');
%% Normalize values to [0, 1] with respect to whole volume.
%% Just for nicer image showing.
%minV = min(fullSet(:));
%fullSet = fullSet - minV;
%maxV = max(fullSet(:));
%fullSet = fullSet / maxV;
% Determine number of "images".
n = size(fullSet, 3);
% "Step size".
s = 1;
% Initialize R.
R = zeros(n-s, 1);
% Compute correlation coefficients.
for ii = 1:n-s
R(ii) = corr2(fullSet(:, :, ii), fullSet(:, :, ii + s));
end
% Show output.
figure(1);
subplot(3, 1, 1);
plot(1:n-s, R);
title('R');
xlim([0 n-s]);
subplot(3, 1, 2);
plot(1:n-s-1, diff(R, 1));
title('1st derivative of R');
xlim([0 n-s-1]);
subplot(3, 1, 3);
plot(1:n-s-2, diff(R, 2));
title('2nd derivative of R');
xlim([0 n-s-2]);
The "step size" defines which "image" should be compared to the current one, i.e. s = 1 is used to compare the current "image" with the next "image", s = 2 is used to compare the current "image" with the second-next "image", and so on.
The results for s = 1:
The results for s = 5:
The results for s = 10:
As you can see, there is a distinct change around [160, 200]. I also computed the 1st and 2nd derivatives, because here you can also see changes later in your "volume" - if this is of interest for you.
Please let me know, if you need further explanations on my script or if you need further help in general.

Calculating the speed of a moving object based on its distance to a target

I am writing a simulation in which an object moves in a 2D world towards a target position, stored as vector target(x,y). The object position is stored as position vector pos(x,y) as well. The object contains two more vectors, the desired movement velocity dv(x,y), as well as the current movement velocity cv(x,y). At the start of the simulation both these velocity vectors are initial, i.e. set to (0,0).
When the object should move towards the target position, I calcuate the desired velocity vector dv, normalize it, and scale it by a movement speed value:
dv.set(target).sub(pos).normalize()
dv.scale(speed)
I want to make the movement look more realistic, that's why I use two velocity vectors. dv tells the full speed I want to move the object, and cv holds the real speed the object currently moves at.
Then at each frame (update step) the current velocity cv is set based on the desired velocity dv and an acceleration value acc. This is done by simply calculating the difference between cv and dv and clamping this difference to acc. That way the object starts to move slowly and accelerates gradually to eventually reach full speed.
So far this is working fine. Now I want to make use of acc for deceleration as well. When the distance between pos and target is at a certain value, the desired velocity dv should be set to (0,0), so that the object gradually decelerates until it comes to a full stop at the target position.
My question is: How can I calculate at which distance I need to set dv to (0,0) (i.e. tell the system to stop movement), so that the object decelerates correctly to stop exactly at the target position?
Use the kinematic equations:
vf2 = vi2 + 2 * a * d
vf is your final velocity, or 0 (the speed you want to be going)
vi is your initial velocity, given (the speed your object is currently moving).
a is acceleration
d is distance.
Solve for d:
2*a*d = vf2 - vi2
2*a*d = 0 - vi2
assume acceleration is negative, so multiply both sides by -1
2*|a|*d = vi2
|a| is the absolute value of your acceleration (deceleration in your case)
d = vi2 / (2*|a|)
You're doing a discrete time simulation of motion. One way to keep things simple is to perform the calculations in a way that makes acceleration and deceleration symmetrical. In other words, the distance traveled while accelerating should be the same as the distance traveled while decelerating. As an example, assume
acceleration is 5
top speed is 13
the object begins decelerating as soon as it reaches top speed
Here's how the discrete time simulation would progress
first tick
old speed = 0
new speed = 5
distance = 5
second tick
old speed = 5
new speed = 10
distance = 15
third tick
old speed = 10
new speed = 13
distance = 28 <-- total distance while accelerating
fourth tick
old speed = 13
distance = 41
new speed = 10 <-- not 8!!!
fifth tick
old speed = 10
distance = 51
new speed = 5
sixth tick
old speed = 5
distance = 56 <-- Yay, twice the distance, we have symmetry
new speed = 0
There are two key points here
While accelerating the speed is updated first and then the distance is updated. While decelerating the order is reversed, the distance is updated first, and then the speed.
When decelerating, it's important to keep the adjusted speed as a multiple of the acceleration
In the C programming language, the following code could be used to update the speed during deceleration
if ( old_speed % acceleration != 0 ) // if speed is not a multiple of acceleration
new_speed = old_speed - old_speed % acceleration; // reduce speed to a multiple of acceleration
else // otherwise
new_speed = old_speed - acceleration; // reduce speed by acceleration
If acceleration and deceleration are symmetrical, then computing the deceleration distance is the same as computing the acceleration distance.
distance = acceleration * (1+2+3+ ... +N) + fudge_factor
where
N is top_speed / acceleration truncated to an integer, e.g. 13/5 ==> 2
fudge_factor is 0 if top speed is a multiple of acceleration, or
top_speed otherwise
The computation can be simplified by noting that
1+2+3+ ... +N = N * (N+1) / 2
In C, the total distance travelled while decelerating could be computed as follows
int top_speed = 13;
int acceleration = 5;
int N = top_speed / acceleration; // Note: in C, integer division truncates
int fudge = 0;
if ( top_speed % acceleration != 0 )
fudge = top_speed;
int distance = acceleration * (N * (N+1)) / 2 + fudge;

Ideas for algorithm to generate random flower

Can anyone suggest any links, ideas or algorithms to generate flowers randomly like the one as my profile pic? The profile pic flower has only a 10 x 10 grid and the algorithm is not truly random. I would also prefer that the new algorithm use a grid of about 500 x 500 or even better, allow the user to pick the size of the grid.
[Plant[][] is declared as int plant[10][10];]
public void generateSimpleSky(){
for(int w2=0;w2<10;w2++)
for(int w3=0;w3<10;w3++)
plant[w2][w3]=5;
}
public void generateSimpleSoil(){
for(int q=0;q<10;q++)
plant[q][9]=1;
}
public void generateSimpleStem(){
int ry=rand.nextInt(4);
plant[3+ry][8]=4;
xr=3+ry;
for(int u=7;u>1;u--){
int yu=rand.nextInt(3);
plant[xr-1+yu][u]=4;
xr=xr-1+yu;
}
}
public void generateSimpleFlower(){
plant[xr][2]=3;
for(int q2=1;q2<4;q2++)
if((2-q2)!=0)
plant[xr][q2]=2;
for(int q3=xr-1;q3<=xr+1;q3++)
if((xr-q3)!=0)
plant[q3][2]=2;
}
It sounds like a reasonably simple problem where you just generate 1 parameter at a time, possibly based on the output of the previous variables.
My model of a flower will be: It has just a reasonably upright stem, a perfectly round center, some amount of leaves on the stem on alternating sides, petals perfectly distributed around the center.
random() is just a random number within some chosen bounds, the bounds may be unique for each variable. random(x1, x2, ..., xn) generates a random number within some bounds dependent on the variables x1, x2, ..., xn (as in stemWidth < stemHeight/2, a reasonable assumption).
The Stem
stemXPosition = width / 2
stemHeight = random()
stemWidth = random(stemHeight)
stemColour = randomColour()
stemWidthVariationMax = random(stemWidth, stemHeight)
stemWidthVariationPerPixel = random(stemWidth, stemHeight)
stemWidthVariationMax/-PerPixel are for generating a stem that isn't perfectly straight (if you want to do something that complicated, a low PerPixel is for smoothness). Generate the stem using these as follows:
pixelRelative[y-position][0] := left x-position at that y-position relative to the stem
pixelRelative[y-position][1] := right x-position at that y-position relative to the stem
pixelRelative[0][0] = randomInRange(-stemWidthVariationMax, stemWidthVariationMax)
for each y > 0:
pixelRelative[y-1][0] = max(min(randomInRange(pixel[y] - stemWidthVariationPerPixel,
pixel[y] + stemWidthVariationPerPixel),
-stemWidthVariationMax),
stemWidthVariationMax)
//pixelRelative[0][1] and pixelRelative[y-1][1] generated same as pixelRelative[y-1][i]
for each y:
pixelAbsolute[y][0] = width / 2 - stemWidth / 2 + pixelRelative[y][0]
pixelAbsolute[y][1] = width / 2 + stemWidth / 2 + pixelRelative[y][1]
You can also use arcs to simplify things and go more than 1 pixel at a time.
The Top
centerRadius = random(stemHeight)
petalCount = random() // probably >= 3
petalSize = random(centerRadius, petalCount)
It's not too easy to generate the petals, you need to step from 0 to 2*PI with step-size of 2*PI/petalCount and generate arcs around the circle. It requires either a good graphics API or some decent maths.
Here's some nicely generated tops of flowers, though seemingly not open-source. Note that they don't have a center at all. (or centerRadius = 0)
The Leaves
You could probably write an entire paper on this, (like this one) but a simple idea would just be to generate a 1/2 circle and extend lines outward from there to meet at 2*the radius of the circle and to draw parallel lines on the flower.
Once you have a leaf generation algorithm:
leafSize = random(stemHeight) // either all leaves are the same size or generate the size for each randomly
leafStemLength = random(leafSize) // either all leaves have the same stem length or generate for each randomly
leafStemWidth = random(leafStemLength)
leaf[0].YPosition = random(stemHeight)
leaf[0].XSide = randomly either left or right
leaf[0].rotation = random between say 0 and 80 degrees
for each leaf i:
leaf[i].YPosition = random(stemHeight, leaf[i-1]) // only generate new leaves above previous leaves
leaf[i].XSide = opposite of leaf[i].XSide
Last words
The way to determine the bounds of each random would be either to argue it out, or give it some fixed value, generate everything else randomly a few times, keep increasing / decreasing it until it starts to look weird.
10 x 10 versus 500 x 500 would probably require greatly different algorithms, I wouldn't recommend the above for below 100 x 100, maybe generate a bigger image and simply shrink it using averaging or something.
Code
I started writing some Java code, when I realised it may take a bit longer than I would like to spend on this, so I'll show you what I have so far.
// some other code, including these functions to generate random numbers:
float nextFloat(float rangeStart, float rangeEnd);
int nextInt(int rangeStart, int rangeEnd);
...
// generates a color somewhere between green and brown
Color stemColor = Color.getHSBColor(nextFloat(0.1, 0.2), nextFloat(0.5, 1), nextFloat(0.2, 0.8));
int stemHeight = nextInt(height/2, 3*height/4);
int stemWidth = nextInt(height/20, height/20 + height/5);
Color flowerColor = ??? // I just couldn't use the same method as above to generate bright colors, but I'm sure it's not too difficult
int flowerRadius = nextInt(Math.min(stemHeight, height - stemHeight)/4, 3*Math.min(stemHeight, height - stemHeight)/4);

Movement algorithm for game

I'm currently developing a script for a map in COD4. I think that the language is so simple that I'm tagging this as language-agnostic since the problem is in the algorithm for this situation.
There is a room which is 960 units wide. And inside it there's an object in the middle, which we'll count as the axis. The ball is supposed to move to a random position each time it is hit, but should not traverse further than the walls. Here's a diagram:
The API of the game only allows the moving of objects relative to its position, as far as I know, so here's code that I came up with. The problem is that after the second call to head_move() it begins to produce unexpected results and this is crashing my head. Could somebody help me out?
movementThink():
while (1)
{
self waittill ("trigger", player); //Wait till player hits the object
head_origin thread head_move();
}
head_move()
{
/* level.prevx is a global variable which I use to store
the distance traveled in the previous shot. Defaults to 0 */
/*This works in the first and second hit, but then it begins to show
incorrect max and min values*/
x_min = (0-480) + level.prevx;
x_max = x_min + 960;
x_units = RandomIntRange( x_min, x_max ); //Create a random integrer
log2screen("MIN: " + x_min + " and MAX: " + x_max + " and MOVED " + x_units);
log2screen("Moved " + x_units);
//Movement function, first parameter is the distance to be traveled, and the second one is the speed
self movex (x_units , level.movespeed);
level.prevx = x_units;
}
EDIT: Just to clarify. When the user shoots the ball, its position changes to a certain value. Now, if he hits it again, the min and max values of the random int generator should change to prevent the ball from moving outside the walls. Example:
Level starts. The ball is in the middle of the room. The min and max ranges are -480 and 480 respectively
The user hits the ball and its moved -200 units (200 units to the left).
Now, the min and max range should be -280 and 680.
I hope this is clear enough.
EDIT 2: Edited the sign as FlipScript suggested. Here's the output from the log2screen functions, what is actually happening:
MIN: -480 and MAX 480. MOVED 67
MIN: -413 and MAX 547. MOVED 236
MIN: -244 and MAX 716. MOVED 461
Just a sample case. Something is backwards I believe, these aren't the right calculations to do.
Your code works only when self.prevx contains your displacement from the starting position, i.e. your absolute position. However, what you are storing is your displacement from your current position. It works the first two times because that displacement happens to be the same as your absolute position, but once you move again, you lose all track of where you are.
What you should do instead is get rid of min and max, and start by calculating a random absolute position within the bounds. Then use your previously stored absolute position to calculate the relative movement needed to get you there, and store the new absolute position.
head_move()
{
new_x = RandomIntRange( -480, 480 ); //create a random location
delta_x = new_x - level.prev; //determine relative movement needed to get there
self movex (delta_x , level.movespeed); //move to new position
level.prevx = new_x; //store new position
}
I dont know much about the programming environment, but this line
head_origin thread head_move();
is suspicious for troublemaking. What are these tokens? Anything that says thread could be duplicating data structures and throwing your local variables astray.
And why do x_min and x_max change? Where's y_min and y_max?
Something doesn't look right in this line here:
x_max = x_min - 960;
Is the MAX really the MIN MINUS 960? From your description, it sounds like that should be a '+' sign.
EDIT:
In your additional comments, the minus sign wouldn't allow these truths:
Level starts....The min and max ranges are -480 and 480 respectively
...
Now, the min and max range should be -280 and 680.
Comments 1 and 3 point to that sign needing to be '+' sign.

Resources