Exemplo n.º 1
0
def main():
    f = FeedHandler()
    f.add_feed(
        FTX(symbols=FTX.info()['symbols'],
            channels=[OPEN_INTEREST, LIQUIDATIONS],
            callbacks={
                OPEN_INTEREST: OpenInterestCallback(oi),
                LIQUIDATIONS: LiquidationCallback(liquidations)
            }))
    symbols = [
        s for s in BinanceFutures.info()['symbols'] if 'PINDEX' not in s
    ]
    f.add_feed(
        BinanceFutures(symbols=symbols,
                       channels=[OPEN_INTEREST, LIQUIDATIONS],
                       callbacks={
                           OPEN_INTEREST: OpenInterestCallback(oi),
                           LIQUIDATIONS: LiquidationCallback(liquidations)
                       }))

    f.add_feed(
        Deribit(symbols=['BTC-USD-PERPETUAL', 'ETH-USD-PERPETUAL'],
                channels=[LIQUIDATIONS, OPEN_INTEREST],
                callbacks={
                    OPEN_INTEREST: OpenInterestCallback(oi),
                    LIQUIDATIONS: LiquidationCallback(liquidations)
                }))
    f.run()
Exemplo n.º 2
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()
Exemplo n.º 3
0
def main(proxy):
    futures_symbols = BinanceFutures.info()['symbols']
    futures_symbols = [
        symbol for symbol in futures_symbols if 'PINDEX' not in symbol
    ]
    shuffle(futures_symbols)
    futures_symbols = futures_symbols[:20]

    # use high volume pairs for quick l2_book updates
    book_symbols = [
        'ETH-BTC', 'LTC-BTC', 'ADA-BTC', 'BTC-USDT', 'ETH-USDT', 'LTC-USDT',
        'BNB-BTC', 'BNB-ETH'
    ]

    f = FeedHandler()
    counter = Counter(f)
    f.add_feed(
        Binance(depth_interval='1000ms',
                http_proxy=proxy,
                max_depth=1,
                symbols=book_symbols,
                channels=[L2_BOOK],
                callbacks={
                    L2_BOOK:
                    counter.callback(BINANCE, L2_BOOK, book_symbols, False)
                }))
    f.add_feed(
        Binance(depth_interval='1000ms',
                http_proxy=proxy,
                max_depth=1,
                symbols=book_symbols,
                channels=[L2_BOOK],
                callbacks={
                    L2_BOOK: counter.callback(BINANCE, L2_BOOK, book_symbols,
                                              True)
                }))
    f.add_feed(
        BinanceFutures(http_proxy=proxy,
                       open_interest_interval=1.0,
                       symbols=futures_symbols,
                       channels=[OPEN_INTEREST],
                       callbacks={
                           OPEN_INTEREST:
                           counter.callback(BINANCE_FUTURES, OPEN_INTEREST,
                                            futures_symbols, False)
                       }))
    f.add_feed(
        BinanceFutures(http_proxy=proxy,
                       open_interest_interval=1.0,
                       symbols=futures_symbols,
                       channels=[OPEN_INTEREST],
                       callbacks={
                           OPEN_INTEREST:
                           counter.callback(BINANCE_FUTURES, OPEN_INTEREST,
                                            futures_symbols, True)
                       }))

    f.run()
