Tradingview custom function with security() - function

I'm looking at the Pine version 3 migration guide and there's an example showing a custom function and using security() to call that function. https://www.tradingview.com/wiki/Pine_Version_3_Migration_Guide
Now I tried to change my custom function in order to return two values instead of one, but for some reason it doesn't work anymore. The error is on line 10 ("[t,i] = ...") and says: variableType.itemType is not a function.
My code below, can anyone advise what the issue is please?
//#version=3
study("My Script")
calcS() =>
s = 0.0
j = 0.0
s := close + 1
j := close + 2
[s, j]
[t, i] = security(tickerid, '120', calcS())
plot(t, color=red, transp=0)
plot(i, color=blue, transp=0)

It's a known problem. You can't return tuple from security. It's in our plans to fix this bug.
Now you may use the following workaround:
//#version=3
study("My Script")
calcS() =>
s = 0.0
j = 0.0
s := close + 1
j := close + 2
[s, j]
calcSs() =>
[s, j] = calcS()
s
calcSj() =>
[s, j] = calcS()
j
t = security(tickerid, '120', calcSs())
i = security(tickerid, '120', calcSj())
plot(t, color=red, transp=0)
plot(i, color=blue, transp=0)

UPDATE
Starting with Pine v4 you can use functions returning tuples with security():
//#version=4
study("", "", true)
f() => [open, high]
[o, h] = security(syminfo.tickerid, "D", f())
plot(o)
plot(h)

Related

How to graph the function in matlab?

