به نام هستی بخش دلها

بایننس

functions are member of class Binance

درخواست

def _request(self, method, uri, signed, force_params=False, **kwargs):

# set default requests timeout

kwargs['timeout'] = 100

# add our global requests params

if self._requests_params:
kwargs.update(self._requests_params)

data = kwargs.get('data', None)
if data and isinstance(data, dict):
kwargs['data'] = data
if signed:

# generate signature

kwargs['data']['timestamp'] = int(time.time() * 1000)
kwargs['data']['signature'] = self._generate_signature(kwargs['data'])

# sort get and post params to match signature order

if data:

# find any requests params passed and apply them

if 'requests_params' in kwargs['data']:

# merge requests params into kwargs

kwargs.update(kwargs['data']['requests_params'])
del(kwargs['data']['requests_params'])

# sort post params

kwargs['data'] = self._order_params(kwargs['data'])

# if get request assign data array to params value for requests lib

if data and (method == 'get' or force_params):
kwargs['params'] = kwargs['data']
del(kwargs['data'])
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 self.

محدودیت های بایننس همراه با نوع یا
RateLimits

"rateLimits":

[ {
"rateLimitType": "REQUESTS",
"interval": "MINUTE",
"limit": 1200
},
{
"rateLimitType": "ORDERS",
"interval": "SECOND",
"limit": 10
},
{
"rateLimitType": "ORDERS",
"interval": "DAY",
"limit": 100000
}
],

دریافت اطلاعات همه ارزهای بایننس
ETHBTC

{

'symbol': 'ETHBTC',


'status':
'TRADING',
'baseAsset':
'ETH',

'baseAssetPrecision':
8,
'quoteAsset':
'BTC',
'quotePrecision':
8,
'quoteAssetPrecision':
8,
'baseCommissionPrecision':
8,
'quoteCommissionPrecision':
8,
'orderTypes':
['LIMIT', 'LIMIT_MAKER', 'MARKET', 'STOP_LOSS_LIMIT', 'TAKE_PROFIT_LIMIT'],
'icebergAllowed':
True,
'ocoAllowed':
True,
'filters':
[PART_Filtters],
'quoteOrderQtyMarketAllowed':
True,
'isSpotTradingAllowed':
True,
'isMarginTradingAllowed':
True,
'permissions':
['SPOT', 'MARGIN']
},
{
....
}


فیلترهای یک ارز دربایننس
Filters (ETH-BTC)

'filters'

: [ {
'filterType':'PRICE_FILTER',
'minPrice': '0.00000100'
, 'maxPrice': '100000.00000000',
'tickSize': '0.00000100'
},
{
'filterType': 'PERCENT_PRICE',
'multiplierUp': '5',
'multiplierDown': '0.2',
'avgPriceMins': 5 },
{
'filterType': 'LOT_SIZE',
'minQty': '0.00100000',
'maxQty': '100000.00000000',
'stepSize': '0.00100000'
},
{
'filterType': 'MIN_NOTIONAL',
'minNotional': '0.00010000',
'applyToMarket': True,
'avgPriceMins': 5
},
{
'filterType': 'ICEBERG_PARTS',
'limit': 10
},
{
'filterType': 'MARKET_LOT_SIZE',
'minQty': '0.00000000',
'maxQty': '8425.97418485',
'stepSize': '0.00000000'
},
{
'filterType': 'MAX_NUM_ALGO_ORDERS',
'maxNumAlgoOrders': 5
},
{
'filterType': 'MAX_NUM_ORDERS',
'maxNumOrders': 200
}
],

دریافت اطلاعات یک جفت ارز در بایننس

def get_symbol_info(self, symbol):

"""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. """
if not str(response.status_code).startswith('2'):
raise BinanceAPIException(response)
try:
return response.json()
except ValueError:
raise BinanceRequestException('Invalid Response: %s' % response.text)

خطایابی درخواست یا خطاهای برگشتی از سرور بایننس

class BinanceRequestException(Exception):

def __init__(self, message):
self.message = message
def __str__(self):
logging.info('BinanceRequestException: %s' % self.message)
return 'BinanceRequestException: %s' % self.message