Exemplo n.º 4
0
def main():
    config = {'log': {'filename': 'demo.log', 'level': 'INFO'}}
    # the config will be automatically passed into any exchanges set up by string. Instantiated exchange objects would need to pass the config in manually.
    f = FeedHandler(config=config)
    # Note: EXX is extremely unreliable - sometimes a connection can take many many retries
    # from cryptofeed.exchanges import EXX
    # f.add_feed(EXX(symbols=['BTC-USDT'], channels=[L2_BOOK, TRADES], callbacks={L2_BOOK: BookCallback(book), TRADES: TradeCallback(trade)}))
    f.add_feed(KuCoin(symbols=['BTC-USDT', 'ETH-USDT'], channels=[L2_BOOK, ], callbacks={L2_BOOK: book, BOOK_DELTA: delta, CANDLES: candle_callback, TICKER: ticker, TRADES: trade}))
    f.add_feed(Gateio(symbols=['BTC-USDT', 'ETH-USDT'], channels=[L2_BOOK], callbacks={CANDLES: candle_callback, L2_BOOK: book, TRADES: trade, TICKER: ticker, BOOK_DELTA: delta}))
    pairs = Binance.symbols()
    f.add_feed(Binance(symbols=pairs, channels=[TRADES], callbacks={TRADES: TradeCallback(trade)}))
    pairs = BinanceUS.symbols()
    f.add_feed(BinanceUS(symbols=pairs, channels=[CANDLES], callbacks={CANDLES: candle_callback}))
    f.add_feed(COINBASE, symbols=['BTC-USD'], channels=[TICKER], callbacks={TICKER: TickerCallback(ticker)})
    f.add_feed(Coinbase(symbols=['BTC-USD'], channels=[TRADES], callbacks={TRADES: TradeCallback(trade)}))
    f.add_feed(Coinbase(subscription={L2_BOOK: ['BTC-USD', 'ETH-USD'], TRADES: ['ETH-USD']}, callbacks={TRADES: TradeCallback(trade), L2_BOOK: BookCallback(book)}))
    f.add_feed(Coinbase(subscription={L3_BOOK: ['LTC-USD']}, callbacks={L3_BOOK: BookCallback(book)}))
    f.add_feed(Bitfinex(symbols=['BTC-USDT'], channels=[L2_BOOK], callbacks={L2_BOOK: BookCallback(book)}))
    f.add_feed(Bitfinex(symbols=['BTC'], channels=[FUNDING], callbacks={FUNDING: FundingCallback(funding)}))
    f.add_feed(Poloniex(symbols=['BTC-USDT'], channels=[TICKER, TRADES], callbacks={TICKER: TickerCallback(ticker), TRADES: TradeCallback(trade)}))
    f.add_feed(Poloniex(subscription={TRADES: ['DOGE-BTC'], L2_BOOK: ['LTC-BTC']}, callbacks={TRADES: TradeCallback(trade), L2_BOOK: BookCallback(book)}))
    f.add_feed(GEMINI, subscription={L2_BOOK: ['BTC-USD', 'ETH-USD'], TRADES: ['ETH-USD', 'BTC-USD']}, callbacks={TRADES: TradeCallback(trade), L2_BOOK: BookCallback(book)})
    f.add_feed(HitBTC(channels=[TRADES], symbols=['BTC-USD'], callbacks={TRADES: TradeCallback(trade)}))
    f.add_feed(HitBTC(channels=[L2_BOOK], symbols=['BTC-USD'], callbacks={L2_BOOK: BookCallback(book)}))
    f.add_feed(Bitstamp(channels=[L2_BOOK, TRADES], symbols=['BTC-USD'], callbacks={L2_BOOK: BookCallback(book), TRADES: TradeCallback(trade)}))
    bitmex_symbols = Bitmex.symbols()
    f.add_feed(Bitmex(channels=[OPEN_INTEREST], symbols=['BTC-USD'], callbacks={OPEN_INTEREST: oi}))
    f.add_feed(Bitmex(channels=[TRADES], symbols=bitmex_symbols, callbacks={TRADES: TradeCallback(trade)}))
    f.add_feed(Bitmex(symbols=['BTC-USD'], channels=[FUNDING, TRADES], callbacks={FUNDING: FundingCallback(funding), TRADES: TradeCallback(trade)}))
    f.add_feed(Bitmex(symbols=['BTC-USD'], channels=[L2_BOOK], callbacks={L2_BOOK: BookCallback(book)}))
    f.add_feed(Kraken(checksum_validation=True, subscription={L2_BOOK: ['BTC-USD'], TRADES: ['BTC-USD'], CANDLES: ['BTC-USD'], TICKER: ['ETH-USD']}, callbacks={L2_BOOK: book, CANDLES: candle_callback, TRADES: TradeCallback(trade), TICKER: TickerCallback(ticker)}))
    sub = {TRADES: ['BTC-USDT', 'ETH-USDT'], L2_BOOK: ['BTC-USDT']}
    f.add_feed(Huobi(subscription=sub, callbacks={TRADES: TradeCallback(trade), L2_BOOK: BookCallback(book)}))
    f.add_feed(Huobi(symbols=['BTC-USDT'], channels=[CANDLES], callbacks={CANDLES: candle_callback}))
    sub = {L2_BOOK: ['BTC_CQ', 'BTC_NQ']}
    f.add_feed(HuobiDM(subscription=sub, callbacks={TRADES: TradeCallback(trade), L2_BOOK: BookCallback(book)}))
    pairs = ['BTC-USD', 'ETH-USD', 'EOS-USD', 'BCH-USD', 'BSV-USD', 'LTC-USD']
    f.add_feed(HuobiSwap(symbols=pairs, channels=[TRADES, L2_BOOK, FUNDING], callbacks={FUNDING: funding, TRADES: TradeCallback(trade), L2_BOOK: BookCallback(book)}))
    f.add_feed(OKCoin(symbols=['BTC-USD'], channels=[L2_BOOK], callbacks={L2_BOOK: BookCallback(book)}))
    f.add_feed(OKEx(symbols=['BTC-USDT'], channels=[TRADES], callbacks={TRADES: TradeCallback(trade)}))
    f.add_feed(Bittrex(subscription={L2_BOOK: ['BTC-USDT', 'ETH-USDT'], CANDLES: ['BTC-USDT', 'ETH-USDT'], TRADES: ['BTC-USDT', 'ETH-USDT'], TICKER: ['BTC-USDT', 'ETH-USDT']}, callbacks={CANDLES: candle_callback, L2_BOOK: BookCallback(book), TICKER: TickerCallback(ticker), TRADES: TradeCallback(trade)}))
    f.add_feed(FTX(symbols=['ADA-PERP', 'ALGO-PERP', 'ALT-PERP', 'ATOM-PERP', 'BCH-PERP', 'BNB-PERP', 'BSV-PERP', 'BTC-PERP', 'BTMX-PERP', 'DOGE-PERP', 'DRGN-PERP', 'EOS-PERP', 'ETC-PERP'], channels=[TICKER], callbacks={TICKER: ticker, TRADES: TradeCallback(trade)}))
    f.add_feed(Bybit(symbols=['BTC-USDT', 'BTC-USD'], channels=[FUTURES_INDEX], callbacks={OPEN_INTEREST: OpenInterestCallback(oi), FUTURES_INDEX: FuturesIndexCallback(futures_index)}))
    f.add_feed(Bybit(symbols=['BTC-USDT', 'BTC-USD'], channels=[L2_BOOK, TRADES], callbacks={TRADES: trade, L2_BOOK: book}))
    f.add_feed(BLOCKCHAIN, symbols=['BTC-USD', 'ETH-USD'], channels=[L2_BOOK, TRADES], callbacks={L2_BOOK: BookCallback(book), TRADES: trade})
    f.add_feed(Bitmax(symbols=['XRP-USDT', 'BTC-USDT'], channels=[L2_BOOK], callbacks={TRADES: trade, L2_BOOK: book}))
    f.add_feed(Bitflyer(symbols=['BTC-JPY'], channels=[L2_BOOK, TRADES, TICKER], callbacks={L2_BOOK: book, BOOK_DELTA: delta, TICKER: ticker, TRADES: trade}))
    f.add_feed(BinanceFutures(symbols=['BTC-USDT'], channels=[TICKER], callbacks={TICKER: ticker}))
    f.add_feed(BinanceFutures(subscription={TRADES: ['BTC-USDT'], CANDLES: ['BTC-USDT', 'BTC-USDT-PINDEX']}, callbacks={CANDLES: candle_callback, TRADES: trade}))
    f.add_feed(dYdX(symbols=dYdX.symbols(), channels=[L2_BOOK], callbacks={TRADES: trade, L2_BOOK: book, BOOK_DELTA: delta}))

    f.run()
