logging.info("kwargs or request End to binance:"+" "+str(kwargs))
response = getattr(self.session, method)(uri, **kwargs)
return self._handle_response(response)
خطایابی درخواست
1-
error:Signature for this request is not valid
solution1:One of your parameters may not be in the correct format.
Check recvWindow is an integer and not a string.
solution2:You may need to regenerate your API Key and Secret
solution3:You may be attempting to access the API from a Chinese IP address, these are now restricted by Binance.
دریافت اطلاعات وب سایت بایننس
def get_exchange_info(self):
"""Return rate limits and list of symbols
:returns: list - List of product dictionaries
.. code-block:: python
{
'timezone': 'UTC',
'serverTime': 1598881503783,
'rateLimits':[Part_Ratelimit],
'exchangeFilters': [empty],
'symbols':[
{
symbol1:,
....
,
'orderTypes':[],
....
,
....
,'filters':[Part_Filters],
'permissions':[]},
{symbol2:},
...]
}
:raises: BinanceResponseException, BinanceAPIException
"""
"""Return information about a symbol
:param symbol: required e.g BNBBTC
:type symbol: str
:returns: Dict if found, None if not
.. code-block:: python
{
Part getExchange
}
:raises: BinanceResponseException, BinanceAPIException
"""
res = self.
for item in res['symbols']:
if item['symbol'] == symbol.upper():
return item
return None
رمزنگاری
def _generate_signature(self, data):
ordered_data = self._order_params(data)
query_string = '&'.join(["{}={}".format(d[0], d[1]) for d in ordered_data])
m = hmac.new(self.API_SECRET.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256)
return m.hexdigest()
ارزیابی پارامترها یا تبدیل پارامترها به لیست
def _order_params(self, data):
"""Convert params to list with signature as last element
:param data:
:return:
"""
has_signature = False
params = []
for key, value in data.items():
if key == 'signature':
has_signature = True
else:
params.append((key, value))
# sort parameters by key
params.sort(key=itemgetter(0))
if has_signature:
params.append(('signature', data['signature']))
return params
ارزیابی پاسخ از سرور بایننس
def _handle_response(self, response):
"""Internal helper for handling API responses from the Binance server.
Raises the appropriate exceptions when necessary; otherwise, returns the
response.
"""
v = self.PRIVATE_API_VERSION if signed else version
return self.API_URL + '/' + v + '/' + path
ثابت های استفاده شده
API_URL =
'https://api.binance.com/api'
WEBSITE_URL =
'https://www.binance.com'
PUBLIC_API_VERSION =
'v1'
PRIVATE_API_VERSION =
'v3'
WITHDRAW_API_VERSION =
'v3'
Serious trading is about timing.Networks can be unstable and unreliable, which can lead to requests taking varying
amounts of time to reach the servers. With recvWindow,you can specify that the request must be processed within
a certain number of milliseconds or be rejected by the server.
In a computing context, an epoch is the date and time relative to which a computer's clock and timestamp values are determined.
The epoch traditionally corresponds to 0 hours, 0 minutes, and 0 seconds (00:00:00) Coordinated Universal Time (UTC) on a specific date,
which varies from system to system. Most versions of Unix, for example, use January 1, 1970 as the epoch date; Windows uses January 1, 1601;
Macintosh systems use January 1, 1904, and Digital Equipment Corporation's Virtual Memory System (VMS) uses November 17, 1858.
The date and time in a computer is determined according to the number of seconds or clock ticks that have elapsed
since the defined epoch for that computer or platform. This number is limited by the word length, and
also by the number of clock ticks per second. In a 32-bit computer with 1 tick per second,
for example, the clock will wrap around (that is, reach its maximum numerical time) on January 18, 2038. This is not likely to be a problem,
because most computers are obsolete after a few years,and longer word lengths and/or new epochs will likely be defined before 2038.
and longer word lengths and/or new epochs will likely be defined before 2038.However, in a computer with 16 ticks per second,
wrap-around can occur well within the useful lifetime of the machine.
Other ways "epoch" is used: In geology, an epoch is a period of time of variable length that is a portion of a period,
which in turn is a fractional part of an era. We are currently in the Holocene epoch, which is part of the Quaternary period,
which in turn is part of the Cenozoic era. In prediction of tides, an epoch is a period of 19 years, representing one complete cycle of
all possible alignments of the sun and the moon. In astronomy, an epoch is the point in time where a calendar, or a defined time frame
within a calendar, is considered to begin. In 1984, the International Astronomical Union decided that
epoch 2000.0 would begin at 1200 UTC on January 1, 2000.
A timestamp is the current time of an event that is recorded by a computer. Through mechanisms such as the Network.
#timestamp in request binance
خطاهای برگشتی از تایم استمپ
1-
error:Timestamp for this request is not valid
solution1:
The timestamp sent is outside of the serverTime -recvWindow
value The timestamp sent is more than 1000ms ahead of the server time
solution2:Check that your system time is in sync.
for some sample code to check the difference between your local time and the Binance server time.
زمان منطقه
The importance of timezones in applications
Once you've heard what Tom says, I think it gets pretty clear that a timestamp without any timezone attached does not give any useful information. It should be considered
irrelevant and useless. Without the necessary context given by the timezone, you cannot infer what point in time your application is really referring to.
That means your application should never handle timestamps with no timezone information. It should try to guess or raises an error if no timezone is provided in any input.
Of course, you can infer that having no timezone information means UTC. This sounds very handy, but can also be dangerous in certain applications or language–such as Python, as we'll see.
Indeed, in certain applications, converting timestamps to UTC and losing the timezone information is a terrible idea.
Imagine that a user create a recurring event every Wednesday at 10:00 in its local timezone, say CET. If you convert that to UTC, the event will end up being stored as every Wednesday at 09:00.
Now imagine that the CET timezone switches from UTC+01:00 to UTC+02:00: your application will compute that the event starts at 11:00 CET every Wednesday.
Which is wrong, because as the user told you, the event starts at 10:00 CET, whatever the definition of CET is. Not at 11:00 CET. So CET means CET, not necessarily UTC+1.
As for endpoints like REST API, a thing I daily deal with, all timestamps should include a timezone information.
It's nearly impossible to know what timezone the timestamps are in otherwise: UTC? Server local? User local? No way to know.
link "The importance of timezones in applications"
زمان هماهنگ جهانی
UTC
Coordinated Universal Time (UTC) is the basis for civil time today. This 24-hour time standard
is kept using highly precise atomic clocks combined with the Earth's rotation.
A Standard, Not a Time Zone
UTC is the time standard commonly used across the world. The world's timing centers have agreed to keep their time
scales closely synchronized - or coordinated - therefore the name Coordinated Universal Time.
link "UTC"
تبدیل زمان منطقه به زمان هماهنگ جهانی
def
d = dateparser.parse(date_str,settings={'TO_TIMEZONE': 'UTC'})#start time:00:00:00
#d = dateparser.parse(date_str)#start time:04:30:00
logging.info("after put date_str to dateparser: " + str(d)+" "+"type: "+str(type(d)))
#........................
# if the date is not timezone aware apply UTC timezone
if d.tzinfo is None or d.tzinfo.utcoffset(d) is None:
d = d.replace(tzinfo=pytz.utc)
logging.info("if d.tzinfo is None or d.tzinfo.utcoffset(d) is None:"+str(d))
Avoid using datetime.replace(tzinfo=…) to make timezones aware
It will only work with UTC and the behavior is inconsistent with other timezones. Rather use localize() as above.
link "Avoid using datetime.replace(tzinfo=…)"
def TimezoneToUTC():
from datetime import datetime
from pytz import timezone
naive = datetime(2020, 8, 29, 21, 28)
UTC = timezone('UTC')
IRR = timezone('Iran')
aware = UTC.localize(naive)
time_in_iran = aware.astimezone(IRR)
چک کردن تاریخ وساعت برای برقراری امنیت در ارتباط با سرور بایننس
زمان برگشتی از سرور بایننس یا تاریخ و ساعت سرور بایننس
def get_server_time(self):
"""
Test connectivity to the Rest API and get the current server time.
:returns: Current server time
.. code-block:: python
{
"serverTime": 1499827319559
}
:raises: BinanceResponseException, BinanceAPIException
"""
return self.
تبدیل تاریخ وزمان به میلی ثانیه
def date_to_milliseconds(date_str):
"""
Convert UTC date to milliseconds
If using offset strings add "UTC" to date string e.g. "now UTC", "11 hours ago UTC"
See dateparse docs for formats http://dateparser.readthedocs.io/en/latest/
:param date_str: date in readable format, i.e. "January 01, 2018", "11 hours ago UTC", "now UTC"
:type date_str: str
"""
'''
an epoch is the date and time relative to which a computer's clock and timestamp values are determined.
'''
# get epoch value in UTC
# parse our date string
#...........................
#UTC=datetime.utcnow()
#Local=datetime.now()
#print(UTC)
#print(epoch)
#print(Local)
#print(date_str)
#.................................
#define epoch, the beginning of times in the UTC timestamp world
# parse our date string
#.........................
#import time
#current_milli= int(round(time.time() * 1000))
#...........................
#start time:00:00:00
d = dateparser.parse(date_str,settings={'TO_TIMEZONE': 'UTC'})
"""Get Historical Klines from Binance
See dateparse docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/
If using offset strings for dates add "UTC" to date string e.g. "now UTC", "11 hours ago UTC"
:param symbol: Name of symbol pair e.g BNBBTC
:type symbol: str
:param interval: Biannce Kline interval
:type interval: str
:param start_str: Start date string in UTC format
:type start_str: str
:param end_str: optional - end date string in UTC format
:type end_str: str
:return: list of OHLCV values
"""
# create the Binance client, no need for api key
# client = Client("", "")
# init our list
output_data = []
# setup the max limit
limit =500 #such as 1m: current time,current time-1m,current time-2m,current time-3m,,...????????
# convert interval to useful value in seconds
timeframe = self.
# convert our date strings to milliseconds
start_ts = self.
# if an end time was passed convert it
end_ts = None
if end_str:
end_ts = self.
idx = 0
# it can be difficult to know when a symbol was listed on Binance so allow start time to be before list date
symbol_existed = False
while True:
# fetch the klines from start_ts up to max 500 entries or the end_ts if set
#print(self.milliseconds_to_date(temp_data[0][0]))
#print("temp_data: "+str(temp_data))
# handle the case where our start date is before the symbol pair listed on Binance
if not symbol_existed and len(temp_data):
symbol_existed = True
if symbol_existed:
# append this loops data to our output data
output_data += temp_data
# update our start timestamp using the last value in the array and add the interval timeframe
# check if we received less than the required limit and exit the loop
if len(temp_data) < limit:
# exit the while loop
break
# sleep after every 3rd call to be kind to the API
if idx % 3 == 0:
sleep(1)
'''
# open a file with filename including symbol, interval and start and end converted to milliseconds
with open(
"Binance_{}_{}_{}-{}.json".format(
symbol,
interval,
self.date_to_milliseconds(start_ts),
self.date_to_milliseconds(end_ts)
),
'w' # set file write mode
) as f:
f.write(json.dumps(temp_data))
'''
return output_data
تبدیل اینتروال یا فاصله زمانی بایننس به میلی ثانیه
def interval_to_milliseconds(self,interval):
"""Convert a Binance interval string to milliseconds
:param interval: Binance interval string 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w
:type interval: str
:return:
None if unit not one of m, h, d or w
None if string not in correct format
int value of interval in milliseconds
"""
#logging.info("Thread %s: starting", 2)
logging.info("Starting function Write CSV File")
with open(PathFile, 'w', newline='') as output_file:
list_writer = csv.writer(output_file)
list_writer.writerow(self.HeadFILE())
logging.info("len Data candle in function write_Csv : %s" ,len(Data_binance_500)) #
for one_minute_milli in Data_binance_500:
#print(self.milliseconds_to_date(one_minute_milli[0])) # convert milliseconds to date)
list_writer.writerow(
[
self.milliseconds_to_date(one_minute_milli[0]), # convert milliseconds to date
one_minute_milli[1],
one_minute_milli[2],
one_minute_milli[3],
one_minute_milli[4],
one_minute_milli[5],
self.milliseconds_to_date(one_minute_milli[6]),
one_minute_milli[7],
one_minute_milli[8],
one_minute_milli[9],
one_minute_milli[10],
one_minute_milli[11]
])
.هدر فایل اکسل که در سطر اول قرار می گیرد و هر ستون را توصیف می کند
def HeadFILE(self):
header_Write_File = [
'Open_time', # Open time
'Open', # Open
'High', # High
'Low', # Low
'Close', # Close
'Volume', # Volume
'Close_time', # Close time
'Quote_asset_volume', # Quote asset volume
'Number_of_trades', # Number of trades
'Taker_buy_base_asset_volume', # Taker buy base asset volume
'Taker_buy_quote_asset_volume', # Taker buy quote asset volume
'Can_be_ignored' # Can be ignored
]
return header_Write_File
ذخیره کندل های دریافت شده از بایننس در پایگاه داده اسکیو ال لایت با زبان پایتون
import sqlite
ذخیره کندل های دریافت شده از بایننس در پایگاه داده اسکیو ال سرور
ذخیره کندل های دریافت شده از بایننس در پایگاه داده اوراکل به زبان پایتون
ذخیره کردن کندل ها درون پایگاه های داده بااستفاده از نخ ها
علت استفاده:
افزایش سرعت
مشکل:
.بعضی مواقع از نخ ها استفاده کردم ولی سرعت افزایش پیدا نکرد
ذخیره کندل ها درون فایل اکسل با نخ ها یا ترد ها
#... thread and csv write file
#Key:time,key:KLINE_INTERVAL_1MINUTE,header:OHCL
logging.info("Main : before creating thread",2)
self.stop_thread2=False
#Key:time,key:KLINE_INTERVAL_1MINUTE,,header:OHCL
self.thread2=Thread(target=self.Write_CsvFile,args=(Key,key,Data_binance_500,header,writeFile,))
logging.info("Main : before running thread",2)
self.thread2.start()
logging.info("Main : wait for the thread to finish")
#self.thread2.join()
logging.info("Thread %s : all done",2)
ذخیره کردن کندل ها درون پایگاه داده ایکس ام ال با نخ ها با استفاده از زبان پایتون
#... thread and xml write file
#Key:time,key:KLINE_INTERVAL_1MINUTE,,header:OHCL
self.thread3=Thread(target=self.Write_XMLFile,args=(start_time,end_time,Key,key,Data_binance_500,header,writeFile,))
logging.info("Main : before running thread %s",3)
self.thread3.start()
logging.info("Main : wait for the thread %s to finish",3)
#self.thread3.join()
logging.info("Thread %s : all done",3)
ذخیره کردن کندل ها درون پایگاه های داده بااستفاده از نخ ها در زبان پایتون یک متد کلی
#... thread and All write file
#change question mark to your functions
دریافت سفارش ها یا اوردر های باز در بایننس با زبان پایتون
def get_open_orders(self, **params):
"""Get all open orders on a symbol.
:param symbol: optional
:type symbol: str
:param recvWindow: the number of milliseconds the request is valid for
:type recvWindow: int
:returns: API response
.. code-block:: python
[
{
"symbol": "LTCBTC",
"orderId": 1,
"clientOrderId": "myOrder1",
"price": "0.1",
"origQty": "1.0",
"executedQty": "0.0",
"status": "NEW",
"timeInForce": "GTC",
"type": "LIMIT",
"side": "BUY",
"stopPrice": "0.0",
"icebergQty": "0.0",
"time": 1499827319559
}
]
:raises: BinanceResponseException, BinanceAPIException
"""
return self.
دریافت کتاب سفارش ها یا اوردربوک از بایننس با زبان پایتون
def get_order_book(self, **params):
"""Get the Order Book for the market
:param symbol: required
:type symbol: str
:param limit: Default 100; max 100
:type limit: int
:returns: API response
.. code-block:: python
{
}
:raises: BinanceResponseException, BinanceAPIException
"""
return self.
ثابت های استفاده شده در بخش سفارش ها یا اوردر بایننس برای برنامه نویسی
ORDER_STATUS_NEW =
'NEW'
ORDER_STATUS_PARTIALLY_FILLED =
'PARTIALLY_FILLED'
ORDER_STATUS_FILLED =
'FILLED'
ORDER_STATUS_CANCELED =
'CANCELED'
ORDER_STATUS_PENDING_CANCEL =
'PENDING_CANCEL'
ORDER_STATUS_REJECTED =
'REJECTED'
ORDER_STATUS_EXPIRED =
'EXPIRED'
ORDER_TYPE_LIMIT =
'LIMIT'
ORDER_TYPE_MARKET =
'MARKET'
ORDER_TYPE_STOP_LOSS =
'STOP_LOSS'
ORDER_TYPE_STOP_LOSS_LIMIT =
'STOP_LOSS_LIMIT'
ORDER_TYPE_TAKE_PROFIT =
'TAKE_PROFIT'
ORDER_TYPE_TAKE_PROFIT_LIMIT =
'TAKE_PROFIT_LIMIT'
ORDER_TYPE_LIMIT_MAKER =
'LIMIT_MAKER'
ORDER_RESP_TYPE_ACK =
'ACK'
ORDER_RESP_TYPE_RESULT =
'RESULT'
ORDER_RESP_TYPE_FULL =
'FULL'
آموزش پایتون
var:
pass
functions:
Variable-length Arguments
Sometimes, we may not know the number of arguments going to be pass
ed in the function, in that case, we can use variable-length arguments.
The arguments we pass as Variable-length Arguments are treated as tuple.
Variable-length Keyword Arguments
Python allows us to send arguments in key=value format.
These are those keyword arguments that do not have fixed length i.e.
during defining a function we do not know the number of keyword arguments are going to be passed.
The arguments we pass as Variable-length Keyword Arguments are treated as dictionary.
ارگومان با طول متغیر
#Variable-length Arguments
def addAll(*args):
print(type(args))
print(args)
result=0
for x in args:
result=result+x
return result
print("sum is",addAll(1,2,3,4,5,6))
print("sum is",addAll(1,2,3))
print("sum is",addAll(1,2))
print("sum is",addAll(1,2,3,4,5,6,7,8,9))
sum:21
sum:6
sum:3
sum:45
ارگومان با طول متغیر
key=value
#Variable-length Keyword Arguments
def addAll(**kwargs):
print(type(kwargs))
print(kwargs)
result=0
for x in kwargs: