Can the amount be in USDT on Binanace Api Future Trade? - binance

import ccxt
import pprint
with open("D:/api.txt") as f:
lines = f.readlines()
api_key = lines[0].strip()
secret = lines[1].strip()
binance = ccxt.binance({
'apiKey' : api_key,
'secret' : secret,
'enableRateLimit': True,
'options': {
'defaultType': 'future'
}
})
markets = binance.fetch_tickers()
print(markets.keys())
order = binance.create_limit_buy_order(
symbol = 'ENSUSDT',
amount = 1,
price = 19.5,
)
pprint.pprint(order)
In this way, I would like to order 10$, but it is inconvenient because the amount is based on the price of one coin. Is there a way to do something like amount=10$ instead of amount = 1 ?

The closest you could do would be to multiply the contractSize by the price and the amount you want to spend
usdt_amount = 10
market['contractSize'] * price * usdt_amount
with open("D:/api.txt") as f:
lines = f.readlines()
api_key = lines[0].strip()
secret = lines[1].strip()
binance = ccxt.binance({
'apiKey' : api_key,
'secret' : secret,
'enableRateLimit': True,
'options': {
'defaultType': 'future'
}
})
tickers = binance.fetch_tickers()
price = 19.5
symbol = 'ENS/USDT'
market = binance.market(symbol)
usdt_amount = 10
order = binance.create_limit_buy_order(
symbol = symbol,
amount = market['contractSize'] * price * usdt_amount,
price = price,
)

Related

Issues in Python with combining multiple JSON pages into single dictionary

