コード例 #1
0
def main():
    try:
        # p = Process(target=receiver, args=(5678,))
        # p.start()

        f = FeedHandler()
        # print(binance_delivery_data_info)
        # print(binance_futures_data_info)
        binance_futures_symbols = defaultdict(list)
        for instrument in BinanceFutures.get_instrument_objects():
            binance_futures_symbols[instrument.instrument_type].append(
                instrument.instrument_name)
        print(binance_futures_symbols)

        binance_delivery_symbols = defaultdict(list)
        for instrument in BinanceDelivery.get_instrument_objects():
            binance_delivery_symbols[instrument.instrument_type].append(
                instrument.instrument_name)
        print(binance_delivery_symbols)

        # f.add_feed(BinanceDelivery(symbols=binance_delivery_symbols[PERPETUAL], channels=[FUNDING], callbacks={FUNDING: FundingZMQ(port=5678)}))
        f.add_feed(
            BinanceFutures(symbols=binance_futures_symbols[PERPETUAL],
                           channels=[FUNDING],
                           callbacks={FUNDING: FundingZMQ(port=5679)}))
        f.run()

    finally:
        p.terminate()
コード例 #2
0
def main():
    path_to_config = 'config.yaml'

    binance = Binance(config=path_to_config,
                      subscription={
                          BALANCES: [],
                          ORDER_INFO: []
                      },
                      timeout=-1,
                      callbacks={
                          BALANCES: balance,
                          ORDER_INFO: order_info
                      })
    binance_delivery = BinanceDelivery(config=path_to_config,
                                       subscription={
                                           BALANCES: [],
                                           POSITIONS: [],
                                           ORDER_INFO: []
                                       },
                                       timeout=-1,
                                       callbacks={
                                           BALANCES: balance,
                                           POSITIONS: position,
                                           ORDER_INFO: order_info
                                       })
    binance_futures = BinanceFutures(config=path_to_config,
                                     subscription={
                                         BALANCES: [],
                                         POSITIONS: [],
                                         ORDER_INFO: []
                                     },
                                     timeout=-1,
                                     callbacks={
                                         BALANCES: balance,
                                         POSITIONS: position,
                                         ORDER_INFO: order_info
                                     })

    print(binance._generate_token())
    print(binance_delivery._generate_token())
    print(binance_futures._generate_token())

    f = FeedHandler()
    f.add_feed(binance)
    f.add_feed(binance_delivery)
    f.add_feed(binance_futures)
    f.run()
コード例 #3
0
def main():
    f = FeedHandler()
    f.add_feed(
        BinanceDelivery(max_depth=3,
                        pairs=['BTC-USD_201225'],
                        channels=[L2_BOOK],
                        callbacks={L2_BOOK: abook}))
    f.run()
コード例 #4
0
def main():
    f = FeedHandler()
    f.add_feed(
        BinanceDelivery(max_depth=3,
                        symbols=[info['symbols'][-1]],
                        channels=[L2_BOOK, TRADES, TICKER],
                        callbacks={
                            L2_BOOK: abook,
                            TRADES: trades,
                            TICKER: ticker
                        }))
    f.run()
コード例 #5
0
def main():
    path_to_config = 'config.yaml'
    binance = Binance(config=path_to_config)
    print(binance.balances_sync())
    print(binance.orders_sync())
    order = binance.place_order_sync('BTC-USDT', SELL, LIMIT, 0.002, 80000, time_in_force=GOOD_TIL_CANCELED, test=False)
    print(binance.orders_sync(symbol='BTC-USDT'))
    print(order)
    print(binance.cancel_order_sync(order['orderId'], symbol='BTC-USDT'))
    print(binance.orders_sync(symbol='BTC-USDT'))

    binance_futures = BinanceFutures(config=path_to_config)
    print(binance_futures.balances_sync())
    print(binance_futures.orders_sync())
    print(binance_futures.positions_sync())
    order = binance_futures.place_order_sync('ETH-USDT-PERP', SELL, LIMIT, 20, 5000, time_in_force=GOOD_TIL_CANCELED)
    print(binance_futures.orders_sync(symbol='BTC-USDT-PERP'))
    print(binance_futures.orders_sync(symbol='ETH-USDT-PERP'))
    print(order)
    print(binance_futures.cancel_order_sync(order['orderId'], symbol='ETH-USDT-PERP'))
    print(binance_futures.orders_sync(symbol='ETH-USDT-PERP'))

    binance_delivery = BinanceDelivery(config=path_to_config)
    print(binance_delivery.balances_sync())
    print(binance_delivery.orders_sync())
    print(binance_delivery.positions_sync())
    order = binance_delivery.place_order_sync('ETH-USD-PERP', SELL, LIMIT, 0.05, 5000, time_in_force=GOOD_TIL_CANCELED, test=False)
    print(binance_delivery.orders_sync(symbol='BTC-USDT-PERP'))
    print(binance_delivery.orders_sync(symbol='ETH-USDT-PERP'))
    print(order)
    print(binance_delivery.cancel_order_sync(order['orderId'], symbol='ETH-USDT-PERP'))
    print(binance_delivery.orders_sync(symbol='ETH-USDT-PERP'))

    f = FeedHandler()
    f.add_feed(BinanceDelivery(max_depth=3, symbols=[info['symbols'][-1]],
                               channels=[L2_BOOK, TRADES, TICKER],
                               callbacks={L2_BOOK: abook, TRADES: trades, TICKER: ticker}))
    f.run()
