I'm new to Pine Script and I've been struggling to understand the logic behind the if/else Pine Script's operators. I can understand all the simple examples that I could find online, but when it comes to the particular code I want to translate into Python, it becomes more difficult. Here is the nested loop I'm struggling to understand:
hi:=hi[1]?high[1]>=stop[1]?false:true:low[1]<=stop[1]?true:false
stop:=hi?max1:min1
stop:=hi?hi[1]==false?stop:stop>stop[1]?stop[1]:stop:hi[1]?stop:stop<stop[1]?stop[1]:stop
As I've mentioned before my goal is to translate this snippet of code into Python. Thank you guys for help!
P.S. this is Pine Script v4
You can convert any ternary (?:) construction to an if-then-else on this website
The [1] does not denote an array, but is a history referencing operator.
With that, you can access values on previous bars.
First example
hi:=hi[1]?high[1]>=stop[1]?false:true:low[1]<=stop[1]?true:false
becomes
hi :=
if (hi[1]) {
if (high[1] >=stop[1]) {
false
} else {
true
}
} else {
if (low[1] <=stop[1]) {
true
} else {
false
}
}
Second example
stop:=hi?max1:min1
becomes
stop:=
if (hi) {
max1
} else {
min1
}
Third example
stop:=hi?hi[1]==false?stop:stop>stop[1]?stop[1]:stop:hi[1]?stop:stop<stop[1]?stop[1]:stop
becomes
stop :=
if (hi) {
if (hi[1]==false) {
stop
} else {
if (stop>stop[1]) {
stop[1]
} else {
stop
}
}
} else {
if (hi[1]) {
stop
} else {
if (stop<stop[1]) {
stop[1]
} else {
stop
}
}
}
Related
So I keep running into a issue where json is asking to use a int to find pieces of data in a json response. Below is the code that works though the issue is i want to print every 'name' in the json though id have to change the [0] to 1 and then 2 ect. I tried to increment it though that ran into issue too. This could be just me overlooking something but let me know, thanks.
def BaseTesting(TarLink):
PayloadToSend = {
}
HeadersToSend = { # make sure to change your token at least once every 30 mins
'authorization': '',
'user-agent': ''
}
ReqForFriends = requests.post(TarLink, headers=HeadersToSend, data=PayloadToSend).text
LoadedJSONData = json.loads(ReqForFriends)
print(LoadedJSONData['friends'][0]['name'])
BaseTesting(TarLink="")
JSON
{
"friends":[
{
"name":"test1",
"user_id":"1132",
"type":2,
"display":"true",
},
{
"name":"test2",
"user_id":"2341",
"type":1,
"display":"true",
},
{
"name":"test3",
"user_id":"1234",
"type":2,
"display":"true",
},
}
it seems to work properly
LoadedJSONData = {
"friends":[
{
"name":"test1",
"user_id":"1132",
"type":2,
"display":"true",
},
{
"name":"test2",
"user_id":"2341",
"type":1,
"display":"true",
},
{
"name":"test3",
"user_id":"1234",
"type":2,
"display":"true",
},
]
}
for i in range(0,3):
print(LoadedJSONData['friends'][i]['name']) #test1 test2 test3
I have a collection of accounts and I am trying to find an account in which the targetAmount >= totalAmount + N
{
"_id": {
"$oid": "60d097b761484f6ad65b5305"
},
"targetAmount": 100,
"totalAmount": 0,
"highPriority": false,
"lastTimeUsed": 1624283088
}
Now I just select all accounts, iterate over them and check if the condition is met. But I'm trying to do this all in a query:
amount = 10
tasks = ProviderAccountTaskModel.objects(
__raw__={
'targetAmount': {
'$gte': {'$add': ['totalAmount', amount]}
}
}
).order_by('-highPriority', 'lastTimeUsed')
I have also tried using the $sum, but both options do not work.
Can't it be used when searching, or am I just going the wrong way?
You can use a $where. Just be aware it will be fairly slow (has to execute Javascript code on every record) so combine with indexed queries if you can.
db.getCollection('YourCollectionName').find( { $where: function() { return this.targetAmount > (this.totalAmount + 10) } })
or more compact way of doing it will be
db.getCollection('YourCollectionName').find( { $where: "this.targetAmount > this.totalAmount + 10" })
You have to use aggregation instead of the find command since self-referencing of documents in addition to arithmetic operations won't work on it.
Below is the aggregation command you are looking for. Convert it into motoengine equivalent command.
db.collection.aggregate([
{
"$match": {
"$expr": {
"$gte": [
"$targetAmount",
{
"$sum": [
"$totalAmount",
10
]
},
],
},
},
},
{
"$sort": {
"highPriority": -1,
"lastTimeUsed": 1,
},
},
])
Mongo Playground Sample Execution
Here is an example of if-else statement in javascript.
function getTranslation(rhyme) {
if (rhyme.toLowerCase() === "apples and pears") {
return "Stairs";
} else if (rhyme.toLowerCase() === "hampstead heath") {
return "Teeth";
} else if (rhyme.toLowerCase() === "loaf of bread") {
return "Head";
} else if (rhyme.toLowerCase() === "pork pies") {
return "Lies";
} else if (rhyme.toLowerCase() === "whistle and flute") {
return "Suit";
}
return "Rhyme not found";
}
A more elegant way is to rewrite the if-else implementation using object.
function getTranslationMap(rhyme) {
const rhymes = {
"apples and pears": "Stairs",
"hampstead heath": "Teeth",
"loaf of bread": "Head",
"pork pies": "Lies",
"whistle and flute": "Suit",
};
return rhymes[rhyme.toLowerCase()] ?? "Rhyme not found";
}
Can python be used to write similar elegant code like javascript object literals?
I am using python 3.8
Javascript code segment is from link below;
https://betterprogramming.pub/dont-use-if-else-and-switch-in-javascript-use-object-literals-c54578566ba0
Python equivalent:
def get_translation_map(rhyme):
rhymes = {
"apples and pears": "Stairs",
"hampstead heath": "Teeth",
"loaf of bread": "Head",
"pork pies": "Lies",
"whistle and flute": "Suit"
}
return rhymes.get(rhyme.lower(), "Rhyme not found")
Another useful variation if you don't know the content of the dict and want to ensure a value is always returned:
v = adict.get('whatever') or 'default'
Would get a default value even if a there was a key with a None value in the dict
I have a json file called pool.json which contains this:
{
"pools": {
"$poolId": {
"nodes": {
"$nodeId": {
"bcm": {
"address": {
"ip": "10.10.10.10"
},
"password": "ADMIN",
"username": "ADMIN"
}
}
}
}
}
}
This is my Python code:
pool_id = ['123456']
json_pool = json.loads(read_json_file('pool.json'))
for i in pool_id:
json_pool['pools'][i] = json_pool.pop(['pools']['$poolId'])
print('json_pool: %s' % json_pool)
I'm trying to update $poolId with the value in pool_id(I know I've only got one pool_id. I just want to get this piece working before I do anything else). Ive been trying to do this with pop but am having no success when it's nested as in this case. I can get it working when I want to change a top level key. What am I doing wrong?
I think you want to execute json_pool['pools'].pop('$poolId') instead of json_pool.pop(['pools']['$poolId']).
For the JSON below, I want to add/update an item to "bonuses". Is there a way I can directly put a the variable {"name": "ham", "bonus": 12} ?
{
"abilities": {
"FGI": {
"score": 10,
"mod": 1,
"bonuses": [
{
"name": "spam",
"bonus": 1
},
{
"name": "eggs",
"bonus": 1
}
]
}
}
}
NOTE: I should clarify that the "JSON" is a Python Object built from a JSON String.
abilities.FGI.bonuses.push({"name": "ham", "bonus": 12});
EDIT or:
abilities["FGI"]["bonuses"].push(..);
That'll be a fun one! There isn't really an easy (built-in) way to do it. In markusf's answer, he mentions pushing at item on the end, but that's only half of your problem. If you want to make sure there's not already a "ham" item in there, you'll have to loop through it using a function like this:
function array_has_item_already(array, key, look_for_key_value) {
for( var i = 0; i < array.length; i++) {
if( typeof array[i][key] != 'undefined' && array[i][key] == look_for_key_value )
return array[i];
}
return false;
}
you'd call it like this, and it would return false if it didn't find the item:
array_has_item_already(abilities.FGI.bonuses, "name", "ham");
I'll leave it to you to push the function out to make it update or push or whatever. Have fun!
UPDATE
I just realized that you're looking for something in python. Welp, you can completely disregard my answer, or translate it, as it's in js. HA.