I'm trying to convert some API we had in JS to Python:
async function find_contact(api_key, email) {
var path = base_path + '/contacts';
var contacts = [];
var rootpath = path;
var result = await call_get_api(path, api_key)
.then(async function(result){
let total_pages = result.meta.total_pages;
console.log('Total Pages:' + total_pages);
contacts=result.contacts;
for(let page=2; page<=total_pages;page++){
path = rootpath + '?page='+page;
contacts = await call_get_api(path, api_key)
.then(async function(result){
return contacts.concat(result.contacts);
});
}
console.log('Total contacts: ' + contacts.length);
//TODO:: refine matching criteria.
let matching_contacts = contacts.filter(contact=> {
return email == contact.email}
);
console.log(matching_contacts.length + ' Matching contacts to ' + contact );
return matching_contacts;
});
This would result in us getting about 7 pages of data with 306 contacts. However, in Python, can't seem to get the concatenation of the subsequent pages (2-7)
def api_get_contacts(api_url, api_key):
url = api_url + "/contacts"
rooturl = url
api_auth = "Bearer " + api_key
headers = {
"Authorization": api_auth
}
response = requests.request("GET",url, headers=headers)
results = response.json()
total_pages = results["meta"]["total_pages"]
total_results = results["meta"]["total_entries"]
print(f"We are looking for {total_pages} and {total_results} contacts")
if total_pages > 1:
for page in range(2,total_pages+1,1):
print(f"Working on page {page}")
url = rooturl + "?page=" + str(page)
response = requests.request("GET",url, headers=headers)
data = response.json()
#results = results + data
#results.update(data) #does not work since it replaces
#results = {**results, **data} #does not work, same as update
#results = dict([(k,[results[k],data[k]]) for k in results])
have tried various methods, but they don't seem to work. the closest one was the last with the for loop, but instead of the result looking like:
'contacts': [{'id': 2343678, 'name': 'Andrew...
it comes out like
{'contacts': [[[[[[[{'id': 2343678, 'name': 'Andrew...

bithumb Api error -{'status': '5100', 'message': 'Bad Request.(Auth Data)'}

I wanted to make a program where I can check the order details of my order at Bithumb Exchange.
So I looked at the docs(https://api.bithumb.com/info/orders) and made it, but the same error code kept coming out, so I don't know what to do.
import time
import math
import base64
import hmac, hashlib
import urllib.parse
import requests
class XCoinAPI:
api_url = "https://api.bithumb.com";
api_key = "";
api_secret = "";
def __init__(self, api_key, api_secret):
self.api_key = api_key;
self.api_secret = api_secret;
def body_callback(self, buf):
self.contents = buf;
def microtime(self, get_as_float = False):
if get_as_float:
return time.time()
else:
return '%f %d' % math.modf(time.time())
def usecTime(self) :
mt = self.microtime(False)
mt_array = mt.split(" ")[:2];
return mt_array[1] + mt_array[0][2:5];
def xcoinApiCall(self, endpoint, rgParams):
# 1. Api-Sign and Api-Nonce information generation.
# 2. Request related information from the Bithumb API server.
#
# - nonce: it is an arbitrary number that may only be used once.
# - api_sign: API signature information created in various combinations values.
endpoint_item_array = {
"endpoint" : endpoint
}
uri_array = dict(endpoint_item_array, **rgParams) # Concatenate the two arrays.
str_data = urllib.parse.urlencode(uri_array)
nonce = self.usecTime()
data = endpoint + chr(1) + str_data + chr(1) + nonce
utf8_data = data.encode('utf-8')
key = self.api_secret
utf8_key = key.encode('utf-8')
h = hmac.new(bytes(utf8_key), utf8_data, hashlib.sha512)
hex_output = h.hexdigest()
utf8_hex_output = hex_output.encode('utf-8')
api_sign = base64.b64encode(utf8_hex_output)
utf8_api_sign = api_sign.decode('utf-8')
headers = {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"Api-Key": self.api_key,
"Api-Nonce": nonce,
"Api-Sign": utf8_api_sign
}
url = self.api_url + endpoint
r = requests.post(url, headers=headers, data=uri_array)
return r.json()
a = XCoinAPI(api_key="MYKEY1c", api_secret="MYKEY2")
aa= a.xcoinApiCall("/info/orders",{"order_currency":"LN","payment_currency":"BTC"})
print(aa)
{'status': '5100', 'message': 'Bad Request.(Auth Data)'}
Process finished with exit code 0
The error code 5100, bad request keeps coming up(https://apidocs.bithumb.com/docs/api-%EC%A3%BC%EC%9A%94-%EC%97%90%EB%9F%AC-%EC%BD%94%EB%93%9C)
I really don't know which code to modify.
I think it's a parameter problem with XcoinApiCall, but I don't know.

Twitter data extraction by user using Twitter API

How can i get user tweets using tweepy , but with user name not screen name, i have a list for company employees and i want to get their tweets, is there any solution ?
``` config.read('config.ini')
api_key = config['twitter']['api_key']
api_key_secret = config['twitter']['api_key_secret']
access_token = config['twitter']['access_token']
access_token_secret = config['twitter']['access_token_secret']
# authentication
auth = tweepy.OAuthHandler(api_key, api_key_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
#users = df['Name'].tolist()
user_ids = []
limit=300
for user in users:
tweets = tweepy.Cursor(api.user_timeline, screen_name=user, count=200,
tweet_mode='extended').items(limit)
#tweets = api.user_timeline(screen_name=user, count=limit,
tweet_mode='extended')
# create DataFrame
columns = ['User', 'Tweet']
data = []
for tweet in tweets:
data.append([tweet.user.screen_name, tweet.full_text])
df1 = pd.DataFrame(data, columns=columns)
print(df1)```

Getting TypeError when trying to log messages in discord

Here's my code:
#bot.command()
#commands.has_permissions(administrator = True)
async def logsave(ctx, amount = None, logName = None):
#Checks if user input an amount, either a number or "all".
if amount == None:
desc = f'**Specify an amount**'
errorEmbed = discord.Embed(title = f'**Log**', description = desc, colour = discord.Color.from_rgb(36, 227, 170))
await ctx.send(embed = errorEmbed)
return
#Checks if user input a name for the log.
if logName == None:
desc = f'**Specify a name.**'
errorEmbed = discord.Embed(title = f'**Log**', description = desc, colour = discord.Color.from_rgb(36, 227, 170))
logMsg = await ctx.send(embed = errorEmbed)
return
#Checks if user input "all"
if amount.lower() == 'all':
isAll = True
else:
isAll = False
#Gets message history
channel = ctx.channel
if isAll:
desc = f'**Started Logging**'
startEmbed = discord.Embed(title = f'**Log**', description = desc, colour = discord.Color.from_rgb(36, 227, 170))
logMsg = await ctx.send(embed = startEmbed)
messages = await channel.history(limit = None, oldest_first = True).flatten()
else:
messages = await channel.history(limit = int(amount), oldest_first = True).flatten()
#Loads previous logs for editing
logsFile = open(f'{currentDirectory}\Saved\logs.json', 'r+')
logsJson = json.load(logsFile)
#Creates new message log in JSON
logCount = logsJson[messages][-1]["count"] + 1
newLog = {
"name": logName,
"creator": ctx.author,
"msgs": [],
"count": logCount
}
logsJson["messageLogs"].append(newLog)
#Stars logging the messages, I'm pretty sure this is where my error is coming from.
for msg in messages:
msgAuthor = msg.author
if msgAuthor.bot:
return
print("done")
msgContent = msg.content
msgAttachments = msg.attachments
msgCreated = msg.created_at
msgWrite = f'\n{msgAuthor} [{msgCreated}]\n{msgContent}'
newMessage = {
"id": msg.id,
"authorname": str(msgAuthor),
"authorid": msgAuthor.id,
"content": msgWrite,
"published": msgCreated,
"attachments": msgAttachments
}
logsJson["messageLogs"][logCount]["msgs"].append(newMessage)
#Edits previous log.
json.dump(logsJson, logsFile)
logsFile.close()
#Ends
logMsg.delete()
desc = f'**Finished Logging**'
endEmbed = discord.Embed(title = f'**Log**', description = desc, colour = discord.Color.from_rgb(36, 227, 170))
await ctx.send(embed = endEmbed)
This is the code for a command that stores messages in a JSON. The problem is that whenever I run this command in discord I get this error:
<discord.ext.commands.context.Context object at 0x000001BB444DC370> Command raised an exception: TypeError: unhashable type: 'list'
I can't seem to figure out what's gone wrong. I've put comments in the code of the command to explain what each part does. I haven't yet figured out if the rest of the code is right so if there's more than one error, feel free to address that as well, right now though I'm just looking for the solution for the particular error above.
TL;DR:
you probably meant to do logsJson["messageLogs"][-1]["count"] + 1
More detail:
When you try to lookup a dictionary with a list value, you get unhashable type: 'list' because dictionaries are just hash tables. You appear to do this here:
logCount = logsJson[messages][-1]["count"] + 1
and you declared messages above this as:
messages = await channel.history(limit = None, oldest_first = True).flatten()
which returns a list of all the messages. So Python can't hash this list and throws the above error. I am guessing you meant to put "messageLogs" in quotes "" as strings are valid keys for a dictionary (they are hashable).
Reproducible example:
x = [1,2,3]
y = {"hello": "world"}
print(y[x])
gives TypeError: unhashable type: 'list'

youtube API get all playlist id from a channel : python

I'm trying to have a list of all playlists from a specific channel in youtube API ... in python
I'd like to have a list of playlist_id in a array
all_playlist_item = []
if I launch
https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UC1udnO-W6gpR9qzleJ5SDKw&key=xxxxxx
here's the response from this request
{
"kind": "youtube#playlistListResponse",
"etag": "PMwo-9BIp7p_L2ynH9sFOGIOido",
"nextPageToken": "CAUQAA",
"pageInfo": {
"totalResults": 17,
"resultsPerPage": 5
},
"items": [
{
"kind": "youtube#playlist",
"etag": "-V67IpyB9a1JGDGJ4pVQnEoMRy4",
"id": "PLWi7PxnyAMeN1tb-ldDzJcnJy2yd5wYrO",
"snippet": {
...
I thing i have to used nextPageToken, but I don't know how to code this function for playlist items
Here's my code (extract in excel all videos just from a specific playlist)
channel_name="UC1udnO-W6gpR9qzleJ5SDKw"
playlist_name="PLWi7PxnyAMeOJmVLv8Z_N3edNyipsnHbo"
api_key = "xxxxxx"
from apiclient.discovery import build
import pandas as pd
youtube = build('youtube', 'v3', developerKey=api_key)
def get_channel_videos(channel_id):
# get Uploads playlist id
res = youtube.channels().list(id=channel_id,
part='contentDetails').execute()
playlist_id = res['items'][0]['contentDetails']['relatedPlaylists']['uploads']
videos = []
next_page_token = None
while 1:
res = youtube.playlistItems().list(playlistId=playlist_name,
part='snippet',
maxResults=50,
pageToken=next_page_token).execute()
videos += res['items']
next_page_token = res.get('nextPageToken')
if next_page_token is None:
break
return videos
videos = get_channel_videos(channel_name)
def get_videos_stats(video_ids):
stats = []
for i in range(0, len(video_ids), 50):
res = youtube.videos().list(id=','.join(video_ids[i:i+50]),
part='statistics').execute()
stats += res['items']
return stats
video_ids = list(map(lambda x:x['snippet']['resourceId']['videoId'], videos))
stats = get_videos_stats(video_ids)
d = []
if len(stats)!=len(videos):
i=1
j=0
else:
i=0
j=0
len_video = len(videos)
len_stats = len(stats)
for video in videos:
if i >= len_video:
break
Url_video='https://www.youtube.com/watch?v='+videos[i]['snippet']['resourceId']['videoId']+'&list='+playlist_name
d.append((videos[i]['snippet']['title'],
videos[i]['snippet']['resourceId']['videoId'],
Url_video,
stats[j]['statistics']['viewCount'],
stats[j]['statistics']['likeCount'],
stats[j]['statistics']['dislikeCount']
))
i+=1
j+=1
df=pd.DataFrame(d, columns=('Titre_video', 'ID_video', 'Url_video','vues','like','dislike'))
df['vues'] = df['vues'].astype(int)
df['like'] = df['like'].astype(int)
df['dislike'] = df['dislike'].astype(int)
df.index+=1
df.to_excel("youtube-playlist.xlsx")
From the pagination doc, you can use :
youtube.playlistItems().list_next(request, response) for iterating playlist item response
youtube.playlists().list_next(request, response) for iterating channel response
Get all videos from Playlist
import googleapiclient.discovery
playlist_id = "PLWi7PxnyAMeOJmVLv8Z_N3edNyipsnHbo"
youtube = googleapiclient.discovery.build("youtube", "v3", developerKey = "YOUR_API_KEY")
request = youtube.playlistItems().list(
part = "snippet",
playlistId = playlist_id,
maxResults = 50
)
response = request.execute()
playlist_items = []
while request is not None:
response = request.execute()
playlist_items += response["items"]
request = youtube.playlistItems().list_next(request, response)
print(f"total: {len(playlist_items)}")
print(playlist_items)
Get all playlists from channel
import googleapiclient.discovery
channel_id = "UC1udnO-W6gpR9qzleJ5SDKw"
youtube = googleapiclient.discovery.build("youtube", "v3", developerKey = "YOUR_API_KEY")
request = youtube.playlists().list(
part = "snippet",
channelId = channel_id,
maxResults = 50
)
response = request.execute()
playlists = []
while request is not None:
response = request.execute()
playlists += response["items"]
request = youtube.playlists().list_next(request, response)
print(f"total: {len(playlists)}")
print(playlists)

Resources