Exemplo n.º 5
0
def main():
    config = {'log': {'filename': 'demo.log', 'level': 'DEBUG', 'disabled': False}}
    # the config will be automatically passed into any exchanges set up by string. Instantiated exchange objects would need to pass the config in manually.
    f = FeedHandler(config=config)

    f.add_feed(FMFW(symbols=['BTC-USDT'], channels=[CANDLES, L2_BOOK, TRADES, TICKER], callbacks={CANDLES: candle_callback, TICKER: ticker, L2_BOOK: book, TRADES: trade}))
    f.add_feed(AscendEX(symbols=['XRP-USDT'], channels=[L2_BOOK, TRADES], callbacks={L2_BOOK: book, TRADES: trade}))
    f.add_feed(Bequant(symbols=['BTC-USDT'], channels=[L2_BOOK], callbacks={L2_BOOK: book, TRADES: trade, TICKER: ticker, CANDLES: candle_callback}))
    pairs = Binance.symbols()[:1]
    f.add_feed(Binance(symbols=pairs, channels=[L2_BOOK], callbacks={L2_BOOK: book, CANDLES: candle_callback, TRADES: trade, TICKER: ticker}))
    pairs = BinanceFutures.symbols()[:30]
    f.add_feed(BinanceFutures(symbols=pairs, channels=[TRADES, OPEN_INTEREST, FUNDING, LIQUIDATIONS], callbacks={TRADES: trade, OPEN_INTEREST: oi, FUNDING: funding, LIQUIDATIONS: liquidations}))
    f.add_feed(BinanceUS(symbols=BinanceUS.symbols()[:2], channels=[TRADES, L2_BOOK], callbacks={L2_BOOK: book, TRADES: trade}))
    f.add_feed(Bitfinex(symbols=['BTC-USDT'], channels=[L3_BOOK], callbacks={L3_BOOK: book, TICKER: ticker, TRADES: trade}))
    f.add_feed(Bitflyer(symbols=['BTC-JPY'], channels=[TICKER, TRADES, L2_BOOK], callbacks={L2_BOOK: book, TICKER: ticker, TRADES: trade}))
    f.add_feed(Bithumb(symbols=['BTC-KRW'], channels=[TRADES], callbacks={TRADES: trade}))
    f.add_feed(Bitmex(timeout=5000, symbols=Bitmex.symbols(), channels=[LIQUIDATIONS], callbacks={LIQUIDATIONS: liquidations, OPEN_INTEREST: oi, FUNDING: funding}))
    f.add_feed(Bitstamp(channels=[L2_BOOK, TRADES], symbols=['BTC-USD'], callbacks={L2_BOOK: book, TRADES: trade}))
    f.add_feed(Bittrex(subscription={L2_BOOK: ['BTC-USDT'], CANDLES: ['BTC-USDT', 'ETH-USDT'], TRADES: ['ETH-USDT', 'BTC-USDT'], TICKER: ['ETH-USDT']}, callbacks={CANDLES: candle_callback, L2_BOOK: book, TICKER: ticker, TRADES: trade}))
    f.add_feed(BLOCKCHAIN, subscription={L2_BOOK: ['BTC-USD'], TRADES: Blockchain.symbols()}, callbacks={L2_BOOK: book, TRADES: trade})
    f.add_feed(Bybit(symbols=['BTC-USDT-PERP', 'BTC-USD-PERP'], channels=[INDEX, FUNDING, OPEN_INTEREST], callbacks={OPEN_INTEREST: oi, INDEX: index, FUNDING: funding}))
    f.add_feed(Bybit(candle_closed_only=True, symbols=['BTC-USDT-PERP', 'BTC-USD-PERP'], channels=[CANDLES, TRADES, L2_BOOK], callbacks={CANDLES: candle_callback, TRADES: trade, L2_BOOK: book}))
    f.add_feed(Coinbase(subscription={L2_BOOK: ['BTC-USD'], TRADES: ['BTC-USD'], TICKER: ['BTC-USD']}, callbacks={TRADES: trade, L2_BOOK: book, TICKER: ticker}))
    f.add_feed(Coinbase(subscription={L3_BOOK: ['LTC-USD']}, callbacks={L3_BOOK: book}))
    f.add_feed(Deribit(symbols=['BTC-USD-PERP'], channels=[L2_BOOK, TRADES, TICKER, FUNDING, OPEN_INTEREST, LIQUIDATIONS], callbacks={TRADES: trade, L2_BOOK: book, TICKER: ticker, OPEN_INTEREST: oi, FUNDING: funding, LIQUIDATIONS: liquidations}))
    f.add_feed(dYdX(symbols=dYdX.symbols(), channels=[L2_BOOK, TRADES], callbacks={TRADES: trade, L2_BOOK: book}))
    f.add_feed(FTX(checksum_validation=True, symbols=['ALGO-USD-PERP'], channels=[TICKER, TRADES, L2_BOOK, LIQUIDATIONS, OPEN_INTEREST, FUNDING], callbacks={TICKER: ticker, TRADES: trade, OPEN_INTEREST: oi, FUNDING: funding, LIQUIDATIONS: liquidations, L2_BOOK: book}))
    f.add_feed(Gateio(symbols=['BTC-USDT', 'ETH-USDT'], channels=[L2_BOOK, CANDLES, TRADES, TICKER], callbacks={CANDLES: candle_callback, L2_BOOK: book, TRADES: trade, TICKER: ticker}))
    f.add_feed(GEMINI, subscription={L2_BOOK: ['BTC-USD', 'ETH-USD'], TRADES: ['ETH-USD', 'BTC-USD']}, callbacks={TRADES: trade, L2_BOOK: book})
    f.add_feed(HitBTC(channels=[TRADES], symbols=['BTC-USDT'], callbacks={TRADES: trade}))
    f.add_feed(Huobi(symbols=['BTC-USDT'], channels=[CANDLES, TRADES, L2_BOOK], callbacks={TRADES: trade, L2_BOOK: book, CANDLES: candle_callback}))
    f.add_feed(HuobiDM(subscription={L2_BOOK: HuobiDM.symbols()[:2], TRADES: HuobiDM.symbols()[:10]}, callbacks={TRADES: trade, L2_BOOK: book}))
    pairs = ['BTC-USD-PERP', 'ETH-USD-PERP', 'EOS-USD-PERP', 'BCH-USD-PERP', 'BSV-USD-PERP', 'LTC-USD-PERP']
    f.add_feed(HuobiSwap(symbols=pairs, channels=[TRADES, L2_BOOK, FUNDING], callbacks={FUNDING: funding, TRADES: trade, L2_BOOK: book}))
    f.add_feed(KrakenFutures(symbols=KrakenFutures.symbols(), channels=[L2_BOOK, TICKER, TRADES, OPEN_INTEREST, FUNDING], callbacks={L2_BOOK: book, FUNDING: funding, OPEN_INTEREST: oi, TRADES: trade, TICKER: ticker}))
    f.add_feed(Kraken(config='config.yaml', checksum_validation=True, subscription={L2_BOOK: ['BTC-USD'], TRADES: ['BTC-USD'], CANDLES: ['BTC-USD'], TICKER: ['ETH-USD']}, callbacks={L2_BOOK: book, CANDLES: candle_callback, TRADES: trade, TICKER: ticker}))
    f.add_feed(KuCoin(symbols=['BTC-USDT', 'ETH-USDT'], channels=[TICKER, TRADES, CANDLES], callbacks={CANDLES: candle_callback, TICKER: ticker, TRADES: trade}))
    f.add_feed(OKX(checksum_validation=True, symbols=['BTC-USDT-PERP'], channels=[TRADES, TICKER, FUNDING, OPEN_INTEREST, LIQUIDATIONS, L2_BOOK], callbacks={L2_BOOK: book, TICKER: ticker, LIQUIDATIONS: liquidations, FUNDING: funding, OPEN_INTEREST: oi, TRADES: trade}))
    f.add_feed(OKCoin(checksum_validation=True, symbols=['BTC-USD'], channels=[TRADES, TICKER, L2_BOOK], callbacks={L2_BOOK: book, TICKER: ticker, TRADES: trade}))
    f.add_feed(Phemex(symbols=[Symbol('BTC', 'USD', type=PERPETUAL)], channels=[L2_BOOK, CANDLES, TRADES], callbacks={TRADES: trade, L2_BOOK: book, CANDLES: candle_callback}))
    f.add_feed(Poloniex(symbols=['BTC-USDT'], channels=[TICKER, TRADES], callbacks={TICKER: ticker, TRADES: trade}))
    f.add_feed(Poloniex(subscription={TRADES: ['DOGE-BTC'], L2_BOOK: ['LTC-BTC']}, callbacks={TRADES: trade, L2_BOOK: book}))
    f.add_feed(Probit(subscription={TRADES: ['BTC-USDT'], L2_BOOK: ['BTC-USDT']}, callbacks={TRADES: trade, L2_BOOK: book}))
    f.add_feed(Upbit(subscription={TRADES: ['BTC-USDT'], L2_BOOK: ['BTC-USDT']}, callbacks={TRADES: trade, L2_BOOK: book}))
    f.add_feed(CryptoDotCom(symbols=['BTC-USDT'], channels=[L2_BOOK, TICKER, CANDLES, TRADES], callbacks={TRADES: trade, CANDLES: candle_callback, TICKER: ticker, L2_BOOK: book}))
    f.add_feed(Delta(symbols=['BTC-USDT', 'BTC-USDT-PERP'], channels=[L2_BOOK, TRADES, CANDLES], callbacks={TRADES: trade, CANDLES: candle_callback, L2_BOOK: book}))
    f.add_feed(BitDotCom(config="config.yaml", sandbox=True, symbols=['BTC-USDT', 'BTC-USD-PERP'], channels=[TICKER, TRADES, L2_BOOK], callbacks={TRADES: trade, L2_BOOK: book, TICKER: ticker}))
    f.add_feed(Bitget(config='config.yaml', symbols=['BTC-USD-PERP', 'BTC-USDT-PERP', 'BTC-USDT'], channels=[L2_BOOK, TICKER, CANDLES, TRADES], callbacks={CANDLES: candle_callback, TRADES: trade, L2_BOOK: book, TICKER: ticker}))
    f.add_feed(IndependentReserve(symbols=['BTC-USD'], channels=[L3_BOOK, TRADES], callbacks={TRADES: trade, L3_BOOK: book}))

    f.run()