خطایابی توابع بایننس یا خطاهای برگشتی از سرور بایننس

class BinanceAPIException(Exception):

LISTENKEY_NOT_EXIST = '-1125'
#constructor
def __init__(self, response):
self.status_code = 0
try:
json_res = response.json()
except ValueError:
logging.info('Invalid JSON error message from Binance: {}'.format(response.text))
self.message = 'Invalid JSON error message from Binance: {}'.format(response.text)
else:
self.code = json_res['code']
self.message = json_res['msg']
self.status_code = response.status_code
self.response = response
self.request = getattr(response, 'request', None)
#output
def __str__(self): # pragma: no cover
logging.info('APIError(code=%s): %s' % (self.code, self.message))
return 'APIError(code=%s): %s' % (self.code, self.message)

تشخیص این که آیا به وب سایت یا سرور بایننس یا به توابع بایننس متصل هستیم یانه؟

def ping(self):

"""
Test connectivity to the Rest API.
:returns: Empty array
.. code-block:: python

{}

:raises: BinanceResponseException, BinanceAPIException

"""
return self._get('ping')

ایجاد درخواست

def _get(self, path, signed=False, version=PUBLIC_API_VERSION, **kwargs):

"""
'get':,
path:,
signed:,
version:,
**kwargs:
"""
return self.

درخواست به مسیر یا درخواست به توابع بایننس

def _request_api(self, method, path, signed=False, version=PUBLIC_API_VERSION, **kwargs):

"""
self:,
method:,
path:,
signed=False:,
version=PUBLIC_API_VERSION:,
**kwargs:
"""
uri = self.
return self.

ایجاد مسیر درخواست

def _create_api_uri(self, path, signed=True, version=PUBLIC_API_VERSION):

"""
self:,
path:,
signed=True:,
version=PUBLIC_API_VERSION:,
"""
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.


انواع زمان ها

import datetime

epoch = datetime.utcfromtimestamp(0).replace(tzinfo=pytz.utc)
UTC=datetime.utcnow()
utc_timestamp = UTC.timestamp()
Local=datetime.now()
servertime=self.servertime=int(self.

print(UTC)
print(epoch)
print(utc_timestamp)
print(Local)
print(servertime)


epoch

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.


link "epoch"

timestamp

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 TimeSecurity(self):

#Time Security
#1-recvWindow:,
#2-timestamp:,
#3-servertime:

recvWindow=5000
timestamp=int(time.time()*1000)
servertime=int(self.

logging.info("timestamp:"+str(timestamp))
logging.info("servertime+1000:"+str(servertime+1000))
logging.info("servertime-timestamp:"+str(servertime-timestamp))
logging.info('recvWindow:'+str(recvWindow))

#important
if((timestamp < servertime+1000) and(servertime-timestamp<=recvWindow)):
return True
else:
return False


زمان برگشتی از سرور بایننس یا تاریخ و ساعت سرور بایننس

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
epoch = datetime.utcfromtimestamp(0).replace(tzinfo=pytz.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'})
#start time:04:30:00
#d = dateparser.parse(date_str)
# 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)

# return the difference in time
return int((d - epoch).total_seconds() * 1000.0)


تبدیل میلی ثانیه به تاریخ و ساعت

def milliseconds_to_date(self,milliseconds):

s = milliseconds/ 1000.0
dte = datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')

#return dte.split() #return date and time
return dte


تفاضل یا تفاوت دو تاریخ وساعت یا زمان

from datetime import datetime

#method1 int to datetime
def diff():
d1 = datetime(2020, 8, 29, 21, 52)
d2 = datetime(2020, 8, 29, 22, 52)

if d2 < d1:
d2 += timedelta(days=1)
print(d2-d1)

#method2 :str to datetime
def diff2():
d1 = datetime.strptime('2020-8-29 21:52:00',"%Y-%m-%d %H:%M:%S")
d2 = datetime.strptime('2020-8-29 22:52:00',"%Y-%m-%d %H:%M:%S")

if d2 < d1:
d2 += timedelta(days=1)
print(d2-d1)

#method3 :str_datetime split to date and time then diff time and date
def between_two_time():
str_datetime1='2020-8-29 21:52:00'
str_datetime2='2020-8-29 22:52:00'

dt1,tm1=(str_datatime1).split()
dt2,tm2=(str_datatime2).split()

#format time
FMT = '%H:%M:%S.%f'
#tdelta=diff time
tdelta = datetime.strptime(tm2, FMT) - datetime.strptime(tm, FMT)
value_min=(tdelta.total_seconds())//60

if tdelta.days < 0:
tdelta = timedelta(days=0,seconds=tdelta.seconds, microseconds=tdelta.microseconds)
value_min=(tdelta.total_seconds())//60
return value_min,tdelta


تفاضل زمان یا تاریخ و ساعت پیشرفته با پاندا

mport pandas as pd
from pandas import Timedelta

d = {
"CallDate": [
"1/8/2009",
"1/11/2009",
"1/9/2009",
"1/11/2009",
"1/16/2009",
"1/17/2009",
"1/19/2009",
"1/20/2009",
"1/20/2009",
"1/23/2009",
"1/30/2009"
],
"BeginningTime": [
"1900-01-01 07:49:00",
"1900-01-01 14:37:00",
"1900-01-01 09:29:00",
"1900-01-01 09:20:00",
"1900-01-01 15:11:00",
"1900-01-01 22:52:00",
"1900-01-01 05:48:00",
"1900-01-01 23:46:00",
"1900-01-01 21:29:00",
"1900-01-01 07:33:00",
"1900-01-01 19:33:00"
],
"EndingTime": [
"1900-01-01 08:19:00",
"1900-01-01 14:59:00",
"1900-01-01 09:56:00",
"1900-01-01 10:13:00",
"1900-01-01 15:50:00",
"1900-01-01 23:26:00",
"1900-01-01 06:32:00",
"1900-01-01 00:21:00",
"1900-01-01 22:08:00",
"1900-01-01 07:55:00",
"1900-01-01 20:01:00"
]
}

df = pd.DataFrame(data=d)

df['BeginningTime']=pd.to_datetime(df['BeginningTime'], format="%Y-%m-%d %H:%M:%S")
df['EndingTime']=pd.to_datetime(df['EndingTime'], format="%Y-%m-%d %H:%M:%S")

def interval(x):

if x['EndingTime'] < x['BeginningTime']:
x['EndingTime'] += Timedelta(days=1)
return x['EndingTime'] - x['BeginningTime']

df['Interval'] = df.apply(interval, axis=1)


In [2]: df
Out[2]:
BeginningTime CallDate EndingTime Interval
0 1900-01-01 07:49:00 1/8/2009 1900-01-01 08:19:00 00:30:00
1 1900-01-01 14:37:00 1/11/2009 1900-01-01 14:59:00 00:22:00
2 1900-01-01 09:29:00 1/9/2009 1900-01-01 09:56:00 00:27:00
3 1900-01-01 09:20:00 1/11/2009 1900-01-01 10:13:00 00:53:00
4 1900-01-01 15:11:00 1/16/2009 1900-01-01 15:50:00 00:39:00
5 1900-01-01 22:52:00 1/17/2009 1900-01-01 23:26:00 00:34:00
6 1900-01-01 05:48:00 1/19/2009 1900-01-01 06:32:00 00:44:00
7 1900-01-01 23:46:00 1/20/2009 1900-01-01 00:21:00 00:35:00
8 1900-01-01 21:29:00 1/20/2009 1900-01-01 22:08:00 00:39:00
9 1900-01-01 07:33:00 1/23/2009 1900-01-01 07:55:00 00:22:00
10 1900-01-01 19:33:00 1/30/2009 1900-01-01 20:01:00 00:28:00

link "Advance diff by panda"


تاریخ و ساعت (زمان) حال به میلی ثانیه

import time

current_milli= int(round(time.time() * 1000))


what is Socket?


what is one?


what is two?


what is three?


what is four?


what is five?


what is kandle?

Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.


مشاهده کندل ها در حالت زمان اجرا در وب سایت تریدینگ ویو

.صفحه خوش آمدگویی یا صفحه ای که تمام اطلاعات در آن طبقه بندی شده است



صفحه مربوط به یک ارز خاص حاوی اطلاعات درباره آن ارز


کندل های 15 دقیقه ای کاردانو- تتر



یک کندل حاوی چه اطلاعاتی می تواند باشد؟
اطلاعات یک کندل بایننس

# Open time
1499040000000,
# Open
"0.01634790",
# High
"0.80000000",
# Low
"0.01575800",
# Close
"0.01577100",
# Volume
"148976.11427815",
# Close time
1499644799999,
# Quote asset volume
"2434.19055334",
# Number of trades
308,
# Taker buy base asset volume
"1756.87402397",
# Taker buy quote asset volume
"28.46694368",
# Can be ignored
"17928899.62484339"

اطلاعات برگشتی از یک کندل بایننس در وب سایت تریدینگ ویو



دریافت اطلاعات کندل ها از نظر زمانی یا اینتروال

#Binance interval string
#m:minute
1m, 3m, 5m, 15m, 30m,
#h:hour
1h, 2h, 4h, 6h, 8h, 12h,
#d:day
1d, 3d,
#w=week
1w
#M:month
1M

مشاهده کندل ها از نظر زمانی


.کندل های زیر ،کندل های پانزده دقیقه ای تتر کاردانو بایننس در وب سایت تریدینگ ویو می باشد
بایننس اطلاعات کندل ها را از یک دقیقه به بالا می دهد .(فعلا)




دریافت اطلاعات یک کندل از وب سایت بایننس یا
یا OHCL
. اطلاعات درباره قیمت یک ارزکه در کندل قرار می گیرد

def get_klines(self, **params):

"""Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.
#input

#....
:param symbol: required
:type symbol: str
:param interval: -
:type interval: enum
#.....
:param limit: - Default 500; max 500.
:type limit: int
:param startTime:
:type startTime: int
:param endTime:
:type endTime: int

:raises: BinanceResponseException, BinanceAPIException

"""

return self.


خطاهای گرفتن کندل برگشتی از سرور بایننس

1-
get_klines('ADAUSDT','1m',10,2020/8/30,"")

error:TypeError: get_klines() takes 1 positional argument but 6 were given

2-
get_klines(symbol='ADAUSDT',interval='1m',startTime='2020/8/30')
#error: APIError(code=-1104): Not all sent parameters were read; read '2' parameter(s) but was sent '3'.

3-
get_klines(symbol='ADAUSDT',interval='1m',startTime=
#no error

4-
get_klines(symbol='ADAUSDT',interval=1m)
#error: SyntaxError: invalid syntax.

5-
get_klines(symbol='ADAUSDT',interval='1m')
#no error

گرفتن کندل ها در یک بازه زمانی با اینتروال دربایننس

def get_historical_klines(self,symbol, interval, start_str, end_str=None):

"""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
temp_data = self.(
symbol=symbol,
interval=interval,
limit=limit,
startTime=start_ts,
endTime=end_ts
)

#if(temp_data==[] or temp_data==None):#limit=0
# temp_data_empty=True
# break
#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
start_ts = temp_data[len(temp_data) - 1][0] + timeframe
else:
# it wasn't listed yet, increment our start date
start_ts += timeframe
logging.info("idx %s" , idx)
idx += 1
# 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
"""
ms = None
seconds_per_unit = {
"m": 60,
"h": 60 * 60,
"d": 24 * 60 * 60,
"w": 7 * 24 * 60 * 60,
"M": 30 * 24 * 60 * 60
}
unit = interval[-1]
if unit in seconds_per_unit:
try:
ms = int(interval[:-1]) * seconds_per_unit[unit] * 1000
except ValueError:
pass
return ms

ثابت های بخش کندل در بایننس


KLINE_INTERVAL_1MINUTE =

'1m'
KLINE_INTERVAL_3MINUTE =
'3m'
KLINE_INTERVAL_5MINUTE =
'5m'
KLINE_INTERVAL_15MINUTE =
'15m'
KLINE_INTERVAL_30MINUTE =
'30m'
KLINE_INTERVAL_1HOUR =
'1h'
KLINE_INTERVAL_2HOUR =
'2h'
KLINE_INTERVAL_4HOUR =
'4h'
KLINE_INTERVAL_6HOUR =
'6h'
KLINE_INTERVAL_8HOUR =
'8h'
KLINE_INTERVAL_12HOUR =
'12h'
KLINE_INTERVAL_1DAY =
'1d'
KLINE_INTERVAL_3DAY =
'3d'
KLINE_INTERVAL_1WEEK =
'1w'
KLINE_INTERVAL_1MONTH =
'1M'

ذخیره کردن کندل های دریافت شده از بایننس در پایگاه داده های مختلف

ذخیره کندل های دریافت شده از بایننس در پایگاه داده نوت پد با زبان پایتون

ذخیره کندل های دریافت شده از بایننس در پایگاه داده نوت پد به صورت جی سان با زبان پایتون

# open a file with filename including symbol, interval and start and end converted to milliseconds
with open(
"Binance_{}_{}_{}-{}.json".format(
symbol,
interval,
date_to_milliseconds(start),
date_to_milliseconds(end)
),
# set file write mode
'w' ) as f:
f.write(json.dumps(klines))

ذخیره کندل های دریافت شده از بایننس در پایگاه داده ایکس ام ال با زبان پایتون

#write candles to XMLFiles
def Write_XMLFile(self,start_time,end_time,Key,key,Data_binance_500,PathFile,writeFile=False):
#logging.info("Thread %s: starting", 3)
logging.info("Staring Write Xml File \n")
# data = ET.Element('data') #
#tree = ET.parse('ADAUSDTbinance1year/BinanceData1year.xml')
root = ET.Element("data")#
#root = tree.getroot()

Kan = ET.SubElement(root, 'KANDLE')#
Kan.set("StartTime", start_time) #
Kan.set("EndTime", end_time)#
Kan.set("TypeKandle", Key) #
Kan.set("TypeTime", key)#

logging.info("len %s : %s" , key,len(Data_binance_500)) #
i=1
for one_minute_milli in Data_binance_500:#problem analyse 1minute
#print(self.milliseconds_to_date(one_minute_milli[0])) # convert milliseconds to date)
open_time = self.milliseconds_to_date(one_minute_milli[0]) # convert milliseconds to datev close_time = self.milliseconds_to_date(one_minute_milli[6]) # convert milliseconds to date
o_c_time = ET.SubElement(Kan, "Recorde"+str(i)) #
o_c_time.set("OpenTime", open_time)#
o_c_time.set("CloseTime", close_time)#
o_c_time.text =str(one_minute_milli[1])+","+str(one_minute_milli[2])+","+str(one_minute_milli[3])+","
+str(one_minute_milli[4])+","+str(one_minute_milli[5])+","+str(one_minute_milli[7])+","+str(one_minute_milli[8])+",
"+str(one_minute_milli[9])+","+str(one_minute_milli[10])+","+str(one_minute_milli[11])
# create a new XML file with the results
i+=1
tree = ET.ElementTree(root)
tree.write(PathFile )
writeFile = True
logging.info('Status File: %s' ,str(writeFile))
logging.info("Directory %s End." , PathFile)
#self.stop(3)

ذخیره کندل های دریافت شده از بایننس در پایگاه داده اکسل با زبان پایتون

def Write_CsvFile(self,Data_binance_500,PathFile,writeFile):#Key:time,key:KLINE_INTERVAL_1MINUTE,,header:OHCL

'''
:param Dire:
:param Type:
:param Data_binance_500:
:param header:
:param writeFile:
:return:
'''
#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]
])
writeFile = True
logging.info('Status File:%s' , str(writeFile))
logging.info("Directory %s End", PathFile)
logging.info("..................")
#self.stop(2)

.هدر فایل اکسل که در سطر اول قرار می گیرد و هر ستون را توصیف می کند

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
def run_Write_CsvFile(self,Key,key,Data_binance_500,header,writeFile):
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
def run_Write_XMLFile(self,start_time,end_time,Key,key,Data_binance_500,header,writeFile):
logging.info("Main : before creating thread %s",3) self.stop_thread3=False
#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
self.thread3=Thread(target=self. Write_?,args=(start_time,end_time,Key,key,Data_binance_500,header,writeFile,))

اندیکاتور

بیشترین مقدار ورودی ها

کمترین مقدار ورودی ها

میانگین ورودی ها

Simple Moving Average

دریافت سفارش ها یا اوردر های باز در بایننس با زبان پایتون

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:
result=result+kwargs[x]
return result

print(addAll(key1=1, key2=2, key3=3))
print(addAll(key1=3, key2=1, key3=2))
print(addAll(key1=3, key2=2, key3=1))


sum:6
sum:6
sum:6



آموزش ارتباط با پایگاه داده های مختلف با زبان پایتون

Part1:install lib
Part2: connect databse
Part3:fetch data from database






#connect Python to MySQL
pip install MySQL
import MySQLdb

db=MySQLdb.connect(host="your host name",
user='your username',
passwd='your password',
db='your database')
cur=db.cursor()
cur.execute("SELECT * FROM your table")
for row in cur.fetchall():
print(row)
db.close()


ارتباط با پایگاه داده اسکیوال سرور با زبان پایتون

#connect python to SQL Server
pip install pyodbc

import pyodbc
conn=pyodbc.connect('Driver={};'
'Server=server_name;'
'DataBase=database_name;'
'Trusted_Connection=yes;')

# cursor=conn.cursor()
cursor.execute('SELECT * FROM database_name.table')
for row in cursor:
print(row)


ارتباط با پایگاه داده اوراکل بازبان پایتون

python -m pip install cx_Oracle
import cx_Oracle

# Connect as user "hr" with password "welcome" to the "orclpdb1" service running on this computer.
connection = cx_Oracle.connect("hr", "welcome", "localhost/orclpdb1")

cursor = connection.cursor()
cursor.execute("""
SELECT first_name, last_name
FROM employees
WHERE department_id = :did AND employee_id > :eid""",
did = 50,
eid = 190)
for fname, lname in cursor:
print("Values:", fname, lname)


link "Oracle"

ارتباط با پایگاه داده مون گو دی با با پایتون

python -m pip install pymongo

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]


dblist = myclient.list_database_names()
if "mydatabase" in dblist:
print("The database exists.")


link "MongoDB"

ارتباط با پایگاه داده پست اسکیو ال با زبان پایتون

pip install psycopg2
CREATE DATABASE suppliers;
conn = psycopg2.connect("dbname=suppliers user=postgres password=postgres")

conn = psycopg2.connect(
host="localhost",
database="suppliers",
user="postgres",
password="Abcd1234")



#!/usr/bin/python
from configparser import ConfigParser

def config(filename='database.ini', section='postgresql'):
# create a parser
parser = ConfigParser()
# read config file
parser.read(filename)

# get section, default to postgresql
db = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
db[param[0]] = param[1]
else:
raise Exception('Section {0} not found in the {1} file'.format(section, filename))

return db




#!/usr/bin/python
import psycopg2
from config import config
def connect():
""" Connect to the PostgreSQL database server """
conn = None
try:
# read connection parameters
params = config()
# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
conn = psycopg2.connect(**params)
# create a cursor
cur = conn.cursor()
# execute a statement
print('PostgreSQL database version:')
cur.execute('SELECT version()')
# display the PostgreSQL database server version
db_version = cur.fetchone()
print(db_version)
# close the communication with the PostgreSQL
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')
if __name__ == '__main__':
connect()


link "PostgreSQL"

آموزش رمزنگاری

:رمزنگاری


متقارن
غیر متقارن


آموزش کتابخانه رمزنگاری هش 256 در زبان پایتون

import hashlib
def encrypt_string(hash_string):
sha_signature = \
hashlib.sha256(hash_string.encode()).hexdigest()
return sha_signature
hash_string = 'confidential data'
sha_signature = encrypt_string(hash_string)


link "SHA256"

آموزش مرحله به مرحله الگوریتم رمزنگاری کلید خصوصی کلید عمومی دیف هلمن

Step by Step Explanation

ALICE BOB
Public Keys available = P, G Public Keys available = P, G
Private Key Selected = a Private Key Selected = b
Key generated = x = G^a mod P Key generated = y = G^b mod P
Exchange of generated keys takes place
Key received = y key received = x
Generated Secret Key = k_a = y^a mod P Generated Secret Key = k_b = x^b mod P
Algebraically it can be shown that k_a = k_b
Users now have a symmetric secret key to encrypt

انتقال داده بین دونفر با الگوریتم هلمن به زبان انسان

Example

Step 1:
Alice and Bob get public numbers P = 23, G = 9

Step 2:
Alice selected a private key a = 4 and
Bob selected a private key b = 3

Step 3:
Alice and Bob compute public values
Alice: x =(9^4 mod 23) = (6561 mod 23) = 6
Bob: y = (9^3 mod 23) = (729 mod 23) = 16

Step 4:
Alice and Bob exchange public numbers

Step 5:
Alice receives public key y =16 and
Bob receives public key x = 6

Step 6:
Alice and Bob compute symmetric keys
Alice: ka = y^a mod p = 65536 mod 23 = 9
Bob: kb = x^b mod p = 216 mod 23 = 9

Step 7: 9
is the shared secret.


link "Diffie-Hellman-Desc"

پیاده سازی الگوریتم رمزنگاری دیف هلمن

/* This program calculates the Key for two persons
using the Diffie-Hellman Key exchange algorithm */
#include
#include

// Power function to return value of a ^ b mod P
long long int power(long long int a, long long int b,
long long int P)
{
if (b == 1)
return a;

else
return (((long long int)pow(a, b)) % P);
}

//Driver program
int main()
{
long long int P, G, x, a, y, b, ka, kb;

// Both the persons will be agreed upon the
// public keys G and P

// A prime number P is taken
P = 23; printf("The value of P : %lld\n", P);

// A primitve root for P, G is taken

G = 9;
printf("The value of G : %lld\n\n", G);

// Alice will choose the private key a
// a is the chosen private key

a = 4; printf("The private key a for Alice : %lld\n", a);
// gets the generated key

x = power(G, a, P);
// Bob will choose the private key b
// b is the chosen private key

b = 3; printf("The private key b for Bob : %lld\n\n", b);
// gets the generated key

y = power(G, b, P);

// Generating the secret key after the exchange
// of keys

// Secret key for Alice
ka = power(y, a, P);
// Secret key for Bob

kb = power(x, b, P);
printf("Secret key for the Alice is : %lld\n", ka);
printf("Secret Key for the Bob is : %lld\n", kb);

return 0;
}


link "Diffie-Hellman-Algorithm"

پیاده سازی الگوریتم رمزنگاری دیف هلمن در زبان پایتون

#Importing necessary modules
from tinyec import registry
import secrets
#Getting the 'brainpoolP256r1' curve from the registry
curve = registry.get_curve('brainpoolP256r1')

#Generating Alice's private
alice_privatekey = secrets.randbelow(curve.field.n)
print("Alice's private key: ", alice_privatekey)

#Generating Bob's private key
bob_privatekey = secrets.randbelow(curve.field.n)
print("Bob's private key: ", bob_privatekey)

#Generate Alice's publickey from her private key and Generator point
alice_publickey = alice_privatekey * curve.g
print("Alice's public key: ", alice_publickey)

#Generate Bob's publickey from his private key and Generator point
bob_publickey = bob_privatekey * curve.g
print("Bob's public key: ", bob_publickey)

#The shared key with Alice
alice_sharedkey = alice_privatekey*bob_publickey
print("Alice's shared secret key: ", alice_sharedkey)

#The shared key with Bob
bob_sharedkey = bob_privatekey*alice_publickey
print("Bob's shared secret key: ", bob_sharedkey)


try:
alice_sharedkey == bob_sharedkey
print("Shared secret keys match each other")

except:
print("Shared secret keys don't match each other")


link "Diffie-Hellman-Python"




نرم افزارهای موجود یا ساخته شده در این زمینه

نرم افزار1:
نرم افزار2:
نرم افزار3:
نرم افزار4:

منابع

WebPages:
https://binance.com/
https://copyassignment.com/
https://www.w3schools.com/
https://www.instagram.com/python.hub/
https://github.com/
Ebooks:
githup
binance

.کانال ارتباطی ، هرگونه سوال در این زمینه پاسخ داده می شود

email:
knowledgecomputer2018@gmail.com
QuestionComputionAnswer2020@gmail.com (not work)