Binance client api python

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

c0lon/binance-api-python

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Requires python 3.6 or greater.

git clone https://github.com/c0lon/binance.git cd binance python setup.py install 

First, enter your API key and secret into config.yaml. Then run the command below:

Any log messages are written to tests/test.log .

To enter a pdb shell on a test failure, run

See the pytest docs for more information.

By default, tests that would change your account in any way, such as placing an order or withdrawing funds, are disabled. To enable them, edit pytest.ini by changing

[pytest] testpaths = tests/test_fetchers.py 

then follow the instructions in tests/test_actions.py.

Enabling these tests means that your account balances will be changed if the tests are successful. Follow the configuration instructions very carefully. Failing to do so could result in the tests altering your account in a negative way.

from binance import BinanceClient client = BinanceClient(apikey, apisecret) client.ping()

Most client methods described below return objects that can be found in binance/storage.py. These objects convert values into their natives types, including:

Each object accepts a raw API version of the object in its constructor. These objects also have a to_json() method that returns the object as a JSON-dumpable dictionary.

Methods with names ending with _async are asynchronous coroutines that perform the same action as their synchronous counterpart. (Read more about Python’s asynchronous features here.)

Return the server time in milliseconds as an integer.

def get_ticker(self, symbol='') 
def get_depth(self, symbol) async def get_depth_async(self, symbol) 

Return list of binance.storage.Candlestick .

def get_candlesticks(self, symbol, interval, **kwargs) async def get_candlesticks_async(self, symbol, interval, **kwargs) 

Return list of binance.storage.Trade .

def get_trade_info(self, symbol) 

Return list of binance.storage.Order .

def get_open_orders(self, symbol) 

Return list of binance.storage.Order .

def get_all_orders(self, symbol): 
def get_order_status(self, symbol, order_id) def place_market_buy(self, symbol, quantity, **kwargs) def place_market_sell(self, symbol, quantity, **kwargs) def place_limit_buy(self, symbol, quantity, price, **kwargs) def place_limit_sell(self, symbol, quantity, price, **kwargs) 

Return True if order was canceled successfully.

def cancle_order(self, order_id) 

Return True if the withdraw is successfully initiated.

def withdraw(self, asset, amount, address, **kwargs) 

Return list of binance.storage.Withdraw .

def get_withdraw_history(self, asset='', **kwargs) 

Return list of binance.storage.Deposit .

def get_deposit_history(self, asset='', **kwargs) 

Websocket Endpoint Methods

def watch_depth(self, symbol) 

See watch_depth.py for an example of how to use the asynchronous watch_depth() method.

def watch_candlesticks(self, symbol) 

See watch_candlesticks.py for an example of how to use the asynchronous watch_candlesticks() method.

Register an asynchronous coroutine that is fired on certain client events.

  • on_depth_ready
  • on_depth_event
  • on_candlesticks_ready
  • on_candlesticks_event

In order for the scripts below to work correctly, you must put your apiKey and secretKey into the apikey and apisecret slots in config.yaml, respectively.

usage: watchdepth [-h] [--log-level ] [--version] [--debug] [-l DEPTH_LIMIT] config_uri symbol positional arguments: config_uri the config file to use. symbol watch the depth of symbol . optional arguments: -h, --help show this help message and exit --log-level --version Show the package version and exit. --debug -l DEPTH_LIMIT, --depth-limit DEPTH_LIMIT show the latest orders on each side. 
usage: watchcandlesticks [-h] [--log-level ] [--version] [--debug] [-d DEPTH] config_uri symbol interval positional arguments: config_uri the config file to use. symbol watch the candlesticks of symbol . interval set the candlesticks interval. optional arguments: -h, --help show this help message and exit --log-level --version Show the package version and exit. --debug -d DEPTH, --depth DEPTH display the latest candlesticks. 

Источник

Getting Started¶

python-binance is available on PYPI. Install with pip :

pip install python-binance 

Register on Binance¶

Generate an API Key¶

To use signed account methods you are required to create an API Key.

Initialise the client¶

Pass your API Key and Secret

from binance.client import Client client = Client(api_key, api_secret) 

or for Asynchronous client