def main():
    fh = FeedHandler()
    # pairs_list = ['BTC-USDT', 'ETH-USDT', 'XRP-USDT', 'LTC-USDT', 'LINK-USDT', 'TRX-USDT', 'DOT-USDT', 'ADA-USDT', 'EOS-USDT',
    #  'BCH-USDT', 'BSV-USDT', 'YFI-USDT', 'UNI-USDT', 'FIL-USDT', 'YFII-USDT', 'SNX-USDT', 'BNB-USDT', 'ZEC-USDT',
    #  'DASH-USDT', 'ETC-USDT', 'THETA-USDT', 'KSM-USDT', 'ATOM-USDT', 'AAVE-USDT', 'XLM-USDT', 'SUSHI-USDT', 'CRV-USDT',
    #  'WAVES-USDT', 'KAVA-USDT', 'RSR-USDT', 'NEO-USDT', 'XMR-USDT', 'ALGO-USDT', 'VET-USDT', 'XTZ-USDT', 'COMP-USDT',
    #  'OMG-USDT', 'XEM-USDT', 'ONT-USDT', 'ZIL-USDT', 'AVAX-USDT', 'BAND-USDT', 'GRT-USDT', '1INCH-USDT', 'DOGE-USDT',
    #  'MATIC-USDT', 'LRC-USDT', 'SOL-USDT', 'IOTA-USDT']

    # pairs_list = get_trade_symbol_list()
    pairs_list = binance_futures_pairs()
    print(pairs_list)

    # fh.add_feed(OKEx(pairs=['EOS-USD-SWAP'], channels=[TRADES_SWAP, L2_BOOK_SWAP, OPEN_INTEREST, FUNDING], callbacks={FUNDING: funding, OPEN_INTEREST: open_interest, TRADES: TradeCallback(trade), L2_BOOK: BookCallback(book), TICKER_SWAP:TickerCallback(ticker)}))
    #fh.add_feed(OKEx(pairs=['EOS-USD-SWAP'], channels=[ TRADES_SWAP,L2_BOOK_SWAP], callbacks={FUNDING: funding, OPEN_INTEREST: open_interest, TRADES_SWAP: TradeCallback(trade), L2_BOOK: BookCallback(book)}))
    # fh.add_feed(HuobiDM(pairs=['BTC'], channels=[ TRADES], callbacks={FUNDING: funding, OPEN_INTEREST: open_interest, TRADES_SWAP: TradeCallback(trade), L2_BOOK: BookCallback(book)}))
    # fh.add_feed(HuobiDM(pairs=['BTC_CQ'], channels=[ TRADES,L2_BOOK], callbacks={FUNDING: funding, OPEN_INTEREST: open_interest, TRADES: TradeCallback(trade), L2_BOOK: BookCallback(book)}))

    # fh.add_feed(HuobiDM(max_depth=1, pairs=['BTC_CQ'], channels=[ L2_BOOK], callbacks={ L2_BOOK: BookCallback(book)}))

    fh.add_feed(
        BinanceFutures(max_depth=1,
                       pairs=pairs_list,
                       channels=[L2_BOOK],
                       callbacks={L2_BOOK: BookCallback(book)}))
    # fh.add_feed(BinanceFutures(max_depth=1, pairs=pairs_list, channels=[ TRADES], callbacks={ TRADES: TradeCallback(trade)}))
    # fh.add_feed(HuobiSwap(pairs=['BTC-USDT'], channels=[ L2_BOOK], callbacks={ L2_BOOK: BookCallback(book)}))

    fh.run()
