I want to get the stock price of any item. I have a function getPrice which returns the price of the item. I am trying to use wit ai.
This is what I have tried.
from wit import Wit
def getPrice(request):
#statements
return price
def send(request, response):
print request['text']
print('Sending to user...', response['text'])
actions = {
'send': send,
'getPrice':getPrice
}
client = Wit(access_token="<token>", actions=actions)
resp = client.message('what is the stock price of xyz')
print('Result: ' + str(resp))
and the result I am getting is:
Result: {
u 'entities': {
u 'search_query': [{
u 'suggested': True,
u 'confidence': 0.578445451443443,
u 'type': u 'value',
u 'value': u 'stock of xyz'
}],
u 'item': [{
u 'confidence': 0.9613219630126943,
u 'value': u 'xyz'
}]
},
u 'msg_id': u '5ac1a450-7c5d-3190-8666-5d88a1884f94',
u '_text': u 'what is the stock of xyz?'
}
I want the Bot to display the price. How can I call this action function?
You can do
print resp['entities']['item'][0]['value']
Instead of:
print('Result: ' + str(resp))
try:
stock = resp['entities']['item'][0]['value']
print('Price: {}'.format(getPrice(stock)))
Related
I'm a python beginner. I would like to ask for help regarding the retrieve the response data. Here's my script:
import pandas as pd
import re
import time
import requests as re
import json
response = re.get(url, headers=headers, auth=auth)
data = response.json()
Here's a part of json response:
{'result': [{'display': '',
'closure_code': '',
'service_offer': 'Integration Platforms',
'updated_on': '2022-04-23 09:05:53',
'urgency': '2',
'business_service': 'Operations',
'updated_by': 'serviceaccount45',
'description': 'ALERT returned 400 but expected 200',
'sys_created_on': '2022-04-23 09:05:53',
'sys_created_by': 'serviceaccount45',
'subcategory': 'Integration',
'contact_type': 'Email',
'problem_type': 'Design: Availability',
'caller_id': '',
'action': 'create',
'company': 'aaaa',
'priority': '3',
'status': '1',
'opened': 'smith.j',
'assigned_to': 'doe.j',
'number': '123456',
'group': 'blabla',
'impact': '2',
'category': 'Business Application & Databases',
'caused_by_change': '',
'location': 'All Locations',
'configuration_item': 'Monitor',
},
I would like to extract the data only for one group = 'blablabla'. Then I would like to extract fields such as:
number = data['number']
group = data['group']
service_offer = data['service_offer']
updated = data['updated_on']
urgency = data['urgency']
username = data['created_by']
short_desc = data['description']
How it should be done?
I know that to check the first value I should use:
service_offer = data['result'][0]['service_offer']
I've tried to create a dictionary, but, I'm getting an error:
data_result = response.json()['result']
payload ={
number = data_result['number']
group = data_result['group']
service_offer = data_result['service_offer']
updated = data_result['updated_on']
urgency = data_result['urgency']
username = data_result['created_by']
short_desc = data_result['description']
}
TypeError: list indices must be integers or slices, not str:
So, I've started to create something like below., but I'm stuck:
get_data = []
if len(data) > 0:
for item in range(len(data)):
get_data.append(data[item])
May I ask for help?
If data is your decoded json response from the question then you can do:
# find group `blabla` in result:
g = next(d for d in data["result"] if d["group"] == "blabla")
# get data from the `blabla` group:
number = g["number"]
group = g["group"]
service_offer = g["service_offer"]
updated = g["updated_on"]
urgency = g["urgency"]
username = g["sys_created_by"]
short_desc = g["description"]
print(number, group, service_offer, updated, urgency, username, short_desc)
Prints:
123456 blabla Integration Platforms 2022-04-23 09:05:53 2 serviceaccount45 ALERT returned 400 but expected 200
i'm trying to scrape some data from a site called laced.co.uk, and i'm a tad confused on whats going wrong. i'm new to this, so try and explain it simply (if possible please!). Here is my code ;
from bs4 import BeautifulSoup
import requests
url = "https://www.laced.co.uk/products/nike-dunk-low-retro-black-white?size=7"
result = requests.get(url)
doc = BeautifulSoup(result.text, "html.parser")
prices = doc.find_all(text=" £195 ")
print(prices)
thank you! (the price at time of posting was 195 (it showed as the size 7 buy now price on the page).
The price is loaded within a <script> tag on the page:
<script>
typeof(dataLayer) != "undefined" && dataLayer.push({
'event': 'eec.productDetailImpression',
'page': {
'ecomm_prodid': 'DD1391-100'
},
'ecommerce': {
'detail': {
'actionField': {'list': 'Product Page'},
'products': [{
'name': 'Nike Dunk Low Retro Black White',
'id': 'DD1391-100',
'price': '195.0',
'brand': 'Nike',
'category': 'Dunk, Dunk Low, Mens Nike Dunks',
'variant': 'White',
'list': 'Product Page',
'dimension1': '195.0',
'dimension2': '7',
'dimension3': '190',
'dimension4': '332'
}]
}
}
});
</script>
You can use a regular expression pattern to search for the price. Note, there's no need for BeautifulSoup:
import re
import requests
url = "https://www.laced.co.uk/products/nike-dunk-low-retro-black-white?size=7"
result = requests.get(url)
price = re.search(r"'price': '(.*?)',", result.text).group(1)
print(f"£ {price}")
I am trying to come up with a script that loops and returns all results from an API. The max transactions per call is 500, and there is a tag 'MoreFlag' that is 0 when there are less than or equal to 500 transactions and 1 when there are more than 500 transactions (per page). How can I write the code so that when 'MoreFlag' is 1 go to the next page until the tag changes to 0?
The API requires a license key and password, but here's a piece of the output.
r = 0
station_name = 'ORANGE'
usageSearchQuery = {
'stationName': station_name,
'startRecord': 1 + r,
'numTransactions': 500
}
trans_data = client.service.getTransactionData(usageSearchQuery)
for c in enumerate(trans_data):
print(c)
This returns the following:
(0, 'responseCode')
(1, 'responseText')
(2, 'transactions')
(3, 'MoreFlag')
Next, if I use this code:
for c in enumerate(trans_data.transactions):
print(trans_data)
# add 500 to startRecord
The API returns:
{
'responseCode': '100',
'responseText': 'API input request executed successfully.',
'transactions': {
'transactionData': [
{
'stationID': '1’,
'stationName': 'ORANGE',
'transactionID': 178543,
'Revenue': 1.38,
'companyID': ‘ABC’,
'recordNumber': 1
},
{
'stationID': '1’,
'stationName': 'ORANGE',
'transactionID': 195325,
'Revenue': 1.63,
'companyID': ‘ABC’,
'recordNumber': 2
},
{
'stationID': '1’,
'stationName': 'ORANGE',
'transactionID': 287006,
'Revenue': 8.05,
'companyID': ‘ABC’,
'recordNumber': 500
}
]
},
'MoreFlag': 1
}
The idea is to pull data from trans_data.transactions.transactionData, but I'm getting tripped up when I need more than 500 results, i.e. subsequent pages.
I figured it out. I guess my only question: is there a cleaner way to do this? It seems kind of repetitive.
i = 1
y = []
lr = 0
station_name = 'ORANGE'
usageSearchQuery = {
'stationName': station_name,
}
trans_data = client.service.getTransactionData(usageSearchQuery)
for c in enumerate(trans_data):
while trans_data.MoreFlag == 1:
usageSearchQuery = {
'stationName': station_name,
'startRecord': 1 + lr,
'numTransactions': 500
}
trans_data = client.service.getTransactionData(usageSearchQuery)
for (d) in trans_data.transactions.transactionData:
td = [i, str(d.stationName), d.transactionID,
d.transactionTime.strftime('%Y-%m-%d %H:%M:%S'),
d.Revenue]
i = i + 1
y.append(td)
lr = lr + len(trans_data.transactions.transactionData)
So i have code that gets data from one api but i can only use frist 3 keys like message idk why is that code:
import requests
import json
result=requests.get('https://api.etherscan.io/api?module=account&action=tokentx&contractaddress=0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2&page=1&offset=1&sort=asc&apikey=mytoken')
result.status_code
result.text
result.json()
print (result.json()['message]) # work
print (result.json()['gas]) # or any other key dont work
Output from api:
{"status":"1","message":"OK","result":[{"blockNumber":"4620855","timeStamp":"1511634257","hash":"0x5c9b0f9c6c32d2690771169ec62dd648fef7bce3d45fe8a6505d99fdcbade27a","nonce":"5417","blockHash":"0xee385ac028bb7d8863d70afa02d63181894e0b2d51b99c0c525ef24538c44c24","from":"0x731c6f8c754fa404cfcc2ed8035ef79262f65702","contractAddress":"0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2","to":"0x642ae78fafbb8032da552d619ad43f1d81e4dd7c","value":"1000000000000000000000000","tokenName":"Maker","tokenSymbol":"MKR","tokenDecimal":"18","transactionIndex":"55","gas":"3000000","gasPrice":"1000000000","gasUsed":"1594668","cumulativeGasUsed":"4047394","input":"deprecated","confirmations":"7045304"}]}
i can only get status message ect.
when i try gas this is error
Traceback (most recent call last):
File "main.py", line 11, in
print (result.json()[gas])
NameError: name 'gas' is not defined
You should add a few print statements to understand your response and debug
your_reponse = {
'message': 'OK',
'result': [{'blockHash': '0xee385ac028bb7d8863d70afa02d63181894e0b2d51b99c0c525ef24538c44c24',
'blockNumber': '4620855',
'confirmations': '7045304',
'contractAddress': '0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2',
'cumulativeGasUsed': '4047394',
'from': '0x731c6f8c754fa404cfcc2ed8035ef79262f65702',
'gas': '3000000',
'gasPrice': '1000000000',
'gasUsed': '1594668',
'hash': '0x5c9b0f9c6c32d2690771169ec62dd648fef7bce3d45fe8a6505d99fdcbade27a',
'input': 'deprecated',
'nonce': '5417',
'timeStamp': '1511634257',
'to': '0x642ae78fafbb8032da552d619ad43f1d81e4dd7c',
'tokenDecimal': '18',
'tokenName': 'Maker',
'tokenSymbol': 'MKR',
'transactionIndex': '55',
'value': '1000000000000000000000000'}],
'status': '1'}
>>> your_reponse['result']
[{'blockHash': '0xee385ac028bb7d8863d70afa02d63181894e0b2d51b99c0c525ef24538c44c24',
'blockNumber': '4620855',
'confirmations': '7045304',
'contractAddress': '0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2',
'cumulativeGasUsed': '4047394',
'from': '0x731c6f8c754fa404cfcc2ed8035ef79262f65702',
'gas': '3000000',
'gasPrice': '1000000000',
'gasUsed': '1594668',
'hash': '0x5c9b0f9c6c32d2690771169ec62dd648fef7bce3d45fe8a6505d99fdcbade27a',
'input': 'deprecated',
'nonce': '5417',
'timeStamp': '1511634257',
'to': '0x642ae78fafbb8032da552d619ad43f1d81e4dd7c',
'tokenDecimal': '18',
'tokenName': 'Maker',
'tokenSymbol': 'MKR',
'transactionIndex': '55',
'value': '1000000000000000000000000'}]
>>> print(your_reponse['result'][0]['gas'])
3000000
Use this recursive function to work around changes in API response:
def price_of_gas(inp):
def recursive_function(inp):
if type(inp) is list:
for i in inp:
ans = recursive_function(i)
if ans!=None: return ans
elif type(inp) is dict:
if 'gas' in inp: return inp['gas']
for i in inp:
ans = recursive_function(inp[i])
if ans!=None: return ans
else: return None
ans = recursive_function(inp)
return ans if ans else "Could NOT find the gas"
price_of_gas(your_reponse)
See the JSON response carefully. Its a dictionary with three keys (status, message and result). The key result is a list having another dictionary inside.
JSON response:
{
"status":"1",
"message":"OK",
"result":[
{
"blockNumber":"4620855",
"timeStamp":"1511634257",
"hash":"0x5c9b0f9c6c32d2690771169ec62dd648fef7bce3d45fe8a6505d99fdcbade27a",
"nonce":"5417",
"blockHash":"0xee385ac028bb7d8863d70afa02d63181894e0b2d51b99c0c525ef24538c44c24",
"from":"0x731c6f8c754fa404cfcc2ed8035ef79262f65702",
"contractAddress":"0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2",
"to":"0x642ae78fafbb8032da552d619ad43f1d81e4dd7c",
"value":"1000000000000000000000000",
"tokenName":"Maker",
"tokenSymbol":"MKR",
"tokenDecimal":"18",
"transactionIndex":"55",
"gas":"3000000",
"gasPrice":"1000000000",
"gasUsed":"1594668",
"cumulativeGasUsed":"4047394",
"input":"deprecated",
"confirmations":"7045304"
}
]
}
So if you need to access the keys present inside the result dictionary, you have to nest your code accordingly.
result.json['result'][0]['gas']
I have this code for changing stoploss on opened order/orders in metatrader 5. When I run this code nothing happens even when my compiler print that, nothing is wrong. I have algotrading on so I'm not sure where is the problem.
Here is source code:
def sl_change(ticket, SL, TP, pair, p_open, volume, o_type):
order_request = {
'action': mt5.TRADE_ACTION_SLTP,
'ticket': ticket,
'type': o_type,
'price_open': p_open,
'volume': volume,
'sl': SL,
'tp': TP,
'symbol': pair,
'deviation': 20,
"magic": ea_magic_number,
"comment": "sent by python",
"type_time": mt5.ORDER_TIME_GTC, # good till cancelled
'type_filling': mt5.ORDER_FILLING_FOK,
"type_filling": mt5.ORDER_FILLING_RETURN,
}
result = mt5.order_check(order_request)
return result, order_request
pair = 'AUDUSD'
SL = 0.7101
positions = mt5.positions_get(symbol=pair)
ordernum = len(positions)
for i in range(0, ordernum):
position = positions[i]
ticket = position.ticket
TP = position.tp
volume = position.volume
o_type = position.type
p_open = position.price_open
print(positions)
time.sleep(5)
sl_change(ticket, SL, TP, pair, p_open, volume, o_type)
When I replace order_check with order_send still nothing happens.
This is what works for me now it's sample code if you don't understand input answer me I can give you more info
def changeslpl(ticket,pair,pos_type,SL,tp,ea_magic_number,volume,p_open):
request = {
"action": mt5.TRADE_ACTION_SLTP,
"symbol": pair,
"volume": volume,
"type": pos_type,
"position": ticket,
"price_open": p_open,
"sl": SL,
"tp": tp,
"deviation": 20,
"magic": ea_magic_number,
"comment": "python script open",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": mt5.ORDER_FILLING_FOK,
"ENUM_ORDER_STATE": mt5.ORDER_FILLING_RETURN,
}
#// perform the check and display the result 'as is'
result = mt5.order_send(request)
if result.retcode != mt5.TRADE_RETCODE_DONE:
print("4. order_send failed, retcode={}".format(result.retcode))
print(" result",result)
I found out why we were facing this problem.
When you execute a trade for the first time note that STOP_LOSS is always equal to for example 500 points difference from price but now you want to modify a stop loss.
So 500 points +/- current_price = e.g. 138.500 == OUR STOP_LOSS
The hack here is that you put price for a STOP_LOSS, NOT POINTS.
So the new request will be:
request = { 'action': mt5.TRADE_ACTION_SLTP, 'position': position.ticket, 'sl': 139.000, }
Now you will be finally on to something.
You should invert your order type. If it is a mt5.ORDER_TYPE_BUY, the SL/TP modification request should be a mt5.ORDER_TYPE_SELL
# This is what is important to you!
if(order_type == mt5.ORDER_TYPE_BUY):
order_type = mt5.ORDER_TYPE_SELL
price = mt5.symbol_info_tick(symbol).bid
else:
order_type = mt5.ORDER_TYPE_BUY
price = mt5.symbol_info_tick(symbol).ask
#importance ends here.
sltp_request = {
"action": mt5.TRADE_ACTION_SLTP,
"symbol": symbol,
"volume": float(volume),
"type": order_type,
"position": deal_id,
"sl": sl,
"price": price,
"magic": 234000,
"comment": "Change stop loss",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": mt5.ORDER_FILLING_IOC,
}
result = mt5.order_send(sltp_request)