Cannot modify global variable 'buyLimit' in function PineScript - global-variables

I am new to TradingView Pine scripting. can you help me about error " Cannot modify global variable 'buyLimit' in function". How i can modif my code to run in security() function.
Thx Before
When i Compile i found error "Cannot modify global variable 'buyLimit' in function".
float buyLimit = na
ShortSignalFunc() =>
buyLimit := (highestHigh - base) / base > bounce and low < base * (1 - baseCrack) ? base * (1 - baseCrack) : na

Try declaring variables locally to your function. eg.
ShortSignalFunc() =>
float buyLimit = na
buyLimit := (highestHigh - base) / base > bounce and low < base * (1 - baseCrack) ? base * (1 - baseCrack) : na
Also, since you only have the one conditional statement for this variable, the following will likely work as well where we just use "=" and dont bother re-assigning.
ShortSignalFunc() =>
buyLimit = (highestHigh - base) / base > bounce and low < base * (1 - baseCrack) ? base * (1 - baseCrack) : na
If a global variable does need to be altered, you can create a new one and then use the funciton to assign it within the global scope.
Cheers my friend

Related

How can I customize an object of the class "expression"? I need to write a function for which the parameters change

I am trying to write an expression for which I need to find the parameters, but once I define the parameters to come from another variable, the expression does not recognize them. For example:
This works fine:
expression(2*x*exp(-3*t))
I get:
expression(2 * x * exp(-3 * t))
But the issue is that I don't know if 2 and 3 are the right values (I'm trying to find them). So I tried to put this into a function like this:
exp.fx <- function(params){
u <- params[1]
D <- params[2]
expr1 <- expression(u*x*exp(-D*t))
return(expr1)
}
And this is what I get:
> exp.fx(c(2,3))
u * x * exp(-D * t)
I need to get instead
2 * x * exp(-3 * t)
Bottom line, I need to put these two parameters into an optim so I can try to find them and that's why I need a function that changes the expression each time accordingly.
What you are looking for is interpolation or injection. There are lots of different ways of achieving it. My favourite way is to use bquote instead of quote/expression:
exp_fx <- function (params) {
u <- params[1L]
D <- params[2L]
bquote(.(u) * x * exp(-.(D) * t))
}
(Note that there’s no need for the expr variable, or for the return() function call; I’ve also replaced the . in the function name by _ since . can lead to confusion with S3 methods, and is therefore potentially problematic.)
An alternative is to use substitute:
exp_fx <- function (params) {
substitute(
u * x * exp(-D * t),
list(u = params[1L], D = params[2L])
)
}

Logic of computing a^b, and is power a keyword?

I found the following code that is meant to compute a^b (Cracking the Coding Interview, Ch. VI Big O).
What's the logic of return a * power(a, b - 1); ? Is it recursion
of some sort?
Is power a keyword here or just pseudocode?
int power(int a, int b)
{ if (b < 0) {
return a; // error
} else if (b == 0) {
return 1;
} else {
return a * power(a, b - 1);
}
}
Power is just the name of the function.
Ya this is RECURSION as we are representing a given problem in terms of smaller problem of similar type.
let a=2 and b=4 =calculate= power(2,4) -- large problem (original one)
Now we will represent this in terms of smaller one
i.e 2*power(2,4-1) -- smaller problem of same type power(2,3)
i.e a*power(a,b-1)
If's in the start are for controlling the base cases i.e when b goes below 1
This is a recursive function. That is, the function is defined in terms of itself, with a base case that prevents the recursion from running indefinitely.
power is the name of the function.
For example, 4^3 is equal to 4 * 4^2. That is, 4 raised to the third power can be calculated by multiplying 4 and 4 raised to the second power. And 4^2 can be calculated as 4 * 4^1, which can be simplified to 4 * 4, since the base case of the recursion specifies that 4^1 = 4. Combining this together, 4^3 = 4 * 4^2 = 4 * 4 * 4^1 = 4 * 4 * 4 = 64.
power here is just the name of the function that is defined and NOT a keyword.
Now, let consider that you want to find 2^10. You can write the same thing as 2*(2^9), as 2*2*(2^8), as 2*2*2*(2^7) and so on till 2*2*2*2*2*2*2*2*2*(2^1).
This is what a * power(a, b - 1) is doing in a recursive manner.
Here is a dry run of the code for finding 2^4:
The initial call to the function will be power(2,4), the complete stack trace is shown below
power(2,4) ---> returns a*power(2,3), i.e, 2*4=16
|
power(2,3) ---> returns a*power(2,2), i.e, 2*3=8
|
power(2,2) ---> returns a*power(2,1), i.e, 2*2=4
|
power(2,1) ---> returns a*power(2,0), i.e, 2*1=2
|
power(2,0) ---> returns 1 as b == 0