Exemplo n.º 7
0
def main():
    f = FeedHandler()
    f.add_feed(
        FTX(pairs=ftx_pairs(),
            channels=[OPEN_INTEREST, LIQUIDATIONS],
            callbacks={
                OPEN_INTEREST: OpenInterestCallback(oi),
                LIQUIDATIONS: LiquidationCallback(liquidations)
            }))

    f.add_feed(
        BinanceFutures(pairs=binance_futures_pairs(),
                       channels=[OPEN_INTEREST, LIQUIDATIONS],
                       callbacks={
                           OPEN_INTEREST: OpenInterestCallback(oi),
                           LIQUIDATIONS: LiquidationCallback(liquidations)
                       }))

    f.add_feed(
        Deribit(pairs=['BTC-PERPETUAL'],
                channels=[OPEN_INTEREST, LIQUIDATIONS],
                callbacks={
                    OPEN_INTEREST: OpenInterestCallback(oi),
                    LIQUIDATIONS: LiquidationCallback(liquidations)
                }))
    f.run()
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()
Exemplo n.º 9
0
def main():
    f = FeedHandler(raw_message_capture=AsyncFileCallback('./'))
    f.add_feed(
        Coinbase(symbols=['BTC-USD'], channels=[L2_BOOK, TICKER, TRADES]))
    f.add_feed(
        BinanceFutures(symbols=['DOT-USDT', 'BTC-USDT'],
                       channels=[OPEN_INTEREST, L2_BOOK]))

    f.run()