I have the following 2n*π-periodic function F(x) = sin(x/n) and I need to graph the dx/dt = γ - F(x) on the segment from 0 to 2pi. So it should look like this. I tried to do it matlab this way:
gamma = 1.01;
n=3;
[t,phi] = ode45(#(t,x)gamma-sin(x/n), [0,400], pi);
[t1,phi1] = ode45(#(t,x)gamma-sin(x/n), [112,400], 0);
[t2,phi2] = ode45(#(t,x)gamma-sin(x/n), [231,250], 0);
figure();
plot(t, phi, 'k', t1, phi1, 'k', t2, phi2, 'k');
ylim([0 2*pi]);
yticks([0 pi 2*pi]);
yticklabels(["0" "\pi" "2\pi"]);
grid on; grid minor;
title('\itsin(x/n)')
but I only got something like this. So there the lines are not transferred, but "begin anew". does anyone here know how to do that?
I get a plot similar to your first sketch, and based on your code in the comments (in future, put such additions into the question itself, use formatting to mark it as addition, and cite it then in the comment) with the changes
use pi as initial point as seen in the drawing,
use the options of the ODE solver to restrict the step size, directly and by imposing error tolerances
your original time span covers about 3 periods, reduce this to [0, 200] to get the same features as the drawing.
gamma = 1.01; n=3;
opts = odeset('AbsTol',1e-6,'RelTol',1e-9,'MaxStep',0.1);
[t, phi] = ode45(#(t,x)gamma-sin(x/n), [0,200], pi, opts);
phi = mod(phi, 2*pi);
plot(t, phi, 'k');
ylim([0 2*pi]); yticks([0 pi 2*pi]); yticklabels(["0" "\pi" "2\pi"]);
grid on; grid minor;
title('\itsin(x/n)')
To get more elaborate, use events to get points on the numerical solution where it exactly crosses the 2*pi periods, then use that to segment the solution plot (styling left out)
function [ res, term, dir ] = event(t,y)
y = mod(y+pi,2*pi)-pi;
res = [ y ];
dir = [1]; % only crossing upwards
term = [0]; % do not terminate
end%function
opts = odeset(opts,'Events',#(t,y)event(t,y));
sol = ode45(#(t,x)gamma-sin(x/n), [0,200], pi, opts);
tfs = [ sol.xe; sol.x(end) ]
N = length(tfs)
clf;
t0 = 0;
for i=1:N
tf = tfs(i);
t = linspace(t0+1e-2,tf-1e-2,150);
y = deval(sol,t); % octave: deval=#(res,t) interp1(res.x, res.y,t)
y = mod(y,2*pi);
plot(t, y);
hold on;
t0=tf;
end;
hold off;

Calculate CRC16 CCITT FALSE in Google Apps Script [duplicate]

This question already has an answer here:
Calculate CRC-16/CCITT-FALSE in Google Apps Script
(1 answer)
Closed 1 year ago.
I have VBA code that calculate the CRC16 CCITT value of string but now i have plan to use it on Google Sheet, but didn't have any idea how it will be on google script
Function crc_ccitt_ffff(strParam As String) As String
Const CRC_POLY_CCITT As Long = &H1021&
Const CRC_START_CCITT_FFFF As Long = &HFFFF&
Dim crc_tabccitt(0 To 255) As Long, crc As Long, b() As Byte, c As Long, i As Long, j As Long
For i = 0 To 255
crc = 0
c = i * 256
For j = 0 To 7
If (crc Xor c) And 32768 Then
crc = (crc * 2) Xor CRC_POLY_CCITT
Else
crc = crc * 2
End If
c = c * 2
Next j
crc_tabccitt(i) = crc
Next i
b = strParam
crc = CRC_START_CCITT_FFFF
For i = 0 To UBound(b) Step 2
crc = (crc * 256) Xor crc_tabccitt(((crc \ 256) Xor b(i)) And 255)
crc = ((crc \ 65536) * 65536) Xor crc
Next i
crc_ccitt_ffff = Hex(crc)
End Function
String on Column A : 00020101021129370016A000000677010111021312345678901215802TH5406500.5553037646304
Expected Results on Column B(or any other column) : 3D85
Can anyone help me with this?
Okay. Just for fun I've managed to translate your VB code (not sure if the code is working) to JS. Here you go:
function crc_ccitt_ffff(str) {
const POLY = 0x1021;
const START = 0xFFFF;
function get_crc_for_num(i) {
var crc = 0;
var c = i * 256;
[...Array(8).keys()].forEach(_ => {
crc = ((crc ^ c) & 0x8000) ? (crc * 2) ^ POLY : crc * 2;
c = c * 2 });
return crc;
}
var table = [...Array(256).keys()].map((_,n) => get_crc_for_num(n));
var crc = START;
str.split('').forEach(c => {
crc = (crc * 0x100) ^ table[ ( ((crc / 0x100) >> 0) ^ c.charCodeAt() ) & 0xFF ];
crc = (((crc / 0x10000) >> 0) * 0x10000) ^ crc;
}
)
return crc.toString(16);
}
var str = '00020101021129370016A000000677010111021312345678901215802TH5406500.5553037646304';
console.log( crc_ccitt_ffff(str) ); // output 3d85
It gives the same result with your data and it gives the same results as here https://crccalc.com/
But, beware, I'm not a real coder and I know next to nothing about VB and CRC-16. So it makes sense to test my code thoroughly before rush it into production.
Here is the code for Google Spreadsheet:
function main() {
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange("A1:B");
const data = range.getValues().map(x => [x[0], crc_ccitt_ffff(x[0])]);
range.setValues(data);
}
function crc_ccitt_ffff(str) {
if (str == '') return;
const get_crc_for_num = (n) => {
let crc = 0;
let c = n * 256;
[...Array(8).keys()].forEach(_ => {
crc = ((crc ^ c) & 0x8000) ? (crc * 2) ^ 0x1021 : crc * 2;
c = c * 2;
});
return crc;
}
const table = [...Array(256).keys()].map((_,n) => get_crc_for_num(n));
var crc = 0xFFFF;
str.split('').forEach(c => {
crc = (crc * 0x100) ^ table[(((crc / 0x100) >> 0) ^ c.charCodeAt()) & 0xFF];
crc = (((crc / 0x10000) >> 0) * 0x10000) ^ crc;
});
return crc.toString(16);
}
It takes all strings from column 'A' and put their CRC-16 to column 'B'.
Not sure if my solution is correct. Here is the JS implementation of CRC-16/CCITT: Generate CRC16 CCITT False with Javascript?
It gives 7D133D85 which looks suspiciously like your expected result. I have no idea where the first four digits go in the VB code.
So I took that JS code and updated it a little bit this way:
var crcTable = [
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE,
0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485,
0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D,
0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4,
0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC,
0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823,
0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12,
0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A,
0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41,
0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49,
0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70,
0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78,
0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,
0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067,
0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E,
0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256,
0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D,
0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C,
0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB,
0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3,
0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A,
0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92,
0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9,
0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,
0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0,
];
function crc16(str) {
var crc = 0xFFFF;
str.split('').forEach(c =>
crc = (crc << 8) ^ crcTable[(c.charCodeAt(0) ^ (crc >> 8)) & 0xFF]);
return crc.toString(16).toUpperCase();
}
var str = "00020101021129370016A000000677010111021312345678901215802TH5406500.5553037646304"
console.log(crc16(str)); // it gives 7d133d85
console.log(crc16(str).substring(4)); // it gives 3d85
As you can see, I use the substring(4) to get rid of the first four digits. Probably it's a stupid idea. Frankly, I'm not sure if this trick is applicable at all. You have to try it on your data.
Or to wait for someone who can translate accurately your VB code to JS. It doesn't look like an unsolvable task.

Octave fminunc doesn't update

I have the following octave script:
clear;
T0 = [...
1.0, 1.0, 5.0; ...
1.0, 2.0, 3.0; ...
-1.0,0.0, 6.0];
option = optimset('Display','Iter','GradObj','on','MaxIter','300','TolFun',10-5);
[t f] = fminunc(#flatTriangle,T0(:),option);
t = reshape(t,3,3);
And following octave functions
function [cost grad] = flatTriangle(T)
T = reshape(T,3,3);
Q = T(1,:)';
P = T(2,:)';
R = T(3,:)';
e3 = [0;0;1];
nf = cross(R - Q,P - Q);
cost = 0.5*(e3'*nf - norm(nf))^2;
grad = zeros(9,1);
commonStuff = (e3'*nf - norm(nf))*(e3 - nf/norm(nf))';
grad(1:3) = (commonStuff*skew(P - R)')';
grad(4:6) = (commonStuff*skew(R - Q)')';
grad(7:9) = (commonStuff*skew(Q - P)')';
endfunction
function Vhat = skew(V)
Vhat = [...
0.0 -V(3) V(2); ...
V(3) 0.0 -V(1); ...
-V(2) V(1) 0.0];
endfunction
Now despite the fact the grad vector isn't 0 the final output doesn't change at all from the initial input.
Am I using incorrectly something? maybe I'm not configuring something properly?
The code runs but it doesn't seem to do anything.

Octave index out of bounds

The program is an optimized gradient descent.
Here is the code :
clear all
close all
[x,y] = meshgrid(-2:0.1:2);
z = x.^2 + 100*y.^2;
n = 1;
k(n)=0.01;
arret = 0.0001;
mesh(x,y,z);
[x1(n),y1(n)] = ginput(1);
diff_x(n) = 2*x1(n);
diff_y(n) = 200*y1(n);
while sqrt(diff_x(n)^2 + diff_y(n)^2) > arret && n < 30
k(n) = sqrt(diff_x(n)^2 + diff_y(n)^2)/(8*x1(n).^2+2*10.^6*y1(n).^2);
x1(n+1) = x1(n) - k(n)*diff_x(n);
y1(n+1) = y1(n) - k(n)*diff_y(n);
n = n+1;
diff_x(n) = 2*x1(n);
diff_y(n) = 200*y1(n);
z1(n) = x1(n).^2 + 100*y1(n).^2;
plot3(x1(n),y1(n),z1(n));
end
x1(n)
y1(n)
n
So I got this and I don't understand why.
error: GradientPasOptFinal2: A(I): index out of bounds; value 2 out of bound 1
error: called from:
error: error: C:\Octave\octave-3.8.2\GradientPasOptFinal2.m at line 13, column 8
SOLVED : the k(n) between y1(n) and n was the reason, i don't know why, but now the program works, thank you !
You have only defined k(1). k(2) is undefined.
Move this line:
k(n) = sqrt(diff_x(n)^2 + diff_y(n)^2)/(8*x1(n).^2+2*10.^6*y1(n).^2);
Ahead of these lines:
x1(n+1) = x1(n) - k(n)*diff_x(n);
y1(n+1) = y1(n) - k(n)*diff_y(n);
And it should work.

Recursive Function In Mathematica

Consider :
dist = Parallelize[
Table[RandomVariate[NormalDistribution[]], {100000}]];
How could I create a recursive function such that :
Subscript[d, 1] = dist[[1]]
Subscript[d, 2] = .95 Subscript[d, 1] + dist[[2]]
Subscript[d, 3] = .95 Subscript[d, 2] + dist[[3]]
And do this till Subscript[d, 100000]
Thank You.
It is surprisingly the first time I run into this.
Consider this:
dist = RandomVariate[NormalDistribution[], {100000}];
dist2 = Rest#FoldList[0.95 # + #2 &, 0, dist];
Subscript[d, x_] := dist2[[x]]
I don't normally use Subscript this way; I don't know what may break doing this. If you describe more of your problem, I may have an alternate suggestion.
How about using something like
In[1]:= dist = ParallelTable[RandomVariate[NormalDistribution[]], {100000}];//Timing
Out[1]= {0.15601, Null}
In[2]:= folded = FoldList[.95 #1 + #2 &, First#dist, Rest#dist]; // Timing
Out[2]= {0.056003, Null}
which you can compare to
In[3]:= Subscript[d, 1] = dist[[1]];
Do[Subscript[d, n] = 0.95 Subscript[d, n - 1] + dist[[n]],
{n, 2, Length#dist}] // Timing
Out[3]= {1.09607, Null}
In[4]:= Table[Subscript[d, n], {n, 1, Length#dist}] === folded
Out[4]= True