コード例 #6
0
from datetime import datetime

from cryptofeed import FeedHandler
from cryptofeed.defines import L2_BOOK
from cryptofeed.exchanges import BinanceDelivery

data_info = BinanceDelivery.info()


async def abook(feed, pair, book, timestamp, receipt_timestamp):
    print(
        f'BOOK lag: {receipt_timestamp - timestamp} Timestamp: {datetime.fromtimestamp(timestamp)} Receipt Timestamp: {datetime.fromtimestamp(receipt_timestamp)} Feed: {feed} Pair: {pair} Snapshot: {book}'
    )


async def delta(feed, pair, delta, timestamp, receipt_timestamp):
    print(
        f'DELTA lag: {receipt_timestamp - timestamp} Timestamp: {datetime.fromtimestamp(timestamp)} Receipt Timestamp: {datetime.fromtimestamp(receipt_timestamp)} Feed: {feed} Pair: {pair} Delta: {delta}'
    )


def main():
    f = FeedHandler()
    f.add_feed(
        BinanceDelivery(max_depth=3,
                        pairs=['BTC-USD_201225'],
                        channels=[L2_BOOK],
                        callbacks={L2_BOOK: abook}))
    f.run()

コード例 #7
0
def main():
    try:
        # p = Process(target=receiver, args=(5678,))
        # p.start()

        path_to_config = os.path.join(Path.home(), 'config.yaml')

        f = FeedHandler()
        binance_futures_symbols = defaultdict(list)
        for instrument in BinanceFutures.get_instrument_objects():
            binance_futures_symbols[instrument.instrument_type].append(instrument.instrument_name)
        print(binance_futures_symbols)

        binance_delivery_symbols = defaultdict(list)
        for instrument in BinanceDelivery.get_instrument_objects():
            binance_delivery_symbols[instrument.instrument_type].append(instrument.instrument_name)
        print(binance_delivery_symbols)

        # binance_symbols = set()
        # for instrument in BinanceDelivery.get_instrument_objects():
        #     binance_symbols.add(instrument.base + '-USDT')
        # print(binance_symbols)
        binance_symbols = []
        for instrument in Binance.info()['symbols']:
            if instrument.endswith('-USDT'):
                binance_symbols.append(instrument)
        print(binance_symbols)

        feeds = []
        feeds.append(BinanceDelivery(candle_interval='1d', symbols=binance_delivery_symbols[PERPETUAL], channels=[FUTURES_INDEX, FUNDING, TICKER, TRADES, VOLUME], callbacks={
            FUNDING: FundingZMQ(port=5678), 
            TICKER: TickerZMQ(port=5679), 
            TRADES: TradeZMQ(port=5682), 
            FUTURES_INDEX: FuturesIndexZMQ(port=5684),
            VOLUME: VolumeZMQ(port=5685)}))
        feeds.append(BinanceDelivery(candle_interval='1d', symbols=binance_delivery_symbols[FUTURE], channels=[FUTURES_INDEX, TICKER, TRADES, VOLUME], callbacks={
            TICKER: TickerZMQ(port=5687), 
            TRADES: TradeZMQ(port=5688), 
            FUTURES_INDEX: FuturesIndexZMQ(port=5689),
            VOLUME: VolumeZMQ(port=5690)}))
        feeds.append(BinanceDelivery(config=path_to_config, channels=[USER_BALANCE, USER_POSITION], symbols=[], callbacks={
            USER_BALANCE: UserBalanceZMQ(port=5691),
            USER_POSITION: UserPositionZMQ(port=5692)}))

        feeds.append(BinanceFutures(symbols=binance_futures_symbols[PERPETUAL], channels=[FUNDING], callbacks={FUNDING: FundingZMQ(port=5680)}))
        
        feeds.append(Binance(symbols=list(binance_symbols), channels=[TICKER, TRADES, VOLUME], callbacks={
            TICKER: TickerZMQ(port=5681), 
            TRADES: TradeZMQ(port=5683),
            VOLUME: VolumeZMQ(port=5686)}))
        feeds.append(Binance(config=path_to_config, channels=[USER_BALANCE], symbols=[], callbacks={
            USER_BALANCE: UserBalanceZMQ(port=5693)}))
        
        tasks = []
        for feed in feeds:
            if feed.requires_authentication:
                tasks.append(do_periodically_every(0, 30, 0, feed.auth.refresh_token))
            f.add_feed(feed)
        f.run(tasks=tasks)
    
    finally:
        p.terminate()
コード例 #8
0
import asyncio
from datetime import datetime
from collections import defaultdict
from multiprocessing import Process
import os
from pathlib import Path
import sys
from yapic import json

