Function in Pine Script with break - function

I have a function in pine script:
fun_check(Sell_Signal) =>
Base_Sell1 = Sell_Signal[0]
for i=0 to 150
if (Sell_Signal[i] == 1)
Base_Sell1 = 5
break
Base_Sell1
B_Sell = fun_check(Sell_Signal)
My function always returns the value as 1, but it should return a value as 5

You are missing : while assigning values to Base_Sell1 in the loop as Base_Sell1 is mutable variable
It should be:
Base_Sell1 := 5

Related

can't extract value from Function

function takes for example rsi and from declared for me historical bar 1 to 12 finds me maximum value ( integer or '00,0') of rsi.
//#version=5
indicator("loop", shorttitle="loop")
len = input.int(14, title="RSI Length")
src = input.source(close, "RSI Source")
Rsi = ta.rsi(src, len)
plot(Rsi*10, "RSI", color=#673ed8)
hline(65,linestyle= hline.style_dashed , color=color.new(color.red, 0))
minF = 1, maxF = 12, RsiFunction = Rsi
ff_loopMax(RsiFunction,minF, maxF) =>
var float Max = na
var float MaxOdpCena = na
var int MaxNrBar = na
for i=minF to maxF
if i == minF
Max := RsiFunction[i]
//MaxOdpCena := high[i]
//MaxNrBar := i
else
//MaxOdpCena := Max > RsiFunction[i] ? MaxOdpCena : high[i]
//MaxNrBar := Max > RsiFunction[i] ? MaxNrBar : i
Max := math.max(Max,RsiFunction[i])
// I want Max result from function
plot(Max, "rsiMax", color=#b63253)
Result = ff_loopMax(Rsi,5,15)
The code extracted from function should work alone. But I can't cope with function.
A function in pine script return the value of the last expression. In your case, the last expression is Max, but you can't access this directly. You call the function, and set this return to a variable.
You should change the last two lines to:
Result = ff_loopMax(Rsi,5,15) // Result is now equal to Max
plot(Result, "rsiMax", color=#b63253)

Use varargin for multiple arguments with default values in MATLAB

Is there a way to supply arguments using varargin in MATLAB in the following manner?
Function
func myFunc(varargin)
if a not given as argument
a = 2;
if b not given as argument
b = 2;
if c not given as argument
c = a+b;
d = 2*c;
end
I want to call the above function once with b = 3 and another time while the previous one is running in the same command window with a = 3 and c = 3 and letting b take the default value in the function this time. How can it be done using varargin?
Here's the latest and greatest way to write the function (using arguments blocks from R2019b)
function out = someFcn(options)
arguments
options.A = 3;
options.B = 7;
options.C = [];
end
if isempty(options.C)
options.C = options.A + options.B;
end
out = options.A + options.B + options.C;
end
Note that this syntax does not allow you to say options.C = options.A + options.B directly in the arguments block.
In MATLAB < R2021a, you call this like so
someFcn('A', 3)
In MATLAB >= R2021a, you can use the new name=value syntax
someFcn(B = 7)
Here are two ways to do this which have been available since 2007a (i.e. a long time!). For a much newer approach, see Edric's answer.
Use nargin and ensure your inputs are always in order
Use name-value pairs and an input parser
nargin: slightly simpler but relies on consistent input order
function myFunc( a, b, c )
if nargin < 1 || isempty(a)
a = 2;
end
if nargin < 2 || isempty(b)
b = 2;
end
if nargin < 3 || isempty(c)
c = a + b;
end
end
Using the isempty check you can optionally provide just later arguments, for example myFunc( [], 4 ) would just set b=4 and use the defaults otherwise.
inputParser: more flexible but can't directly handle the c=a+b default
function myFunc( varargin )
p = inputParser;
p.addOptional( 'a', 2 );
p.addOptional( 'b', 2 );
p.addOptional( 'c', NaN ); % Can't default to a+b, default to NaN
p.parse( varargin{:} );
a = p.Results.a;
b = p.Results.b;
c = p.Results.c;
if isnan(c) % Handle the defaulted case
c = a + b;
end
end
This would get used like myFunc( 'b', 4 );. This approach is also agnostic to the input order because of the name-value pairs, so you can also do something like myFunc( 'c', 3, 'a', 1 );

Lua nested Json, remove single occurs or list of occurs if multiple

So what I am trying to do here is for a given json_body which is decoded json into a table using cjson I want to remove a given element by a configurable value conf.remove.json, I feel I am pretty close but its still not working, and is there a better way? Is there a safe way to find the tables "depth" and then reach out like conf.remove.json= I.want.to.remove.this creates the behavior json_table[I][want][to][remove][this] = nil without throwing some kind of NPE?
local configRemovePath= {}
local configRemoveDepth= 0
local recursiveCounter = 1
local function splitString(inputstr)
sep = "%." --Split on .
configRemovePath={}
configRemoveDepth=0
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
configRemovePath[configRemoveDepth + 1] = str
configRemoveDepth = configRemoveDepth + 1
end
end
local function recursiveSearchAndNullify(jsonTable)
for key, value in pairs(jsonTable) do --unordered search
-- First iteration
--Sample Json below, where conf.remove.json = data.id and nothing happened. conf.remove.json=data.id
--{
--"data": {
-- "d": 2,
-- "id": 1
--}
--}
-- value = {"d": 2, "id": 1}, key = "data", configRemovePath[recursiveCounter] = "data" , configRemovePath ['data','id'] , configRemoveDepth = 2
if(type(value) == "table" and value == configRemovePath[recursiveCounter] and recursiveCounter < configRemoveDepth) then --If the type is table, the current table is one we need to dive into, and we have not exceeded the configurations remove depth level
recursiveCounter = recursiveCounter + 1
jsonTable = recursiveSearchAndNullify(value)
else
if(key == configRemovePath[recursiveCounter] and recursiveCounter == configRemoveDepth) then --We are at the depth to remove and the key matches then we delete.
for key in pairs (jsonTable) do --Remove all occurances of said element
jsonTable[key] = nil
end
end
end
end
return jsonTable
end
for _, name in iter(conf.remove.json) do
splitString(name)
if(configRemoveDepth == 0) then
for name in pairs (json_body) do
json_body[name] = nil
end
else
recursiveCounter = 1 --Reset to 1 for each for call
json_body = recursiveSearchAndNullify(json_body)
end
end
Thanks to any who assist, this is my first day with Lua so I am pretty newb.
This is the official answer, found a better way with the help of Christian Sciberras!
local json_body_test_one = {data = { id = {"a", "b"},d = "2" }} --decoded json w cjson
local json_body_test_two = {data = { { id = "a", d = "1" }, { id = "b", d = "2" } } }
local config_json_remove = "data.id"
local function dump(o) --Method to print test tables for debugging
if type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then k = '"'..k..'"' end
s = s .. '['..k..'] = ' .. dump(v) .. ','
end
return s .. '} '
else
return tostring(o)
end
end
local function splitstring(inputstr, sep)
if sep == nil then
sep = "%." --Dot notation default
end
local t={} ; i=1
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
t[i] = str
i = i + 1
end
return t
end
local function setjsonprop(json_object, path, newvalue)
local configarray = splitstring(path)
while (#configarray > 1) do
json_object = json_object[table.remove(configarray, 1)]
if(type(json_object) == "table" and #json_object > 0) then
local recursepath = table.concat(configarray, ".")
for _, item in pairs(json_object) do
setjsonprop(item, recursepath, newvalue)
end
return
end
end
json_object[table.remove(configarray, 1)] = newvalue
end
setjsonprop(json_body_test_one, config_json_remove, nil)
print(dump(json_body_test_one))

Why isn't my return statement working?

I have a function that converts a decimal value to binary. I understand I have the logic correct as I can get it to work outside of a function.
def decimaltobinary(value):
invertedbinary = []
value = int(value)
while value >= 1:
value = (value / 2)
invertedbinary.append(value)
value = int(value)
for n, i in enumerate(invertedbinary):
if (round(i) == i):
invertedbinary[n] = 0
else:
invertedbinary[n] = 1
invertedbinary.reverse()
value = ''.join(str(e) for e in invertedbinary)
return value
decimaltobinary(firstvalue)
print (firstvalue)
decimaltobinary(secondvalue)
print (secondvalue)
Let's say firstvalue = 5 and secondvalue = 10. The values returned each time the function is executed should be 101 and 1010 respectively. However, the values I get printed are the starting values of five and ten. Why is this happening?
The code works as expected, but you didn't assign the returned value:
>>> firstvalue = decimaltobinary(5)
>>> firstvalue
'101'
Note that there are easier ways to accomplish your goal:
>>> str(bin(5))[2:]
'101'
>>> "{0:b}".format(10)
'1010'

I'm trying to do Ackermann's Function on IBasic

Ackermann's Function is a recursive mathematical algorithm that can be used to test how well a computer performs recursion. Design a function ackermann(m,n), which solves Ackermann's Function. Use the following logic in your function:
If m = 0, then return n + 1
If n = 0 then return ackermann(m-1, 1)
Otherwise, return ackermann(m-1, ackermann(m, n-1))
The program stops after it hits 13. Can anyone tell me what I have done wrong?
declare main()
declare ackermann(m:int, n:int)
openconsole
main()
print:print "Press any key to quit...",
do:until inkey$<>""
closeconsole
end
sub main()
def counter, m, n:int
counter = 0
for counter = 1 to 100
print ackermann(counter)
next counter
return
sub ackermann(m, n)
if m = 0
return = n + 1
else
if n = 0
return = ackermann(m - 1, 1)
else
return = ackermann(m - 1, ackermann(m, n - 1))
endif
endif
return
Your print statement is
print ackermann(counter)
but your function is
sub ackermann(m, n)
You need to send a second parameter in the first call.
Do note that Ackermann's function grows incredibly quickly - values above m,n > (3,4) are going to have a LOT of digits and if you go more than even about (4,4) you'll quickly find numbers that could quite possibly fill up your memory entirely with digits...
Refer to Wikipedia to see the magnitude of the numbers you are trying to compute...
declare main()
declare ackermann(m:int, n:int)
openconsole
main()
print:print "Press any key to quit...",
do:until inkey$<>""
closeconsole
end
sub main()
print Ackermann(3,5)
return
sub ackermann(m, n)
if m = 0
return = n + 1
else
if n = 0
return = ackermann(m - 1, 1)
else
return = ackermann(m - 1, ackermann(m, n - 1))
endif
endif
return