Exemplo n.º 10
0
def main():
    f = FeedHandler(raw_data_collection=AsyncFileCallback("./"))
    f.add_feed(
        Coinbase(symbols=['BTC-USD'], channels=[L2_BOOK, TICKER, TRADES]))
    f.add_feed(
        BinanceFutures(symbols=['DOT-USDT', 'BTC-USDT'],
                       channels=[OPEN_INTEREST, L2_BOOK]))

    f.run()
Exemplo n.º 11
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()
Exemplo n.º 12
0
def main():
    fh = FeedHandler()

    # Add futures contracts
    pairs0 = ["BTC-USDT", "EOS-USDT"]
    pairs1 = ["BTC_CQ", "EOS_CQ"]
    pairs2 = ["BTC-USD", "EOS-USD"]
    pairs3 = OKEx.get_active_symbols()[:5]
    pair4 = ['XRP-USD-210326', 'LTC-USD-201225']
    pair5 = list(binance_pairs().keys())[:5]
    pair6 = list(binance_futures_pairs().values())[:5]
    pair7 = list(okcoin_pairs().keys())[:5]
    #print(pair6)
    # fh.add_feed(HuobiR(pairs=pairs0, channels=[KLINE], callbacks={KLINE: kline}))
    # fh.add_feed(HuobiDMR(pairs=pairs1, channels=[KLINE], callbacks={KLINE: kline}))
    # fh.add_feed(HuobiSwapR(pairs=pairs2, channels=[KLINE], callbacks={KLINE: kline}))
    # fh.add_feed(BinanceFutures(pairs=["BTCUSDT"], channels=[KLINE], callbacks={KLINE: kline}))
    print(pair6)
    fh.add_feed(
        BinanceFutures(pairs=pair6, channels=[KLINE], callbacks={KLINE:
                                                                 kline}))
    # fh.add_feed(OKCoin(pairs=pair7, channels=[KLINE], callbacks={KLINE: kline}))
    # fh.add_feed(OKEx(pairs=pairs3, channels=[KLINE], callbacks={KLINE: kline}))
    fh.run()