async def main(): # initialise the client client = await AsyncClient.create(api_key, api_secret) if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main()) 

Using the Spot, Futures or Vanilla Options Testnet¶

Binance offers a Spot, Futures and Vanilla Options Testnet, to test interacting with the exchange.

To enable this set the testnet parameter passed to the Client to True.

The testnet parameter will also be used by any websocket streams when the client is passed to the BinanceSocketManager.

client = Client(api_key, api_secret, testnet=True) 

or for Asynchronous client

client = await AsyncClient.create(api_key, api_secret, testnet=True) 

Using a different TLD¶

If you are interacting with a regional version of Binance which has a different TLD such as .us or ` .jp’ then you will need to pass this when creating the client, see examples below.

This tld will also be used by any websocket streams when the client is passed to the BinanceSocketManager.

client = Client(api_key, api_secret, tld='us') 

or for Asynchronous client

client = await AsyncClient.create(api_key, api_secret, tld='us') 

Making API Calls¶

Every method supports the passing of arbitrary parameters via keyword matching those in the Binance API documentation. These keyword arguments will be sent directly to the relevant endpoint.

Each API method returns a dictionary of the JSON response as per the Binance API documentation. The docstring of each method in the code references the endpoint it implements.

The Binance API documentation references a timestamp parameter, this is generated for you where required.

Some methods have a recvWindow parameter for timing security, see Binance documentation.

API Endpoints are rate limited by Binance at 20 requests per second, ask them if you require more.

Async API Calls¶

aiohttp is used to handle asyncio REST requests.

Each function available in the normal client is available in the AsyncClient class.

The only difference is to run within an asyncio event loop and await the function like below.

import asyncio from binance import AsyncClient async def main(): client = await AsyncClient.create() # fetch exchange info res = await client.get_exchange_info() print(json.dumps(res, indent=2)) await client.close_connection() if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main()) 

Read Async basics for Binance for more information about asynchronous patterns.

API Rate Limit¶

Check the get_exchange_info() call for up to date rate limits.

At the current time Binance rate limits are:

Some calls have a higher weight than others especially if a call returns information about all symbols. Read the official Binance documentation for specific information.

On each request Binance returns X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter) and X-MBX-ORDER-COUNT-(intervalNum) headers.

Here are examples to access these

import asyncio from binance import AsyncClient api_key = '' api_secret = '' async def main(): client = await AsyncClient.create(api_key, api_secret) res = await client.get_exchange_info() print(client.response.headers) await client.close_connection() if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main()) 
from binance import Client api_key = '' api_secret = '' def main(): client = Client(api_key, api_secret) res = client.get_exchange_info() print(client.response.headers) if __name__ == "__main__": main() 

Requests Settings¶

python-binance uses the requests library.

You can set custom requests parameters for all API calls when creating the client.

client = Client("api-key", "api-secret", "verify": False, "timeout": 20>) 

You may also pass custom requests parameters through any API call to override default settings or the above settingsspecify new ones like the example below.

# this would result in verify: False and timeout: 5 for the get_all_orders call client = Client("api-key", "api-secret", "verify": False, "timeout": 20>) client.get_all_orders(symbol='BNBBTC', requests_params='timeout': 5>) 

Check out the requests documentation for all options.

Proxy Settings

You can use the Requests Settings method above

proxies =  'http': 'http://10.10.1.10:3128', 'https': 'http://10.10.1.10:1080' > # in the Client instantiation client = Client("api-key", "api-secret", 'proxies': proxies>) # or on an individual call client.get_all_orders(symbol='BNBBTC', requests_params='proxies': proxies>) 

Or set an environment variable for your proxy if required to work across all requests.

An example for Linux environments from the requests Proxies documentation is as follows.

$ export HTTP_PROXY="http://10.10.1.10:3128" $ export HTTPS_PROXY="http://10.10.1.10:1080" 
C:\>set HTTP_PROXY=http://10.10.1.10:3128 C:\>set HTTPS_PROXY=http://10.10.1.10:1080

© Copyright 2017, Sam McHardy Revision a354b258 .

Versions latest stable Downloads pdf html epub On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.

Источник

Читайте также:  Найти сумму нечетных элементов массива python
Оцените статью