I'm making a CoinBasePro TradingBot and I've got some error with trying to make a position.
class Trader():
def __init__(self):
self.public = 'Public'
self.passphrase = 'Passphrase'
self.secret = 'Secret'
self.auth_client = cbpro.AuthenticatedClient(key= self.public, b64secret= self.secret, passphrase= self.passphrase)
Then, there is some RSI calculation function (float output) and direction function.
Next thing is to make a position function:
def make_pos(self, ticker):
rsi = self.RSI_calc(ticker)
direction = self.set_direction(ticker)
if rsi <= 42 and direction == 'buy':
position = self.auth_client.place_market_order(product_id= ticker, side=direction, size= self.QUANTITY)
print(position)
You know, it should output something like {
"id": "d0c5340b-6d6c-49d9-b567-48c4bfca13d2",
"price": "0.10000000",
"size": "0.01000000",
"product_id": "BTC-USD",
"side": "buy",
"stp": "dc",
"type": "limit",
"time_in_force": "GTC",
"post_only": false,
"created_at": "2016-12-08T20:02:28.53864Z",
"fill_fees": "0.0000000000000000",
"filled_size": "0.00000000",
"executed_value": "0.0000000000000000",
"status": "pending",
"settled": false
}
, but it returns {'message': 'Forbidden'}
Any hints please?
My thanks.
Related
I am learning and having much fun with python, currently I am making a simple discord bot but I am stuck with nested dictionary access problem.
This is my command
#bot.command()
async def burek(ctx, arg):
burek_seller = burek_dictionary["bureks"][arg]["seller"]
burek_price = burek_dictionary["bureks"][arg]["price"]
burek_state = burek_dictionary["bureks"][arg]["state"]
burek_name = burek_dictionary["bureks"][arg]["name"]
await ctx.send(
f"{burek_name} is available {burek_state} at {burek_seller} for {burek_price}$."
)
The problem is I want to change 'arg' to search by 'name' in my nested dictionary not by a number of nested dictionary. I am aware I will have to make a few changes, but I have been stuck trying to figure it out for two days now :(
this is my dictionary
burek_dictionary = {
"bureks": {
"0": {
"name": "mesni",
"ingredient": "govedina",
"seller": "sipac",
"price": 2.2,
"state": "hot",
"demand": "low",
},
"1": {
"name": "sirni",
"ingredient": "sir",
"seller": "merc",
"price": 1.8,
"state": "cold",
"demand": "average",
},
"2": {
"name": "spinacni",
"ingredient": "spinaca",
"seller": "pecjak",
"price": 2,
"state": "fresh",
"demand": "high",
},
"3": {
"name": "ajdov",
"ingredient": "sirspinaca",
"price": 2.1,
"state": "hot",
"demand": "average",
},
}
}
Obviously now as 'arg' I have to write a number to achieve my result, but I would like to use 'name' from dictionary and achieve the same result. I have no idea idea how to approach this. I hope it makes sense! Thank you.
Sure.
Loop through the bureks and when you find the one with the matching name, use that.
I assume you might need the same functionality somewhere else, so I broke it out into a separate function.
def find_burek_by_name(name):
for burek_key, burek_info in burek_dictionary["bureks"].items():
if burek_info["name"] == name:
return burek_info
return None # Not found
#bot.command()
async def burek(ctx, arg):
burek_info = find_burek_by_name(arg)
if burek_info:
burek_seller = burek_info["seller"]
burek_price = burek_info["price"]
burek_state = burek_info["state"]
burek_name = burek_info["name"]
await ctx.send(
f"{burek_name} is available {burek_state} at {burek_seller} for {burek_price}$."
)
else:
pass # No such burek
If you know the entire dictionary beforehand, you can build a map from names to numbers, if the dict does not change you build the map in a single pass and avoid looping later:
name2num = {}
for num in burek_dictionary["bureks"]:
name2num[burek_dictionary["bureks"][num]["name"]] = num
print(name2num)
name = "sirni"
num = name2num[name]
burek_seller = burek_dictionary["bureks"][num]["seller"]
burek_price = burek_dictionary["bureks"][num]["price"]
burek_state = burek_dictionary["bureks"][num]["state"]
burek_name = burek_dictionary["bureks"][num]["name"]
print(burek_seller, burek_price, burek_state, burek_name)
Cheers!
I'm trying to use this code as a lambda function so it will print the text as the output but I can't seem to figure it out. The lambda should be invoked in the event any of the values stored in critical_count, medium_count, or high_count exceed the values stored in CRITICAL, MEDIUM OR HIGH.
I have tried printing them directly but that doesn't work. I trying making them into variables but that didn't work either. Any help would be greatly appreciated
import json
def lambda_handler(event, context):
CRITICAL = 0
MEDIUM = 1
HIGH = 0
f = open('ECR_scan.json', )
test = json.loads(f)
resource = test["resources"][0]
finding_severity_counts = test["detail"]["finding-severity-counts"]
if "CRITICAL" in finding_severity_counts:
critical_count = finding_severity_counts["CRITICAL"]
if critical_count > CRITICAL:
print("Resource {} has {} critical findings".format(resource, critical_count))
if "MEDIUM" in finding_severity_counts:
medium_count = finding_severity_counts["MEDIUM"]
f medium_count > MEDIUM:
print("Resource {} has {} medium findings".format(resource, medium_count))
if "HIGH" in finding_severity_counts:
high_count = finding_severity_counts["HIGH"]
if high_count > HIGH:
print("Resource {} has {} high findings".format(resource, high_count))
return {
'statusCode': 200,
'body':
Here is the json file I am envoking as well
"version": "0",
"id": "85fc3613-e913-7fc4-a80c-a3753e4aa9ae",
"detail-type": "ECR Image Scan",
"source": "aws.ecr",
"account":
"123456789012",
"time": "2019-10-29T02:36:48Z",
"region": "us-east-1",
"resources": [
"arn:aws:ecr:us-east-1:123456789012:repository/my-repo"
],
"detail": {
"scan-status": "COMPLETE",
"repository-name": "my-repo",
"finding-severity-counts": {
"CRITICAL": 10,
"MEDIUM": 9
}
}
}
How can I get the name of json object so that I can match on it in an if statement?
def test():
device_config = api_get_conf()
routing_protocol = device_config['Cisco-IOS-XE-native:native']
if 'ospf' in routing_protocol:
print('It worked!')
else:
print('dunno')
The routing_protocol variable has the following information in it:
{"Cisco-IOS-XE-ospf:router-ospf": {
"ospf": {
"process-id": [
{
"id": 100,
"area": [
{
"area-id": 0,
"authentication": {
"message-digest": [
null
]
}
}
],
"network": [
{
"ip": "192.168.200.200",
"wildcard": "0.0.0.0",
"area": 0
}
]
}
]
}
}
}
I would like to match on only 'Cisco-IOS-XE-ospf:router-ospf' or 'ospf'. Any help on how I can do this would be appreciated.
def test():
device_config = api_get_conf()
# since we use get here, if we dont find it we set routing_protocol as False, easier to use on if
routing_protocol = device_config.get('Cisco-IOS-XE-native:native', False)
if routing_protocol:
if 'ospf' in routing_protocol:
print('It worked!')
print("ospf not a key")
else:
print('routing protocol not a key')
I'm not sure what you mean, but it looks like api_get_conf() returns Dictionary where "Cisco-IOS-XE-ospf:router-ospf" is first key, and its value is another dictionary where key is "ospf". If it's what you wants to compare then you can simply use .keys() method on routing_protocol dict.
def test():
device_config = api_get_conf()
routing_protocol = device_config['Cisco-IOS-XE-native:native']
if 'ospf' in routing_protocol.keys():
print('It worked!')
else:
print('dunno')
When I was designing my Ui by Tkinter tool, I was confused by some codes from others. From the code below, it has a function my_coinportfolio to trigger the loop, which is to create Label. However, this function doesn't return anything. My question is why I can still see result printed on screen?
Please shed some lights to me.
api_response = [
{
"id": "bitcoin",
"name": "Bitcoin",
"symbol": "BTC",
"rank": "1",
"price_usd": "9451.36954216",
"price_btc": "1.0",
"24h_volume_usd": "13472387097.5",
"market_cap_usd": "168674102818",
"available_supply": "17846525.0",
"total_supply": "17846525.0",
"max_supply": "21000000.0",
"percent_change_1h": "-0.13",
"percent_change_24h": "-2.0",
"percent_change_7d": "-7.08",
"last_updated": "1564463368"
},
{
"id": "ethereum",
"name": "Ethereum",
"symbol": "ETH",
"rank": "2",
"price_usd": "207.595410461",
"price_btc": "0.02198341",
"24h_volume_usd": "5469338196.61",
"market_cap_usd": "22235200091.0",
"available_supply": "107108341.0",
"total_supply": "107108341.0",
"max_supply": None,
"percent_change_1h": "-0.01",
"percent_change_24h": "-2.52",
"percent_change_7d": "-3.26",
"last_updated": "1564463364"
}]
pycryptp = Tk()
pycryptp.title("Digital Currency Application")
## Define Heading
name = Label(pycryptp, text = 'Coin Symbol')
name.grid(row = 0, column = 0)
price = Label(pycryptp, text = 'Price')
price.grid(row = 0, column = 1)
holding_amount = Label(pycryptp, text = 'Holding Amount')
holding_amount.grid(row = 0, column = 2)
proftloss = Label(pycryptp, text = 'Profit & Loss')
proftloss.grid(row = 0, column = 3)
## Define Function for app
def my_coinportfolio():
coin_buyinfo = [
{
"symbol": "BTC",
"number_of_coins": 2,
"buy_price": 3200
},
{
"symbol": "ETH",
"number_of_coins": 1.43,
"buy_price": 290
},
{
"symbol": "BCH",
"number_of_coins": 0.78,
"buy_price": 530
}
]
coin_row = 1
pl_list = []
api_response_json = api_response
for coin in coin_buyinfo:
for i in range(3):
symbol = api_response_json[i]['symbol']
if symbol == coin['symbol']:
name = api_response_json[i]['name']
price = api_response_json[i]['price_usd']
pl = (float(price) - coin['buy_price'])*coin['number_of_coins']
pl_list.append(pl)
numholding = coin['number_of_coins']
ss = Label(pycryptp, text = symbol)
ss.grid(row = coin_row, column = 0)
dd = Label(pycryptp, text = str(price))
dd.grid(row = coin_row, column = 1)
vv = Label(pycryptp, text = str(numholding))
vv.grid(row = coin_row, column = 2)
proftloss = Label(pycryptp, text = str(pl))
proftloss.grid(row = coin_row, column = 3)
coin_row = coin_row +1
## Call Function to initiate grid
my_coinportfolio()
pycryptp.mainloop()
Not all functions must return something. In the end, a function is merely a container for a code to be repeated in a clean way. That is, instead of copying it everywhere.
Of course, a lot of functions return values to be used by calling them. But some functions' purpose is simply to print, or activate stuff, as in your example. Here, the function creates different labels according to some parameters and is simply used to pack the code in a readable fashion. There is no value needed to be returned!
With that said, functions actually do always return. When a function does not explicitly return (by using return), it will automatically return None.
A few simple examples to catch the idea:
def my_func():
print("Hello")
And now we can do:
>>> x = my_func()
Hello
>>> print(x)
None
As you can see, by calling the function our print statement was executed, and the returned value inside x is None.
With this code
import sense
import json
sense.api_key = '...'
node = sense.Node.retrieve('........')
feed = node.feeds.retrieve('presence')
events = feed.events.list(limit=1)
result = json.dumps(events,indent=1)
print result
I get a JSON-Feed like this:
{
"links": {...},
"objects": [
{
"profile": "GenStandard",
"feedUid": ".....",
"gatewayNodeUid": ".....",
"dateServer": "2015-02-28T09:57:22.337034",
"geometry": null,
"data": {
"body": "Present",
"code": 200
},
"signal": "-62",
"dateEvent": "2015-02-28T09:57:22.000000",
"type": "presence",
"payload": "2",
"nodeUid": "....."
}
],
"totalObjects": 875,
"object": "list"
}
How can I check if 'body' is 'present' (or 'code' is '200')? My script should return TRUE or FALSE
UPDATE
If I add this code as proposed in the answers it works fine:
d=json.loads(result)
def checkJson(jsonContents):
bodyFlag = True if "body" in jsonContents["objects"][0]["data"] and jsonContents["objects"][0]["data"]["body"] == "Present" else False
return bodyFlag
print checkJson(d)
You should also maybe check if the body key is actually there.
def checkJson(jsonContents):
bodyFlag = True if "body" in jsonContents["objects"][0]["data"] and jsonContents["objects"][0]["data"]["body"] == "Present" else False
codeFlag = True if "code" in jsonContents["objects"][0]["data"] and jsonContents["objects"][0]["data"]["code"] == 200 else False
return bodyFlag or codeFlag
print checkJson(result)
d = json.loads(results)
objs = d["objects"][0]
# see if any code is either == 200 or "body" is a key in the subdict
return any(x for x in (objs["data"]["code"] == 200,"body" in objs["data"]))