Exemplo n.º 13
0
import asyncio
from datetime import datetime
from collections import defaultdict
from multiprocessing import Process
from yapic import json

from cryptofeed import FeedHandler
from cryptofeed.backends.zmq import FundingZMQ
from cryptofeed.defines import L2_BOOK, FUNDING, PERPETUAL
from cryptofeed.exchanges import BinanceFutures, BinanceDelivery

binance_delivery_data_info = BinanceDelivery.info()
binance_futures_data_info = BinanceFutures.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)
            res[msg['feed']][msg['symbol']] = msg['rate']
            d = res[msg['feed']]
            res[msg['feed']] = dict(
Exemplo n.º 14
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()
Exemplo n.º 15
0
'''
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):
Exemplo n.º 16
0
class BinanceFutures(API):
    ID = BINANCE_FUTURES
    api = "https://fapi.binance.com/fapi/v1/"
    info = BinanceFutures()

    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'] 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
Exemplo n.º 17
0
    #print(huobi[market])
\
"""
bcontracts = []

pairs = requests.get('https://dapi.binance.com/dapi/v1/exchangeInfo').json()
for symbol in pairs['symbols']:
    split = len(symbol['baseAsset'])
    #if 'BTC' in symbol['symbol']:
    #print(symbol['symbol'])
    normalized = symbol['symbol'][:split] + '-' + symbol['symbol'][split:]
    bcontracts.append(normalized)
config = {TICKER: bcontracts}
fh.add_feed(
    BinanceFutures(config=config, callbacks={TICKER: TickerCallback(ticker)}))
"""
ofuts = []
oswaps = []
swaps = requests.get('https://www.okex.com/api/swap/v3/instruments').json()

futures = requests.get('https://www.okex.com/api/futures/v3/instruments').json()
for s in swaps:
    oswaps.append(s['instrument_id'])
for f in futures:
    ofuts.append(f['instrument_id'])
config = {TICKER_OKS: oswaps
,TICKER_FUTURES: ofuts}
fh.add_feed(OKEx(config=config, callbacks={TICKER_FUTURES: TickerCallback(ticker), TICKER_OKS: TickerCallback(ticker)}))

#print(expis)