Related
I'm trying to make a strategy of an indicator, but I get the error: Line 73: Cannot call 'operator >' with argument 'expr0'='call 'alertcondition' (void)'. An argument of 'void' type was used but a 'const float' is expected. How can I change the code to get a correct boolean if statement for the trade entry? I'm very new to pine, hopefully someone can help me.
// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//#version=5
// Umgeschrieben von JSt
strategy("Watson Strategie Nadaraya-Watson Envelope [JSt]",overlay=true,max_bars_back=1000,max_lines_count=500,max_labels_count=500)
length = input.float(500,'Window Size',maxval=500,minval=0)
h = input.float(8.,'Bandwidth')
mult = input.float(3.)
src = input.source(close,'Source')
up_col = input.color(#39ff14,'Colors',inline='col')
dn_col = input.color(#ff1100,'',inline='col')
//----
n = bar_index
var k = 2
var upper = array.new_line(0)
var lower = array.new_line(0)
lset(l,x1,y1,x2,y2,col)=>
line.set_xy1(l,x1,y1)
line.set_xy2(l,x2,y2)
line.set_color(l,col)
line.set_width(l,2)
if barstate.isfirst
for i = 0 to length/k-1
array.push(upper,line.new(na,na,na,na))
array.push(lower,line.new(na,na,na,na))
//----
line up = na
line dn = na
//----
cross_up = 0.
cross_dn = 0.
if barstate.islast
y = array.new_float(0)
sum_e = 0.
for i = 0 to length-1
sum = 0.
sumw = 0.
for j = 0 to length-1
w = math.exp(-(math.pow(i-j,2)/(h*h*2)))
sum += src[j]*w
sumw += w
y2 = sum/sumw
sum_e += math.abs(src[i] - y2)
array.push(y,y2)
mae = sum_e/length*mult
for i = 1 to length-1
y2 = array.get(y,i)
y1 = array.get(y,i-1)
up := array.get(upper,i/k)
dn := array.get(lower,i/k)
lset(up,n-i+1,y1 + mae,n-i,y2 + mae,up_col)
lset(dn,n-i+1,y1 - mae,n-i,y2 - mae,dn_col)
if src[i] > y1 + mae and src[i+1] < y1 + mae
label.new(n-i,src[i],'▼',color=#00000000,style=label.style_label_down,textcolor=dn_col,textalign=text.align_center)
if src[i] < y1 - mae and src[i+1] > y1 - mae
label.new(n-i,src[i],'▲',color=#00000000,style=label.style_label_up,textcolor=up_col,textalign=text.align_center)
cross_up := array.get(y,0) + mae
cross_dn := array.get(y,0) - mae
// TestUP = ta.crossover(src,cross_up) > 0
alertcondition(ta.crossover(src,cross_up),'Down','Down')
alertcondition(ta.crossunder(src,cross_dn),'Up','Up')
//---- Alarm für Webhook -----
plot(cross_up, color=#000000, transp=100) //Für den Alert, jedoch Darstellungsfehler → Transparent
plot(cross_dn, color=#000000, transp=100)
plotchar(cross_up, title="cross_up%", char="", location=location.top, color = color.green) // Damit der Wert in der Statusleiste dargestellt wird
plotchar(cross_dn, title="cross_dn%", char="", location=location.top, color = color.red)
//-------------------
// Start Date
// STEP 1. Create inputs that configure the backtest's date range
useDateFilter = input.bool(true, title="Begin Backtest at Start Date",
group="Backtest Time Period")
backtestStartDate = input.time(timestamp("1 Jan 2021"),
title="Start Date", group="Backtest Time Period",
tooltip="This start date is in the time zone of the exchange " +
"where the chart's instrument trades. It doesn't use the time " +
"zone of the chart or of your computer.")
// STEP 2. See if current bar happens on, or later than, the start date
inTradeWindow = not useDateFilter or time >= backtestStartDate
// ---------------
// Enter a long position when the entry rule is triggered
if inTradeWindow and ta.crossover(src,cross_up) > 0
strategy.entry('Long', strategy.long)
// Exit the Long position when the exit rule is triggered
if close > strategy.position_avg_price + 50
strategy.close("Long", comment = "TP")
else if close < strategy.position_avg_price - 50
strategy.close("Long", comment = "SL")
I tried the ta.crossover(src,cross_up) to compare it to zero, but it doesn't work.
ta.crossover() returns a bool value.
ta.crossover(source1, source2) → series bool
So, comparing its return value with some number does not make any sense and the compiler will complain: ta.crossover(src,cross_up) > 0.
You should just do:
if inTradeWindow and ta.crossover(src,cross_up)
strategy.entry('Long', strategy.long)
*[I found that the error occurred at line 57, z2 = w12.a1 + b12; with incompatible array size,
May I know how to fix it? Basically the data is from the simulation on MATLAB Simulink, so the size of the array changes as we increase the inputs from the original code which only have 1 input type][1]
%% load training data (use training_data.mat attached file)
% initialize number of nodes, weights, biases, errors and gradients.
%epochs and mini-batch size
clc
data = [out.dutycycle out.voltage out.current]
sample=1000;
labels = data(1:sample,1);
y = labels'; %output vector
images = data(1:sample,2:3);
images(:,1) = images(:,1)/400;
images(:,2) = images(:,2)/100;
images = images'; %Input vectors
hn1 = 80; %Number of neurons in the first hidden layer
hn2 = 60; %Number of neurons in the second hidden layer
%Initializing weights and biases
w12 = randn(hn1,1000).*sqrt(2/1000);
w23 = randn(hn2,hn1)*sqrt(2/hn1);
w34 = randn(1,hn2)*sqrt(2/hn2);
b12 = randn(hn1,1);
b23 = randn(hn2,1);
b34 = randn(1,1);
%learning rate
eta = 0.0058;
%Initializing errors and gradients
error4 = zeros(1,1);
error3 = zeros(hn2,1);
error2 = zeros(hn1,1);
errortot4 = zeros(1,1);
errortot3 = zeros(hn2,1);
errortot2 = zeros(hn1,1);
grad4 = zeros(1,1);
grad3 = zeros(hn2,1);
grad2 = zeros(hn1,1);
epochs = 50;
m = 10; %Minibatch size
%% Training phase
for k = 1:epochs %Outer epoch loop
batches = 1;
for j = 1:sample/m
error4 = zeros(1,1);
error3 = zeros(hn2,1);
error2 = zeros(hn1,1);
errortot4 = zeros(1,1);
errortot3 = zeros(hn2,1);
errortot2 = zeros(hn1,1);
grad4 = zeros(1,1);
grad3 = zeros(hn2,1);
grad2 = zeros(hn1,1);
for i = batches:batches+m-1 %Loop over each minibatch
%Feed forward
a1 = images(:,i);
z2 = w12.*a1 + b12;
a2 = elu(z2);
z3 = w23*a2 + b23;
a3 = elu(z3);
z4 = w34*a3 + b34;
a4 = elu(z4); %Output vector
%backpropagation
error4 = (a4-y(:,i)).*elup(z4);
error3 = (w34'*error4).*elup(z3);
error2 = (w23'*error3).*elup(z2);
errortot4 = errortot4 + error4;
errortot3 = errortot3 + error3;
errortot2 = errortot2 + error2;
grad4 = grad4 + error4*a3';
grad3 = grad3 + error3*a2';
grad2 = grad2 + error2*a1';
end
%Gradient descent
w34 = w34 - eta/m*grad4;
w23 = w23 - eta/m*grad3;
w12 = w12 - eta/m*grad2;
b34 = b34 - eta/m*errortot4;
b23 = b23 - eta/m*errortot3;
b12 = b12 - eta/m*errortot2;
batches = batches + m;
end
fprintf('Epochs:');
disp(k) %Track number of epochs
[images,y] = shuffle(images,y); %Shuffles order of the images for next epoch
end
disp('Training done!')
%note : create folder for this experiment and save the parameters.
% don't forget to keep the folder in matlab path!
save('wfour.mat','w34');
save('wthree.mat','w23');
save('wtwo.mat','w12');
save('bfour.mat','b34');
save('bthree.mat','b23');
save('btwo.mat','b12');
%% Testing phase
% load testing data with labels ... (use testing_data.mat attached file)
testsample = 100;
labels = test(1:testsample,1);
y = labels';
images = test(1:testsample,2:3);
images(:,1) = images(:,1)/400;
images(:,2) = images(:,2)/100;%copy
images = images';
we34 = matfile('wfour.mat');
w4 = we34.w34;
we23 = matfile('wthree.mat');
w3 = we23.w23;
we12 = matfile('wtwo.mat');
w2 = we12.w12;
bi34 = matfile('bfour.mat');
b4 = bi34.b34;
bi23 = matfile('bthree.mat');
b3 = bi23.b23;
bi12 = matfile('btwo.mat');
b2 = bi12.b12;
success = 0;
n = testsample;
for i = 1:n
out2 = elu(w2*images(:,i)+b2);
out3 = elu(w3*out2+b3);
out = elu(w4*out3+b4);
big = 0;
num = 0;
for k = 1:10
if out(k) > big
num = k-1;
big = out(k);
end
end
if labels(i) == num
success = success + 1;
end
end
fprintf('Accuracy: ');
fprintf('%f',success/n*100);
disp(' %');
%% ELU activation function
function fr = elu(x)
f = zeros(length(x),1);
for i = 1:length(x)
if x(i)>=0
f(i) = x(i);
else
f(i) = 0.2*(exp(x(i))-1);
end
end
fr = f;
end
%% derivative of the ELU activation function
function fr = elup(x)
f = zeros(length(x),1);
for i = 1:length(x)
if x(i)>=0
f(i) = 1;
else
f(i) = 0.2*exp(x(i));
end
end
fr = f;
end
%% SHuffle function
function [B,v] = shuffle(A,y)
cols = size(A,2);
P = randperm(cols);
B = A(:,P);
v = y(:,P);
end
Your help is much appreciated, thank you
MATLAB Error :
Arrays have incompatible sizes for this operation.
Error in ANN_PV_Array (line 57)
z2 = w12.*a1 + b12;
I've been trying my first codes in pine script. The question is this. I have created few array.new_float to use as buffers in the 'for' statement. The thing is that I need to do some math over the data. Now, once the 'for' is done, an error pops: 'Cannot call 'operator -' with argument 'expr0' = 'High'.An argument of 'float[]' type was used but a 'const int' is expected'.
Please, if anyone knows what am I doing wrong, I will thank you.
Edit: I will leave the script of what I'm trying to do here
//#version=5
// Indicator name
indicator("DAF_Swing_Index", shorttitle= 'DAF_SwInd', overlay=false)
// Input
T = input.int(30000, title = 'Ratio de escala', minval = 1000, maxval = 150000)
Shift = input.int(0, title = 'Desplazamiento horizontal', minval = 0, maxval = 100)
// Array
SWINGINDEX = array.new_float(200)
Open = array.new_float(200)
Open1 = array.new_float(200)
Close = array.new_float(200)
Close1 = array.new_float(200)
High = array.new_float(200)
Low = array.new_float(200)
// Other variable
var float SwingIndex = 0
var int StartBars = 1
Prev_calculated = bar_index
Rates_total = bar_index + 1
var float SH1 = 0
var float SI = 0
var float R = 0
// Initial bar verification
if Rates_total < StartBars
SwingIndex := 0
Primero = 1
if Prev_calculated > Rates_total or Prev_calculated <= 0
Primero := 1
else
Primero := Prev_calculated-1
// Main process
for bar = Primero to Rates_total
array.push(Open, high[bar])
array.push(Open1, open[bar-1])
array.push(Close, close[bar])
array.push(Close1, close[bar-1])
array.push(High, high[bar])
array.push(Low, low[bar])
K = math.max(math.abs(High - Close1), math.abs(Low - Close1))
TR = math.max(math.max(math.abs(High-Close1), math.abs(Low-Close1)), math.abs(High-Low))
ER = 0.0
if Close1 > High
ER := math.abs(High - Close1)
if Close1 < Low
ER := math.abs(Low - Close1)
SH1 := math.abs(Close1 - Open1)
R := TR - 0.5 * ER + 0.25 * SH1
SI := 0.0
if R != 0
SI := 50 * ((Close - Close1) + 0.5 * (Close - Open1)) * (K / T) / R
SwingIndex := SI
// ploting result
plot(SwingIndex, title = 'Swing Index', style = plot.style_line, color = color.rgb(193, 255, 51, 10))
So, what the error message tells you is, your are passing an array, where it expects a const value.
Like here:
K = math.max(math.abs(High - Close1), math.abs(Low - Close1))
All those variables (High, Close1, Low) are arrays. It simply can not subtract one array from another. You can however, subtract one element from another element.
So for that line, I believe you want something like this:
K = math.max(math.abs(array.get(High, bar) - array.get(Close1, bar)), math.abs(array.get(Low, bar) - array.get(Close1, bar)))
With array.get(), you can get value the of the element at the specified index.
You should fix this in all other occurences.
I'm doing a rather easy example to learn how to use ocaml as an imperative language.
My guess is I messed up with the semicolons but I can't find any mistakes in the code
let sort array =
for index = 0 to (Array.length array -1) do
let boole = ref false;
let pos = ref index;
let max = ref array.(index);
let p = ref !pos;
let m = ref !max;
while !pos <> (Array.lenght array -1 ) do
if array.(!pos) > !max then begin
max := array(!pos);
boole := true;
p := !pos
end
pos := !pos + 1
done;
if (!boole = true) then begin
array.(index) <- max;
array.(pos) <- m
end
done ;;
Thank you.
Edit 1 :
In case someone comes across this question, I'm posting the correct code cause the above didn't sort the array correctly even with the correct syntax:
let sort array =
for index = 0 to (Array.length array -1) do
let boole = ref false in
let pos = ref index in
let max = ref array.(index) in
let p = ref !pos in
let m = ref !max in
for i = !pos to (Array.length array -1) do
if (array.(i) > !max) then begin
pos :=i;
max := array.(!pos);
boole := true;
end;
done;
if (!boole = true) then begin
array.(!pos) <- !m;
array.(!p) <- !max;
end;
done ;;
First off all, there is no let x = y; expression in OCaml, a correct syntax is let x = y in, also you shouldn't forget to dereference your references.
let sort array =
for index = 0 to (Array.length array -1) do
let boole = ref false in
let pos = ref index in
let max = ref array.(index) in
let p = ref !pos in
let m = ref !max in
while !pos <> (Array.length array -1 ) do
if array.(!pos) > !max then begin
max := array.(!pos);
boole := true;
p := !pos
end;
pos := !pos + 1;
done;
if (!boole = true) then begin
array.(index) <- !max;
array.(!pos) <- !m;
end;
done ;;
The following fix in the code may help - at least to get the code compiled - :
let sort toto =
for index = 0 to (Array.length toto - 1) do
let boole = ref false in
let pos = ref index in
let max = ref toto.(index) in
let p = ref !pos in
let m = ref !max in
begin
while !pos <> (Array.length toto - 1 ) do
begin
if (toto.(!pos) > !max) then
begin
max := toto.(!pos);
boole := true;
p := !pos;
end;
pos := !pos + 1;
end
done;
if (!boole = true) then begin
toto.(index) <- !max;
toto.(!pos) <- !m
end
end
done;;
Notably : the declaration of local variable, and also some missing semicolons.
I change the name of the argument (array to toto) - as array is a keyword, but I do not think it is necessary.
This question already has an answer here:
MATLAB : What is the mistake in my Ramachandran plot?
(1 answer)
Closed 8 years ago.
I am trying matlab to plot ramachandran plot, without using built in command. I have succeeded too. Now I wanted to spot the GLYCINEs alone in the scatter array. Any ideas how to do this? (link to 1UBQ.pdb file : http://www.rcsb.org/pdb/download/downloadFile.do?fileFormat=pdb&compression=NO&structureId=1UBQ)
% Program to plot Ramanchandran plot of Ubiquitin
close all; clear ; clc; % close all figure windows, clear variables, clear screen
pdb1 ='/home/devanandt/Documents/VMD/1UBQ.pdb';
p=pdbread(pdb1); % read pdb file corresponding to ubiquitin protein
atom={p.Model.Atom.AtomName};
n_i=find(strcmp(atom,'N')); % Find indices of atoms
ca_i=find(strcmp(atom,'CA'));
c_i=find(strcmp(atom,'C'));
X = [p.Model.Atom.X];
Y = [p.Model.Atom.Y];
Z = [p.Model.Atom.Z];
X_n = X(n_i(2:end)); % X Y Z coordinates of atoms
Y_n = Y(n_i(2:end));
Z_n = Z(n_i(2:end));
X_ca = X(ca_i(2:end));
Y_ca = Y(ca_i(2:end));
Z_ca = Z(ca_i(2:end));
X_c = X(c_i(2:end));
Y_c = Y(c_i(2:end));
Z_c = Z(c_i(2:end));
X_c_ = X(c_i(1:end-1)); % the n-1 th C (C of cabonyl)
Y_c_ = Y(c_i(1:end-1));
Z_c_ = Z(c_i(1:end-1));
V_c_ = [X_c_' Y_c_' Z_c_'];
V_n = [X_n' Y_n' Z_n'];
V_ca = [X_ca' Y_ca' Z_ca'];
V_c = [X_c' Y_c' Z_c'];
V_ab = V_n - V_c_;
V_bc = V_ca - V_n;
V_cd = V_c - V_ca;
phi=0;
for k=1:numel(X_c)
n1=cross(V_ab(k,:),V_bc(k,:))/norm(cross(V_ab(k,:),V_bc(k,:)));
n2=cross(V_bc(k,:),V_cd(k,:))/norm(cross(V_bc(k,:),V_cd(k,:)));
x=dot(n1,n2);
m1=cross(n1,(V_bc(k,:)/norm(V_bc(k,:))));
y=dot(m1,n2);
phi=cat(2,phi,-atan2d(y,x));
end
phi=phi(1,2:end);
X_n_ = X(n_i(2:end)); % (n+1) nitrogens
Y_n_ = Y(n_i(2:end));
Z_n_ = Z(n_i(2:end));
X_ca = X(ca_i(1:end-1));
Y_ca = Y(ca_i(1:end-1));
Z_ca = Z(ca_i(1:end-1));
X_n = X(n_i(1:end-1));
Y_n = Y(n_i(1:end-1));
Z_n = Z(n_i(1:end-1));
X_c = X(c_i(1:end-1));
Y_c = Y(c_i(1:end-1));
Z_c = Z(c_i(1:end-1));
V_n_ = [X_n_' Y_n_' Z_n_'];
V_n = [X_n' Y_n' Z_n'];
V_ca = [X_ca' Y_ca' Z_ca'];
V_c = [X_c' Y_c' Z_c'];
V_ab = V_ca - V_n;
V_bc = V_c - V_ca;
V_cd = V_n_ - V_c;
psi=0;
for k=1:numel(X_c)
n1=cross(V_ab(k,:),V_bc(k,:))/norm(cross(V_ab(k,:),V_bc(k,:)));
n2=cross(V_bc(k,:),V_cd(k,:))/norm(cross(V_bc(k,:),V_cd(k,:)));
x=dot(n1,n2);
m1=cross(n1,(V_bc(k,:)/norm(V_bc(k,:))));
y=dot(m1,n2);
psi=cat(2,psi,-atan2d(y,x));
end
psi=psi(1,2:end);
scatter(phi,psi)
box on
axis([-180 180 -180 180])
title('Ramachandran Plot for Ubiquitn Protein','FontSize',16)
xlabel('\Phi^o','FontSize',20)
ylabel('\Psi^o','FontSize',20)
grid
The output is :
EDIT : Is my plot correct? Biopython: How to avoid particular amino acid sequences from a protein so as to plot Ramachandran plot? has an answer which has slightly different plot.
The modified code is as below :
% Program to plot Ramanchandran plot of Ubiquitin with no glycines
close all; clear ; clc; % close all figure windows, clear variables, clear screen
pdb1 ='/home/devanandt/Documents/VMD/1UBQ.pdb';
p=pdbread(pdb1); % read pdb file corresponding to ubiquitin protein
atom={p.Model.Atom.AtomName};
n_i=find(strcmp(atom,'N')); % Find indices of atoms
ca_i=find(strcmp(atom,'CA'));
c_i=find(strcmp(atom,'C'));
X = [p.Model.Atom.X];
Y = [p.Model.Atom.Y];
Z = [p.Model.Atom.Z];
X_n = X(n_i(2:end)); % X Y Z coordinates of atoms
Y_n = Y(n_i(2:end));
Z_n = Z(n_i(2:end));
X_ca = X(ca_i(2:end));
Y_ca = Y(ca_i(2:end));
Z_ca = Z(ca_i(2:end));
X_c = X(c_i(2:end));
Y_c = Y(c_i(2:end));
Z_c = Z(c_i(2:end));
X_c_ = X(c_i(1:end-1)); % the n-1 th C (C of cabonyl)
Y_c_ = Y(c_i(1:end-1));
Z_c_ = Z(c_i(1:end-1));
V_c_ = [X_c_' Y_c_' Z_c_'];
V_n = [X_n' Y_n' Z_n'];
V_ca = [X_ca' Y_ca' Z_ca'];
V_c = [X_c' Y_c' Z_c'];
V_ab = V_n - V_c_;
V_bc = V_ca - V_n;
V_cd = V_c - V_ca;
phi=0;
for k=1:numel(X_c)
n1=cross(V_ab(k,:),V_bc(k,:))/norm(cross(V_ab(k,:),V_bc(k,:)));
n2=cross(V_bc(k,:),V_cd(k,:))/norm(cross(V_bc(k,:),V_cd(k,:)));
x=dot(n1,n2);
m1=cross(n1,(V_bc(k,:)/norm(V_bc(k,:))));
y=dot(m1,n2);
phi=cat(2,phi,-atan2d(y,x));
end
phi=phi(1,2:end);
X_n_ = X(n_i(2:end)); % (n+1) nitrogens
Y_n_ = Y(n_i(2:end));
Z_n_ = Z(n_i(2:end));
X_ca = X(ca_i(1:end-1));
Y_ca = Y(ca_i(1:end-1));
Z_ca = Z(ca_i(1:end-1));
X_n = X(n_i(1:end-1));
Y_n = Y(n_i(1:end-1));
Z_n = Z(n_i(1:end-1));
X_c = X(c_i(1:end-1));
Y_c = Y(c_i(1:end-1));
Z_c = Z(c_i(1:end-1));
V_n_ = [X_n_' Y_n_' Z_n_'];
V_n = [X_n' Y_n' Z_n'];
V_ca = [X_ca' Y_ca' Z_ca'];
V_c = [X_c' Y_c' Z_c'];
V_ab = V_ca - V_n;
V_bc = V_c - V_ca;
V_cd = V_n_ - V_c;
psi=0;
for k=1:numel(X_c)
n1=cross(V_ab(k,:),V_bc(k,:))/norm(cross(V_ab(k,:),V_bc(k,:)));
n2=cross(V_bc(k,:),V_cd(k,:))/norm(cross(V_bc(k,:),V_cd(k,:)));
x=dot(n1,n2);
m1=cross(n1,(V_bc(k,:)/norm(V_bc(k,:))));
y=dot(m1,n2);
psi=cat(2,psi,-atan2d(y,x));
end
psi=psi(1,2:end);
res=strsplit(p.Sequence.ResidueNames,' ');
angle =[phi;psi];
angle(:,find(strcmp(res,'GLY'))-1)=[];
scatter(angle(1,:),angle(2,:))
box on
axis([-180 180 -180 180])
title('Ramachandran Plot for Ubiquitn Protein','FontSize',16)
xlabel('\Phi^o','FontSize',20)
ylabel('\Psi^o','FontSize',20)
grid
which gives output (with no GLY) as below :
I would change this code block to use logical indexing
res=strsplit(p.Sequence.ResidueNames,' ');
angle =[phi;psi];
angle(:,find(strcmp(res,'GLY'))-1)=[];
Instead:
residues = strsplit(p.Sequency.ResidueNames,' ');
glycine = ismember(residues,'GLY');
angle = [phi;psi];
angleNoGLY= angle(:,~glycine);
Doing it this way, if you wanted to highlight glycine (or any other residue) you can easily call it out:
angleGLY = angle(:,glycine);
plot(angleNoGLY(1,:),angleNoGLY(2,:),'ob')
line(angleGLY(1,:),angleGLY(2,:),'Marker','o','Color','r','LineStyle','none')