I found an old thread ( how can I close position on OKX V5 based on CCXT Python? ) but is not working.
I'm having problem in closing my current margin-spot position. Here's my code:
params = {'tdMode': 'cross', 'ccy': 'USDT'}
order = await self.okx.create_order(
symbol='XRP/USDT', type='market', side='sell',
amount=99.43, price=0.39024, params=params
)
Result:
{'amount': 99.431119,
'average': 0.39005,
'clientOrderId': 'e847386590ce4dBCce71dedc37e12254',
'cost': 38.78310796595,
'datetime': '2022-12-02T17:29:58.048Z',
'fee': {'cost': 0.03878310796595, 'currency': 'USDT'},
'fees': [{'cost': 0.03878310796595, 'currency': 'USDT'}],
'filled': 99.431119,
'id': '518962064594153472',
Places the first order correctly. Now to close this order I use barrely the same code, changing sides:
params = {'tdMode': 'cross', 'ccy': 'USDT'}
order = await self.okx.create_order(
symbol='XRP/USDT', type='market', side='buy',
amount=99.43, price=0.39017, params=params
)
Problem is that the amount in the second order seeems to be 'contracts'/'price' instead:
result:
{'amount': 99.43111,
'average': 0.39015,
'clientOrderId': 'e847386590ce4dBC328bc6dfc937795f',
'cost': 99.43110980145,
'datetime': '2022-12-02T17:36:47.913Z',
'fee': {'cost': 0.254853543, 'currency': 'XRP'},
'fees': [{'cost': 0.254853543, 'currency': 'XRP'}],
'filled': 254.853543,
'id': '518963783692562432',
What am I doing wrong ?
Are you changing the default tgtCcy value?
Can you try to place the market order without the price (market orders execute at the market price so you don't need to specify it)?
Related
I am using this python library to grab a response from the google places API.
Using the places function from the above library returns the object you see below. You can see that is just gives me a boolean on whether the restaurant is open or closed. How can I see the hours it is open for each day of the week? If this library isnt capable of it, can anyone show me an example that is?
Here is the line of code making the request for full context.
import googlemaps # https://googlemaps.github.io/google-maps-services-python/docs/index.html
gmaps = googlemaps.Client(key='apiKey')
response = gmaps.places(query=charlestonBars[idx], location=charleston)
[ { 'business_status': 'OPERATIONAL',
'formatted_address': '467 King St, Charleston, SC 29403, United States',
'geometry': { 'location': {'lat': 32.7890988, 'lng': -79.9386229},
'viewport': { 'northeast': { 'lat': 32.79045632989271,
'lng': -79.93725907010727},
'southwest': { 'lat': 32.78775667010727,
'lng': -79.93995872989272}}},
'icon': 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/bar-71.png',
'icon_background_color': '#FF9E67',
'icon_mask_base_uri': 'https://maps.gstatic.com/mapfiles/place_api/icons/v2/bar_pinlet',
'name': "A.C.'s Bar & Grill",
------->'opening_hours': {'open_now': True},
'photos': [ { 'height': 1816,
'html_attributions': [ '<a '
'href="https://maps.google.com/maps/contrib/106222166168758671498">Lisa '
'Royce</a>'],
'photo_reference': 'ARywPAKpP_eyNL_y625xWYrQvSjAI91TzEx4XgT1rwCxjFyQjEAwZb2ha9EgE2RcKJalrZhjp0yTWa6QqvPNU9c7GeNBTDtzXVI0rHq2RXtTySGu8sjcB76keFugOmsl1ix4NnDVh0NO0vt_PO3nIZ-R-ytOzzIRhJgPAJd3SxKNQNfEyVp5',
'width': 4032}],
'place_id': 'ChIJk6nSrWt6_ogRE9KiNXVG5KA',
'plus_code': { 'compound_code': 'Q3Q6+JG Charleston, South Carolina',
'global_code': '8742Q3Q6+JG'},
'price_level': 1,
'rating': 4.3,
'reference': 'ChIJk6nSrWt6_ogRE9KiNXVG5KA',
'types': [ 'bar',
'restaurant',
'point_of_interest',
'food',
'establishment'
What you need to use is the Place Details of Places API
Before we proceed with the solution, we must understand that there's a difference in the result of a Place Search and a Place Details request.
According to the documentation:
"Place Search requests and Place Details requests do not return the same fields. Place Search requests return a subset of the fields that are returned by Place Details requests. If the field you want is not returned by Place Search, you can use Place Search to get a place_id, then use that Place ID to make a Place Details request."
Now what you used on your code according to the python library documentation is the places(*args, **kwargs) which is the Place Search.
The Google Maps API documentation you provided on your comment above where you can get the expected result of hours each day is from Place Details which is the place(*args, **kwargs) from the python library documentation.
As quoted above, to request the detail of a place, you need the place_id which you can get by doing a Places Search request like you did on your question. So what you only need to do is get the place_id of the location you want through Place Search, then use that place_id to get the Place Details result that includes the opening_hours field result.
Here's what it looks like on a python code:
# I used pprint to print the result on the console
from pprint import pprint
import googlemaps #import googlemaps python library
# Instantiate the client using your own API key
API_KEY = 'API_KEY'
map_client = googlemaps.Client(API_KEY)
# Store the location you want, in my case, I tried using 'Mall of Asia'
location_name = 'Mall of Asia'
# Instantiate Place Search request using `places(*args, **kwargs)` from the library
# Use the `stored location` as an argument for query
place_search = map_client.places(location_name)
# Get the search results
search_results = place_search.get('results')
# Store the place_id from the result to be used
place_id = (search_results[0]['place_id'])
# Instantiate Place Details request using the `place(*args, **kwargs)` from the library
# Use the stored place_id as an argument for the request
place_details = map_client.place(place_id)
# Get the Place Details result
details_results = place_details.get('result')
# Print the result specifying what you only need which is the `opening_hours` field
pprint(details_results['opening_hours'])
The result of this sample request would be this:
{'open_now': False,
'periods': [{'close': {'day': 0, 'time': '2200'},
'open': {'day': 0, 'time': '1000'}},
{'close': {'day': 1, 'time': '2200'},
'open': {'day': 1, 'time': '1000'}},
{'close': {'day': 2, 'time': '2200'},
'open': {'day': 2, 'time': '1000'}},
{'close': {'day': 3, 'time': '2200'},
'open': {'day': 3, 'time': '1000'}},
{'close': {'day': 4, 'time': '2200'},
'open': {'day': 4, 'time': '1000'}},
{'close': {'day': 5, 'time': '2200'},
'open': {'day': 5, 'time': '1000'}},
{'close': {'day': 6, 'time': '2200'},
'open': {'day': 6, 'time': '1000'}}],
'weekday_text': ['Monday: 10:00\u202fAM\u2009–\u200910:00\u202fPM',
'Tuesday: 10:00\u202fAM\u2009–\u200910:00\u202fPM',
'Wednesday: 10:00\u202fAM\u2009–\u200910:00\u202fPM',
'Thursday: 10:00\u202fAM\u2009–\u200910:00\u202fPM',
'Friday: 10:00\u202fAM\u2009–\u200910:00\u202fPM',
'Saturday: 10:00\u202fAM\u2009–\u200910:00\u202fPM',
'Sunday: 10:00\u202fAM\u2009–\u200910:00\u202fPM']}
That would be all and I hope this helps! Feel free to comment below if this does not meet your expected results.
I'm making a call to an api which is returning a JSON response, whcih i am then trying to retrieve certain data from within the response.
{'data': {'9674': {'category': 'token',
'contract_address': [{'contract_address': '0x2a3bff78b79a009976eea096a51a948a3dc00e34',
'platform': {'coin': {'id': '1027',
'name': 'Ethereum',
'slug': 'ethereum',
'symbol': 'ETH'},
'name': 'Ethereum'}}],
'date_added': '2021-05-10T00:00:00.000Z',
'date_launched': '2021-05-10T00:00:00.000Z',
'description': 'Wilder World (WILD) is a cryptocurrency '
'launched in 2021and operates on the '
'Ethereum platform. Wilder World has a '
'current supply of 500,000,000 with '
'83,683,300.17 in circulation. The last '
'known price of Wilder World is 2.28165159 '
'USD and is down -6.79 over the last 24 '
'hours. It is currently trading on 21 active '
'market(s) with $2,851,332.76 traded over '
'the last 24 hours. More information can be '
'found at https://www.wilderworld.com/.',
'id': 9674,
'is_hidden': 0,
'logo': 'https://s2.coinmarketcap.com/static/img/coins/64x64/9674.png',
'name': 'Wilder World',
'notice': '',
'platform': {'id': 1027,
'name': 'Ethereum',
'slug': 'ethereum',
'symbol': 'ETH',
'token_address': '0x2a3bff78b79a009976eea096a51a948a3dc00e34'},
'self_reported_circulating_supply': 19000000,
'self_reported_tags': None,
'slug': 'wilder-world',
'subreddit': '',
'symbol': 'WILD',
'tag-groups': ['INDUSTRY',
'CATEGORY',
'INDUSTRY',
'CATEGORY',
'CATEGORY',
'CATEGORY',
'CATEGORY'],
'tag-names': ['VR/AR',
'Collectibles & NFTs',
'Gaming',
'Metaverse',
'Polkastarter',
'Animoca Brands Portfolio',
'SkyVision Capital Portfolio'],
'tags': ['vr-ar',
'collectibles-nfts',
'gaming',
'metaverse',
'polkastarter',
'animoca-brands-portfolio',
'skyvision-capital-portfolio'],
'twitter_username': 'WilderWorld',
'urls': {'announcement': [],
'chat': [],
'explorer': ['https://etherscan.io/token/0x2a3bff78b79a009976eea096a51a948a3dc00e34'],
'facebook': [],
'message_board': ['https://medium.com/#WilderWorld'],
'reddit': [],
'source_code': [],
'technical_doc': [],
'twitter': ['https://twitter.com/WilderWorld'],
'website': ['https://www.wilderworld.com/']}}},
'status': {'credit_count': 1,
'elapsed': 7,
'error_code': 0,
'error_message': None,
'notice': None,
'timestamp': '2022-01-20T21:33:04.832Z'}}
The data i am trying to get is 'logo': 'https://s2.coinmarketcap.com/static/img/coins/64x64/9674.png', but this sits within [data][9674][logo]
But as this script to running in the background for other objects, i won't know what the number [9674] is for other requests.
So is there a way to get that number automatically?
[data] will always be consistent.
Im using this to get the data back
session = Session()
session.headers.update(headers)
response = session.get(url, params=parameters)
pprint.pprint(json.loads(response.text)['data']['9674']['logo'])
You can try this:
session = Session()
session.headers.update(headers)
response = session.get(url, params=parameters)
resp = json.loads(response.text)
pprint.pprint(resp['data'][next(iter(resp['data']))]['logo'])
where next(iter(resp['data'])) - returns first key in resp['data'] dict. In your example it '9674'
With .keys() you get a List of all Keys in a Dictionary.
So you can use keys = json.loads(response.text)['data'].keys() to get the keys in the data-dict.
If you know there is always only one entry in 'data' you could use json.loads(response.text)['data'][keys[0]]['logo']. Otherwise you would need to iterate over all keys in the list and check which one you need.
I would like to extract some data from the following line of text. The data of interest are:'exchange_symbol under both market_pair_base and 'market_pair_quote, all the data under exchange_reported.
Any help would be great.
{'status': {'timestamp': '2019-10-04T02:57:39.238Z', 'error_code': 0, 'error_message': None, 'elapsed': 14, 'credit_count': 1, 'notice': None}, 'data': {'id': 112, 'name': 'Liquid', 'slug': 'liquid', 'num_market_pairs': 190, 'market_pairs': [{'market_pair_base': {'exchange_symbol': 'ETH', 'currency_id': 1027, 'currency_symbol': 'ETH', 'currency_type': 'cryptocurrency'}, 'market_pair_quote': {'exchange_symbol': 'JPY', 'currency_id': 2797, 'currency_symbol': 'JPY', 'currency_type': 'fiat'}, 'quote': {'exchange_reported': {'price': 18522.8757, 'volume_24h_base': 12901.4143123, 'volume_24h_quote': 238971293.660934, 'last_updated': '2019-10-04T02:57:04.000Z'}, 'USD': {'price': 173.503768779353, 'volume_24h': 2238444.00576794, 'last_updated': '2019-10-04T02:57:04.000Z'}}, 'market_id': 4431, 'market_pair': 'ETH/JPY', 'category': 'spot', 'fee_type': 'percentage'}, {'market_pair_base': {'exchange_symbol': 'XRP', 'currency_id': 52, 'currency_symbol': 'XRP', 'currency_type': 'cryptocurrency'}, 'market_pair_quote': {'exchange_symbol': 'JPY', 'currency_id': 2797, 'currency_symbol': 'JPY', 'currency_type': 'fiat'}, 'quote': {'exchange_reported': {'price': 26.55199, 'volume_24h_base': 8223150.63965144, 'volume_24h_quote': 218341013.552519, 'last_updated': '2019-10-04T02:56:04.000Z'}, 'USD': {'price': 0.248712479001935, 'volume_24h': 2045200.18079406, 'last_updated': '2019-10-04T02:56:04.000Z'}}, 'market_id': 16254, 'market_pair': 'XRP/JPY', 'category': 'spot', 'fee_type': 'percentage'}]}}
I tried the following code but this send an error :
File "proc_manual_comp.py", line 112, in <module>
for item in data['data'][currency]['market_pairs']
TypeError: 'int' object is not subscriptable
the code:
c_price = []
url = 'https://pro-api.coinmarketcap.com/v1/exchange/market-pairs/latest'
parameters = {
'id':'112',
'start':'1',
'limit':'91'
}
headers = {
'Accepts': 'application/json',
'X-CMC_PRO_API_KEY': 'XXXXXXXXXXXXXXXXXXXXXXX',
}
session = Session()
session.headers.update(headers)
response = session.get(url, params=parameters)
data = json.loads(response.text)
for currency in data['data']:
used_list = [
item['market_pairs']['market_pair_base']
for item in data['data'][currency]['market_pairs']
]
price = pd.DataFrame.from_records(used_list)
print(price)
price['timestamp'] = pd.to_datetime(price['timestamp'])
price['timestamp'] = price['timestamp'].astype(str).str[:-6]
price_c = price.set_index('timestamp').close
c_price.append(price_c.rename(currency))
print(c_price)
c_price = pd.concat(c_price, axis=1)
Expected output:
market_pair_base market_pair_quoted last_updated price
ETH JPY 2019-10-04T02:57:04.000Z 18522.8757
Assumed JSON as given in d variable
Try below snippet:
target_df=pd.DataFrame(columns=['market_pair_base','market_pair_quote','price','last_updated'])
target=dict()
usedlist=d['data']['market_pairs']
for i in range(len(usedlist)):
target['market_pair_base']=[usedlist[i]['market_pair_base']['exchange_symbol']]
target['market_pair_quote'] = [usedlist[i]['market_pair_quote']['exchange_symbol']]
target['price'] = [usedlist[i]['quote']['exchange_reported']['price']]
target['last_updated'] = [usedlist[i]['quote']['exchange_reported']['last_updated']]
target_df=pd.concat([target_df, pd.DataFrame(target)], ignore_index=True)
This print(target_df) will give desired output as below:
market_pair_base market_pair_quote price last_updated
0 ETH JPY 18522.87570 2019-10-04T02:57:04.000Z
1 XRP JPY 26.55199 2019-10-04T02:56:04.000Z
it seems like a problem with your for loop.
for currency in data['data']:
here since data['data'] is a dict hence values of currency is going to be keys of dict, an alternate way can be something like this
for market_pairs in data['data']['market_pairs']:
used_list = [market_pair['market_pair_base'] for market_pair in market_pairs]
price = pd.DataFrame.from_records(used_list)
this is based on the fact that you wanted to put all market_pair_base in a Dataframe.
I'm using a basic script to retrieve some trading data from an exchange, here is the response:
{'info': {'symbol': 'ETHBTC',
'orderListId': -1,
'price': '0.01083700',
'origQty': '0.01800000',
'executedQty': '0.00000000',
'cummulativeQuoteQty': '0.00000000',
'status': 'NEW',
'timeInForce': 'GTC',
'type': 'LIMIT',
'side': 'BUY',
'stopPrice': '0.00000000',
'icebergQty': '0.00000000',
'time': 1567078061338,
'updateTime': 1567078061338,
'isWorking': True}}
Now i want to print some parts of this response individually.
If i try:
tot = exchange.fetch_open_orders()
for x in tot:
print(x['symbol'])
I'll get: 'ETHBTC'. Until now, everything is normal.
But if i try:
tot = exchange.fetch_open_orders()
for x in tot:
print(x['origQty'])
I get a KeyError: 'origQty', which is weird, because this error should appear when i try to reference a parameter which doesn't exist, but it exists, since it is in my response. What am i doing wrong?
Here you iterating dictionary on keys, so each time you are trying to get value from key, that's why it is giving KeyError.
This occurs when a key which is not present in a dictionary and still it accessed.
This can be achieved by following way.
for x in tot:
print(tot[x].get('symbol'))
print(tot[x].get('origQty'))
Give output
ETHBTC
0.01800000
I am not sure what is the format of tot. But you can try this.
for x, v in dict(tot).items():
print(v['symbol'])
print(v['origQty'])
Output:
ETHBTC
0.01800000
I am writing program code to record the stock in the nested list to a dictionary using the code as key (e.g., '3AB') and the value is a list containing the stock information without the code (e.g., ["Telcom", "12/07/2018", 1.55, 3000]). My program code must also be able to access the elements in the nested list.
However, when I run my code, it keeps on hitting syntax error. Can I check what is wrong with my code?
stock = {
3AB: {'Name': 'Telcom', 'Purchase Date': '12/12/2018', 'Price': '1.55', 'Volume':'3000'},
S12: {'Name': 'S&P', 'Purchase Date': '12/08/2018', 'Price': '3.25', 'Volume': '2000'},
AE1: {'Name': 'A ENG', 'Purchase Date': '04/03/2018', 'Price': '1.45', 'Volume': '5000'}
}
print(stock[3AB]['Name'])
print(stock[S12]['Name'])
print(stock[AE1]['Name'])
You got the error:
SyntaxError: invalid syntax
because your dictionary was unhashable. i.e Invalid literal key 3AB, the correct syntax, being '3AB':
stock = {
'3AB': {'Name': 'Telcom', 'Purchase Date': '12/12/2018', 'Price': '1.55', 'Volume':'3000'},
'S12': {'Name': 'S&P', 'Purchase Date': '12/08/2018', 'Price': '3.25', 'Volume': '2000'},
'AE1': {'Name': 'A ENG', 'Purchase Date': '04/03/2018', 'Price': '1.45', 'Volume': '5000'}
}
print(stock['3AB']['Name'])
print(stock['S12']['Name'])
print(stock['AE1']['Name'])
OUTPUT:
Telcom
S&P
A ENG
Use this
stock = {
'3AB': {'Name': 'Telcom', 'Purchase Date': '12/12/2018', 'Price': '1.55', 'Volume':'3000'},
'S12': {'Name': 'S&P', 'Purchase Date': '12/08/2018', 'Price': '3.25', 'Volume': '2000'},
'AE1': {'Name': 'A ENG', 'Purchase Date': '04/03/2018', 'Price': '1.45', 'Volume': '5000'}
}
print(stock['3AB']['Name'])
print(stock['S12']['Name'])
print(stock['AE1']['Name'])
it throws error because in your code look at 3AB as a variable that it cannot found so you need pass it in '' as string
key must be hashable.your key 3AB must be a string.change into '3AB',the others are the same as 3AB.