Convert sin calculation to use per-frame delta

I currently have a function that updates a value using the sin function, and a timeFactor double that keeps track of how much time has passed since the program started:
double timeFactor;
double delta;
while(running) {
delta = currentTime - lastTime;
timeFactor += delta;
var objectX = sin(timeFactor);
}
However, I need to convert this code to use the delta rather than the timeFactor.
I.e. For updating to sin(time+delta) I only want to use the current value of sin(time) and anything calculated from the value of delta.
I.e. calcualte sin(time+delta) == f(sin(time),delta)
How do I do this?
From math:
sin(A + B) == sin(A) * cos(B) + cos(A) * sin(B)
cos(A + B) == cos(A) * cos(B) - sin(A) * sin(B)
Store sin(A) and cos(A) in two variables.
Then for updating them use temporary copy of one of them, otherwise you will update the second using the new instead of the old value of the first.
Assuming:
persistent objectX stores current and is initialised with initial sin(timeFactor)
persistent objectXc stores current and is initialised with initial cos(timeFactor)
temporary objectXt stores a copy of objectX
("persistent" as in "keeps value across executions of update code",
in contrast to "temporary" as in "only keeps value during update code";
this is to avoid using the "global" attribute, which implies poor data design)
Update code:
objectXt = objectX;
objectX = objectX * cos(delta) + objectXc * sin(delta);
objectXc = objectXc* cos(delta) - objectXt * sin(delta);
Credits to John Coleman for spotting the problem in initial idea to use
1 == sin(A)*sin(A)+cos(A)*cos(A)
That would have been actually
sin(time+delta)== f(sin(time), delta)
But it fails for 50% of a full period.
So I hope this
sin(time+delta)==f(sin(time), cos(time), delta)
also helps.

Generating random math equation using tree - Avoiding Parentheses

