Python binance futures klines

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.

a simple connector to Binance Public API

License

binance/binance-connector-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

* update user agent * update test case

Git stats

Files

Failed to load latest commit information.

README.md

Binance Public API Connector Python

This is a lightweight library that works as a connector to Binance public API

  • Supported APIs:
    • /api/*
    • /sapi/*
    • Spot Websocket Market Stream
    • Spot User Data Stream
    • Spot WebSocket API
    pip install binance-connector
    from binance.spot import Spot client = Spot() # Get server timestamp print(client.time()) # Get klines of BTCUSDT at 1m interval print(client.klines("BTCUSDT", "1m")) # Get last 10 klines of BNBUSDT at 1h interval print(client.klines("BNBUSDT", "1h", limit=10)) # API key/secret are required for user data endpoints client = Spot(api_key='', api_secret='') # Get account and balance information print(client.account()) # Post a new order params = < 'symbol': 'BTCUSDT', 'side': 'SELL', 'type': 'LIMIT', 'timeInForce': 'GTC', 'quantity': 0.002, 'price': 9500 > response = client.new_order(**params) print(response)

    Please find examples folder to check for more endpoints.

    • In order to set your API and Secret Key for use of the examples, create a file examples/config.ini with your keys.
    • Eg:
    # examples/config.ini Python binance futures klines api_key=abc123456 api_secret=cba654321

    Binance supports HMAC, RSA and ED25519 API authentication.

    # HMAC: pass API key and secret client = Client(api_key, api_secret) print(client.account()) # RSA Keys client = Client(api_key=api_key, private_key=private_key) print(client.account()) # ED25519 Keys api_key = "" private_key = "./private_key.pem" private_key_pass = "" with open(private_key, 'rb') as f: private_key = f.read() spot_client = Client(api_key=api_key, private_key=private_key, private_key_pass=private_key_pass) # Encrypted RSA Key client = Client(api_key=api_key, private_key=private_key, private_key_pass='password') print(client.account())

    Please find examples/spot/wallet/account_snapshot.py for more details on ED25519. Please find examples/spot/trade/get_account.py for more details on RSA.

    Spot Testnet is available, it can be used to test /api/* endpoints.

    from binance.spot import Spot as Client client = Client(base_url='https://testnet.binance.vision') print(client.time())

    If base_url is not provided, it defaults to api.binance.com .
    It’s recommended to pass in the base_url parameter, even in production as Binance provides alternative URLs in case of performance issues:

    PEP8 suggests lowercase with words separated by underscores, but for this connector, the methods’ optional parameters should follow their exact naming as in the API documentation.

    # Recognised parameter name response = client.cancel_oco_order('BTCUSDT', orderListId=1) # Unrecognised parameter name response = client.cancel_oco_order('BTCUSDT', order_list_id=1)

    Additional parameter recvWindow is available for endpoints requiring signature.
    It defaults to 5000 (milliseconds) and can be any value lower than 60000 (milliseconds). Anything beyond the limit will result in an error response from Binance server.

    from binance.spot import Spot as Client client = Client(api_key, api_secret) response = client.get_order('BTCUSDT', orderId=11, recvWindow=10000)

    timeout is available to be assigned with the number of seconds you find most appropriate to wait for a server response.
    Please remember the value as it won’t be shown in error message no bytes have been received on the underlying socket for timeout seconds.
    By default, timeout is None. Hence, requests do not time out.

    from binance.spot import Spot as Client client= Client(timeout=1)
    from binance.spot import Spot as Client proxies = < 'https': 'http://1.2.3.4:8080' > client= Client(proxies=proxies)

    The Binance API server provides weight usages in the headers of each response. You can display them by initializing the client with show_limit_usage=True :

    from binance.spot import Spot as Client client = Client(show_limit_usage=True) print(client.time())
    'data': 'serverTime': 1587990847650>, 'limit_usage': 'x-mbx-used-weight': '31', 'x-mbx-used-weight-1m': '31'>>

    You can also display full response metadata to help in debugging:

    client = Client(show_header=True) print(client.time())
    'data': 'serverTime': 1587990847650>, 'header': 'Context-Type': 'application/json;charset=utf-8', . >>

    If ClientError is received, it’ll display full response meta information.

    Setting the log level to DEBUG will log the request URL, payload and response text.

    There are 2 types of error returned from the library:

    • binance.error.ClientError
      • This is thrown when server returns 4XX , it’s an issue from client side.
      • It has 5 properties:
        • status_code — HTTP status code
        • error_code — Server’s error code, e.g. -1102
        • error_message — Server’s error message, e.g. Unknown order sent.
        • header — Full response header.
        • error_data * — Additional detailed data which supplements the error_message .
          • *Only applicable on select endpoints, eg. cancelReplace
          • This is thrown when server returns 5XX , it’s an issue from server side.

          WebSocket can be established through either of the following types of connections:

          • WebSocket API ( https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-api.md )
          • WebSocket Stream ( https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-streams.md )
          # WebSocket API Client from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient def message_handler(_, message): logging.info(message) my_client = SpotWebsocketAPIClient(on_message=message_handler) my_client.ticker(symbol="BNBBUSD", type="FULL") time.sleep(5) logging.info("closing ws connection") my_client.stop()
          # WebSocket Stream Client from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient def message_handler(_, message): logging.info(message) my_client = SpotWebsocketStreamClient(on_message=message_handler) # Subscribe to a single symbol stream my_client.agg_trade(symbol="bnbusdt") time.sleep(5) logging.info("closing ws connection") my_client.stop()

          Client can assign a request id to each request. The request id will be returned in the response message. Not mandatory in the library, it generates a uuid format string if not provided.

          # id provided by client my_client.ping_connectivity(id="my_request_id") # library will generate a random uuid string my_client.ping_connectivity()
          • If you set is_combined to True , «/stream/» will be appended to the baseURL to allow for Combining streams.
          • is_combined defaults to False and «/ws/» (raw streams) will be appended to the baseURL .

          More websocket examples are available in the examples folder.

          Example file «examples/websocket_api/app_demo.py» demonstrates how Websocket API and Websocket Stream can be used together.

          from binance.websocket.spot.websocket_client import SpotWebsocketClient as WebsocketClient def message_handler(message): print(message) ws_client = WebsocketClient() ws_client.start() ws_client.mini_ticker( symbol='bnbusdt', id=1, callback=message_handler, ) # Combine selected streams ws_client.instant_subscribe( stream=['bnbusdt@bookTicker', 'ethusdt@bookTicker'], callback=message_handler, ) ws_client.stop()

          Once connected, the websocket server sends a ping frame every 3 minutes and requires a response pong frame back within a 10 minutes period. This package handles the pong responses automatically.

          from binance.websocket.spot.websocket_client import SpotWebsocketClient as WebsocketClient ws_client = WebsocketClient(stream_url='wss://testnet.binance.vision')
          # In case packages are not installed yet pip install -r requirements/requirements-test.txt pytest

          Futures and Vanilla Options APIs are not supported:

          Contributions are welcome.
          If you’ve found a bug within this project, please open an issue to discuss what you would like to change.
          If it’s an issue with the API, please open a topic at Binance Developer Community

          About

          a simple connector to Binance Public API

          Источник

          Market Data Endpoints¶

          Iterate over aggregate trades for a symbol from a given date or a given order id.

          agg_trades = client.aggregate_trade_iter(symbol='ETHBTC', start_str='30 minutes ago UTC') # iterate over the trade iterator for trade in agg_trades: print(trade) # do something with the trade data # convert the iterator to a list # note: generators can only be iterated over once so we need to call it again agg_trades = client.aggregate_trade_iter(symbol='ETHBTC', '30 minutes ago UTC') agg_trade_list = list(agg_trades) # example using last_id value agg_trades = client.aggregate_trade_iter(symbol='ETHBTC', last_id=23380478) agg_trade_list = list(agg_trades) 

          Get Kline/Candlesticks¶

          candles = client.get_klines(symbol='BNBBTC', interval=Client.KLINE_INTERVAL_30MINUTE) 

          Get Historical Kline/Candlesticks¶

          Fetch klines for any date range and interval

          # fetch 1 minute klines for the last day up until now klines = client.get_historical_klines("BNBBTC", Client.KLINE_INTERVAL_1MINUTE, "1 day ago UTC") # fetch 30 minute klines for the last month of 2017 klines = client.get_historical_klines("ETHBTC", Client.KLINE_INTERVAL_30MINUTE, "1 Dec, 2017", "1 Jan, 2018") # fetch weekly klines since it listed klines = client.get_historical_klines("NEOBTC", Client.KLINE_INTERVAL_1WEEK, "1 Jan, 2017") 

          Get Historical Kline/Candlesticks using a generator¶

          Fetch klines using a generator

          for kline in client.get_historical_klines_generator("BNBBTC", Client.KLINE_INTERVAL_1MINUTE, "1 day ago UTC"): print(kline) # do something with the kline 

          Get average price for a symbol¶

          avg_price = client.get_avg_price(symbol='BNBBTC') 

          Get 24hr Ticker¶

          tickers = client.get_ticker() 

          Get All Prices¶

          Get last price for all markets.

          prices = client.get_all_tickers() 

          Get Orderbook Tickers¶

          Get first bid and ask entry in the order book for all markets.

          tickers = client.get_orderbook_tickers() 

          © 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.

          Источник

          Читайте также:  Can we restart thread java
Оцените статью