from cryptofeed import FeedHandler
from cryptofeed.backends.zmq import CandlesZMQ, FundingZMQ, FuturesIndexZMQ, TickerZMQ, TradeZMQ, VolumeZMQ, UserBalanceZMQ, UserPositionZMQ
from cryptofeed.defines import CANDLES, FUTURES_INDEX, L2_BOOK, FUNDING, TICKER, PERPETUAL, FUTURE, TRADES, VOLUME, USER_BALANCE, USER_POSITION
from cryptofeed.exchanges import BinanceFutures, BinanceDelivery, Binance

binance_delivery_data_info = BinanceDelivery.info()
# binance_futures_data_info = BinanceFutures.info()
binance_data_info = Binance.info()
print(binance_data_info)

import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

def receiver(port):
    async def listen():
        while True:
            data = await s.recv_string()
            print(data)
            key, msg = data.split(" ", 1)
            print(key)
            # print(json.loads(msg))
            msg = json.loads(msg)
コード例 #9
0
ファイル: test_binance.py プロジェクト: vroomzel/cryptofeed
'''
Copyright (C) 2017-2022 Bryant Moscon - [email protected]

Please see the LICENSE file for the terms and conditions
associated with this software.
'''
import asyncio
from decimal import Decimal

from cryptofeed.defines import BINANCE, BINANCE_DELIVERY, BINANCE_FUTURES, BUY, SELL
from cryptofeed.exchanges import BinanceFutures, BinanceDelivery, Binance
from cryptofeed.types import Candle

b = Binance()
bd = BinanceDelivery()
bf = BinanceFutures()


def teardown_module(module):
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:
        loop = asyncio.new_event_loop()

    loop.run_until_complete(b.shutdown())
    loop.run_until_complete(bf.shutdown())
    loop.run_until_complete(bd.shutdown())


class TestBinanceRest:
    def test_trade(self):
コード例 #10
0
class BinanceDelivery(API):
    ID = BINANCE_DELIVERY
    api = "https://dapi.binance.com/dapi/v1/"
    info = BinanceDelivery()

    def _get(self, endpoint, retry, retry_wait):
        @request_retry(self.ID, retry, retry_wait)
        def helper():
            r = requests.get(f"{self.api}{endpoint}")
            self._handle_error(r, LOG)
            return r.json()

        return helper()

    def _nonce(self):
        return str(int(round(time.time() * 1000)))

    def _generate_signature(self, url: str, body=json.dumps({})):
        nonce = self._nonce()
        signature = "/api/" + url + nonce + body
        h = hmac.new(self.config.key_secret.encode('utf8'),
                     signature.encode('utf8'), hashlib.sha384)
        signature = h.hexdigest()

        return {
            "X-MBX-APIKEY": self.config.key_id,
            "signature": signature,
            "content-type": "application/json"
        }

    def _trade_normalization(self, symbol: str, trade: list) -> dict:
        ret = {
            'timestamp': timestamp_normalize(self.ID, trade['T']),
            'symbol': self.info.exchange_symbol_to_std_symbol(symbol),
            'id': trade['a'],
            'feed': self.ID,
            'side': BUY if trade['m'] is True else SELL,
            'amount': abs(float(trade['q'])),
            'price': float(trade['p']),
        }

        return ret

    def _get_trades_hist(self, symbol, start_date, end_date, retry,
                         retry_wait):
        start = None
        end = None

        if start_date:
            if not end_date:
                end_date = pd.Timestamp.utcnow()
            start = API._timestamp(start_date)
            end = API._timestamp(end_date) - pd.Timedelta(nanoseconds=1)

            start = int(start.timestamp() * 1000)
            end = int(end.timestamp() * 1000)

        @request_retry(self.ID, retry, retry_wait)
        def helper(start, end):
            if start and end:
                return requests.get(
                    f"{self.api}aggTrades?symbol={symbol}&limit={REQUEST_LIMIT}&startTime={start}&endTime={end}"
                )
            else:
                return requests.get(f"{self.api}aggTrades?symbol={symbol}")

        while True:
            r = helper(start, end)

            if r.status_code == 429:
                sleep(int(r.headers['Retry-After']))
                continue
            elif r.status_code == 500:
                LOG.warning("%s: 500 for URL %s - %s", self.ID, r.url, r.text)
                sleep(retry_wait)
                continue
            elif r.status_code != 200:
                self._handle_error(r, LOG)
            else:
                sleep(RATE_LIMIT_SLEEP)

            data = r.json()
            if data == []:
                LOG.warning("%s: No data for range %d - %d", self.ID, start,
                            end)
            else:
                if data[-1]['T'] == start:
                    LOG.warning(
                        "%s: number of trades exceeds exchange time window, some data will not be retrieved for time %d",
                        self.ID, start)
                    start += 1
                else:
                    start = data[-1]['T']

            data = list(
                map(lambda x: self._trade_normalization(symbol, x), data))
            yield data

            if len(data) < REQUEST_LIMIT:
                break

    def trades(self,
               symbol: str,
               start=None,
               end=None,
               retry=None,
               retry_wait=10):
        symbol = self.info.std_symbol_to_exchange_symbol(symbol)
        for data in self._get_trades_hist(symbol, start, end, retry,
                                          retry_wait):
            yield data