Edit: This was originally on programmers.stackexchange.com, but since I already had some code I thought it might be better here.
I am trying to generate a random math problem/equation. After researching the best (and only) thing I found was this question: Generating random math expression. Because I needed all 4 operations, and the app that I will be using this in is targeted at kids, I wanted to be able to insure that all numbers would be positive, division would come out even, etc, I decided to use a tree.
I have the tree working, and it can generate an equation as well as evaluate it to a number. The problem is that I am having trouble getting it to only use parentheses when needed. I have tried several solutions, that primaraly involve:
Seeing if this node is on the right of the parent node
Seeing if the node is more/less important then it's parent node (* > +, etc).
Seeing if the node & it's parent are of the same type, and if so if the order matters for that operation.
Not that it matters, I am using Swift, and here is what I have so far:
func generateString(parent_node:TreeNode) -> String {
if(self.is_num){
return self.equation!
}
var equation = self.equation!
var left_equation : String = self.left_node!.generateString(self)
var right_equation : String = self.right_node!.generateString(self)
// Conditions for ()s
var needs_parentheses = false
needs_parentheses = parent_node.importance > self.importance
needs_parentheses = (
needs_parentheses
||
(
parent_node.right_node?.isEqualToNode(self)
&&
parent_node.importance <= self.importance
&&
(
parent_node.type != self.type
&&
( parent_node.order_matters != true || self.order_matters != true )
)
)
)
needs_parentheses = (
needs_parentheses
&&
(
!(
self.importance > parent_node.importance
)
)
)
if (needs_parentheses) {
equation = "(\(equation))"
}
return equation.stringByReplacingOccurrencesOfString("a", withString: left_equation).stringByReplacingOccurrencesOfString("b", withString: right_equation)
}
I have not been able to get this to work, and have been banging my head against the wall about it.
The only thing I could find on the subject of removing parentheses is this: How to get rid of unnecessary parentheses in mathematical expression, and I could not figure out how to apply it to my use case. Also, I found this, and I might try to build a parser (using PEGKit), but I wanted to know if anybody had a good idea to either determine where parentheses need to go, or put them everywhere and remove the useless ones.
EDIT: Just to be clear, I don't need someone to write this for me, I am just looking for what it needs to do.
EDIT 2: Since this app will be targeted at kids, I would like to use the least amount of parentheses possible, while still having the equation come out right. Also, the above algorithm does not put enough parentheses.
I have coded a python 3 pgrm that does NOT use a tree, but does successfully generate valid equations with integer solutions and it uses all four operations plus parenthetical expressions. My target audience is 5th graders practicing order of operations (PEMDAS).
872 = 26 * 20 + (3 + 8) * 16 * 2
251 = 256 - 3 - 6 + 8 / 2
367 = 38 * 2 + (20 + 15) + 16 ** 2
260 = 28 * 10 - 18 - 4 / 2
5000 = 40 * 20 / 4 * 5 ** 2
211 = 192 - 10 / 2 / 1 + 24
1519 = 92 * 16 + 6 + 25 + 16
If the python of any interest to you ... I am working on translating the python into JavaScript and make a web page available for students and teachers.

Redefine the infix operators

I am learning Jason Hickey's Introduction to Objective Caml.
Just have a question about Redefine the infix operators.
So in the book, there is such a paragraph:
# let (+) = ( * )
and (-) = (+)
and ( * ) = (/)
and (/) = (-);;
val + : int > int > int = <fun>
val - : int > int > int = <fun>
val * : int > int > int = <fun>
val / : int > int > int = <fun>
# 5 + 4 / 1;;
-: **int = 15**
First, how does these redefinition work?
To me, it seems the functions are running in a kind of indefinite loop, because all the operations seem redefined and connected.
for example, if I do 1+2, then it will be 1 * 2 and since ( * ) = (/), it will be then 1 / 2 and since (/) = (-), then it will be 1-2, so on so forth. Am I right?
Second, will the result of 5 + 4 / 1 be 15, even if the functions are executed only one step further in the redefinition?
So assume the redefinition will be execute one step further, i.e., 1 + 2 will only be 1 * 2 and no more transform, so 5 + 4 / 1 should be 5 * 4 -1, right? then the answer is 19. Am I correct?
To me, it seems the functions are running in a kind of indefinite
loop, because all the operations seem redefined and connected.
Not really, it's just a simultaneous re-definition of infix operators (with the and keyword). What you see is not a recursive definition. In OCaml, recursive definitions are made with let rec (as you may already know).
For the second part of the question, I think it's a matter of operator precedence. Note that in the original expression 5 + 4 / 1 is actually 5 + (4/1) following the usual precedence rules for arithmetic operators. So, I think the conversion simply preserves this binding (sort of). And you get 5 * (4 - 1) = 15.
The key observation (IMHO) is that (+) is being defined by the preexisting definition of ( * ), not by the one that appears a few lines later. Similarly, ( * ) is being defined by the preexisting definition of (/). As Asiri says, this is because of the use of let rather than let rec.
It's also true that in OCaml, precedence and associativity are inherent in the operators and can't be changed by definitions. Precedence and associativity are determined by the first character of the operator.
If you look at the table of operator precedences and associativities in Section 6.7 of the OCaml Manual, you'll see that all the entries are defined for "operators beginning with character X".

Resources