Ejemplo n.º 1
0
async def run():
    api_key = os.environ['APIKEY']
    sec_key = os.environ['SECKEY']

    client = CryptoXLib.create_binance_client(api_key, sec_key)

    print("BLVT symbol info:")
    await client.get_blvt_info()

    print("Subscribe BTCUP:")
    try:
        await client.blvt_subscribe("BTCUP", "500000000")
    except Exception as e:
        print(e)

    print("Subscription history:")
    await client.get_blvt_subscribtion_record()

    print("Redeem BTCUP:")
    try:
        await client.blvt_redeem("BTCUP", "500000000")
    except Exception as e:
        print(e)

    print("Redemption history:")
    await client.get_blvt_redemption_record()

    print("BLVT user limits:")
    await client.get_blvt_user_info()

    await client.close()
Ejemplo n.º 2
0
async def run():
    api_key = os.environ['APIKEY']
    sec_key = os.environ['SECKEY']

    client = CryptoXLib.create_binance_client(api_key, sec_key)

    # Bundle several subscriptions into a single websocket
    client.compose_subscriptions([
        OrderBookTickerSubscription(callbacks=[orderbook_ticker_update]),
        OrderBookSymbolTickerSubscription(pair=Pair("BTC", "USDT"),
                                          callbacks=[orderbook_ticker_update]),
        TradeSubscription(pair=Pair('ETH', 'BTC'), callbacks=[trade_update]),
        CandlestickSubscription(Pair('BTC', 'USDT'),
                                Interval.I_1MIN,
                                callbacks=[candlestick_update])
    ])

    # Bundle another subscriptions into a separate websocket
    client.compose_subscriptions(
        [AccountSubscription(callbacks=[account_update])])

    # Execute all websockets asynchronously
    await client.start_websockets()

    await client.close()
async def run():
    api_key = os.environ['APIKEY']
    sec_key = os.environ['SECKEY']

    client = CryptoXLib.create_binance_client(api_key, sec_key)

    print("All margin assets:")
    await client.get_margin_all_assets()

    print("Margin pair:")
    await client.get_margin_pair(Pair('BTC', 'USDT'))

    print("Margin price index:")
    await client.get_margin_price_index(Pair('BTC', 'USDT'))

    print("Margin account balance:")
    await client.get_margin_account()

    await client.close()
Ejemplo n.º 4
0
async def run():
    api_key = os.environ['APIKEY']
    sec_key = os.environ['SECKEY']

    client = CryptoXLib.create_binance_client(api_key, sec_key)

    print('Swap pools:')
    await client.get_bswap_pools()

    print('Swap liquidity:')
    await client.get_bswap_liquidity()

    print('Add liquidity:')
    try:
        await client.bswap_add_liquidity(0, 'BTC', '10000000')
    except Exception as e:
        print(e)

    print('Remove liquidity:')
    try:
        await client.bswap_remove_liquidity(
            0, 'BTC', '10000000', type=enums.LiquidityRemovalType.COMBINATION)
    except Exception as e:
        print(e)

    print('Liquidity history:')
    await client.get_bswap_liquidity_operations()

    print('Request quote:')
    await client.get_bswap_quote(Pair('BTC', 'USDT'), '1000')

    print('Swap:')
    try:
        await client.bswap_swap(Pair('BTC', 'USDT'), '100000000000')
    except Exception as e:
        print(e)

    print('Swap hisotry:')
    await client.get_bswap_swap_history()

    await client.close()
Ejemplo n.º 5
0
async def run():
    api_key = os.environ['APIKEY']
    sec_key = os.environ['SECKEY']

    client = CryptoXLib.create_binance_client(api_key, sec_key)

    # initialize three independent websockets
    sub.subscription_set_ids.append(
        client.compose_subscriptions(sub.subscriptions[0]))
    sub.subscription_set_ids.append(
        client.compose_subscriptions(sub.subscriptions[1]))
    sub.subscription_set_ids.append(
        client.compose_subscriptions(sub.subscriptions[2]))

    try:
        await asyncio.gather(*[client.start_websockets(), main_loop(client)])
    except Exception as e:
        print(f"Out: {e}")

    await client.close()
    print("Exiting.")
Ejemplo n.º 6
0
async def run():
    api_key = os.environ['APIKEY']
    sec_key = os.environ['SECKEY']

    client = CryptoXLib.create_binance_client(api_key, sec_key)

    # Bundle several subscriptions into a single websocket
    client.compose_subscriptions([
        CandlestickSubscription(Pair('BTC', 'USDT'),
                                Interval.I_1MIN,
                                callbacks=[candlestick_update])
    ])

    # Bundle another subscriptions into a separate websocket
    client.compose_subscriptions([
        # uncomment if isolated margin account is setup
        #AccountIsolatedMarginSubscription(pair = Pair('BTC', 'USDT'), callbacks = [account_update]),
        AccountCrossMarginSubscription(callbacks=[account_update])
    ])

    # Execute all websockets asynchronously
    await client.start_websockets()

    await client.close()
Ejemplo n.º 7
0
 async def init_test(self):
     self.client = CryptoXLib.create_binance_client(api_key, sec_key)
async def run():
    api_key = os.environ['APIKEY']
    sec_key = os.environ['SECKEY']

    client = CryptoXLib.create_binance_client(api_key, sec_key)

    print("Ping:")
    await client.ping()

    print("Server time:")
    await client.get_time()

    print("Exchange info:")
    await client.get_exchange_info()

    print("Order book:")
    await client.get_orderbook(pair=Pair('ETH', 'BTC'),
                               limit=enums.DepthLimit.L_5)

    print("Trades:")
    await client.get_trades(pair=Pair('ETH', 'BTC'), limit=5)

    print("Historical trades:")
    await client.get_historical_trades(pair=Pair('ETH', 'BTC'), limit=5)

    print("Aggregate trades:")
    await client.get_aggregate_trades(pair=Pair('ETH', 'BTC'), limit=5)

    print("Candelsticks:")
    await client.get_candelsticks(pair=Pair('ETH', 'BTC'),
                                  interval=enums.CandelstickInterval.I_1D,
                                  limit=5)

    print("Average price:")
    await client.get_average_price(pair=Pair('ETH', 'BTC'))

    print("24hour price ticker:")
    await client.get_24h_price_ticker(pair=Pair('ETH', 'BTC'))

    print("Price ticker:")
    await client.get_price_ticker(pair=Pair('ETH', 'BTC'))

    print("Best order book ticker:")
    await client.get_best_orderbook_ticker(pair=Pair('ETH', 'BTC'))

    print("Create test market order:")
    await client.create_test_order(
        Pair("ETH", "BTC"),
        side=enums.OrderSide.BUY,
        type=enums.OrderType.MARKET,
        quantity="1",
        new_order_response_type=enums.OrderResponseType.FULL)

    print("Create limit order:")
    try:
        await client.create_order(
            Pair("ETH", "BTC"),
            side=enums.OrderSide.BUY,
            type=enums.OrderType.LIMIT,
            quantity="1",
            price="0",
            time_in_force=enums.TimeInForce.GOOD_TILL_CANCELLED,
            new_order_response_type=enums.OrderResponseType.FULL)
    except BinanceException as e:
        print(e)

    print("Cancel order:")
    try:
        await client.cancel_order(pair=Pair('ETH', 'BTC'), order_id="1")
    except BinanceException as e:
        print(e)

    print("Get order:")
    try:
        await client.get_order(pair=Pair('ETH', 'BTC'), order_id=1)
    except BinanceException as e:
        print(e)

    print("Get open orders:")
    await client.get_open_orders(pair=Pair('ETH', 'BTC'))

    print("Get all orders:")
    await client.get_all_orders(pair=Pair('ETH', 'BTC'))

    print("Create OCO order:")
    try:
        await client.create_oco_order(
            Pair("ETH", "BTC"),
            side=enums.OrderSide.BUY,
            quantity="1",
            price="0",
            stop_price="0",
            new_order_response_type=enums.OrderResponseType.FULL)
    except BinanceException as e:
        print(e)

    print("Cancel OCO order:")
    try:
        await client.cancel_oco_order(pair=Pair('ETH', 'BTC'),
                                      order_list_id="1")
    except BinanceException as e:
        print(e)

    print("Get OCO order:")
    try:
        await client.get_oco_order(order_list_id=1)
    except BinanceException as e:
        print(e)

    print("Get open OCO orders:")
    await client.get_open_oco_orders()

    print("Get all OCO orders:")
    await client.get_all_oco_orders()

    print("Account:")
    await client.get_account(recv_window_ms=5000)

    print("Account trades:")
    await client.get_account_trades(pair=Pair('ETH', 'BTC'))

    await client.close()
Ejemplo n.º 9
0
async def run():
    cl = CryptoXLib.create_binance_client(os.environ['BINANCEAPIKEY'], os.environ['BINANCESECKEY'])

    coins = set()

    # download a list of coins supported by binance, the coins will be used as an input for a download from coin gecko
    exchange_info = (await cl.get_exchange_info())['response']
    for symbol in exchange_info['symbols']:
        coins.add(symbol['baseAsset'].upper())

    print(f"Number of coins: {len(coins)}")
    print(f"Coins: {sorted(coins)}")

    cg = CoinGeckoAPI()

    # maps symbol to coin gecko id
    coin_ids = {}
    for coin in cg.get_coins_list():
        if coin['symbol'].upper() in coins:
            # filter major margin coins, stable coins and exchange coins
            if '3x-' not in coin['id'] and \
                    'USDC' not in coin['symbol'].upper() and \
                    'USDS' not in coin['symbol'].upper() and \
                    'USDT' not in coin['symbol'].upper() and \
                    'TUSD' not in coin['symbol'].upper() and \
                    'BGBP' not in coin['symbol'].upper() and \
                    'BUSD' not in coin['symbol'].upper() and \
                    'PAX' not in coin['symbol'].upper() and \
                    'BNB' not in coin['symbol'].upper():
                coin_ids[coin['symbol'].upper()] = coin['id']

    # output is of format {'YYYY-MM-DD': {'coin': {'price': ..., 'cap': ..., 'volume': ...}, ...}
    output = defaultdict(defaultdict)

    try:
        for coin in sorted(coin_ids.keys()):
            coin_id = coin_ids[coin]
            if STARTING_COIN is None or coin >= STARTING_COIN:
                print(f"Downloading {coin} ({coin_id})")

                # attempt to download the data max. 3 times (e.g. because of failures due to too many requests)
                for i in range(0, 3):
                    try:
                        data = cg.get_coin_market_chart_range_by_id(coin_id, 'usd', START_DT.timestamp(), END_DT.timestamp())
                        break
                    except Exception as e:
                        if i == 2:
                            raise e
                        else:
                            print(e)
                            print(f"Retrying after 30sec")
                            time.sleep(30)

                for (price, cap, volume) in reversed(list(zip(data['prices'], data['market_caps'], data['total_volumes']))):
                    date = datetime.datetime.fromtimestamp(price[0] / 1000).strftime("%Y-%m-%d")
                    if coin not in output[date]:
                        output[date][coin] = {}
                    output[date][coin]['price'] = price[1]
                    output[date][coin]['cap'] = cap[1]
                    output[date][coin]['volume'] = volume[1]
    except Exception as e:
        print(e)

    # dump output into a file
    output_file_name = "data.json" if STARTING_COIN is None else f"{STARTING_COIN}.json"
    with open(output_file_name, 'w') as file:
        file.write(json.dumps(output))

    await cl.close()
Ejemplo n.º 10
0
import asyncio
from pprint import pprint
import random
from datetime import datetime

import requests

from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.Pair import Pair
from cryptoxlib.version_conversions import async_run
from cryptoxlib.clients.binance.BinanceWebsocket import TradeSubscription, AggregateTradeSubscription

from cryptoxlib.clients.binance.BinanceWebsocket import BinanceWebsocket
BinanceWebsocket.WEBSOCKET_URI = "wss://fstream.binance.com/"

client = CryptoXLib.create_binance_client(None, None)
queue = asyncio.Queue()

MIN_QTY = 0
MIN_QTY_VOICE = 0

# -- util


def format_time(s):
    try:
        return datetime.strptime(s, "%Y-%m-%dT%H:%M:%S.%fZ").timestamp()
    except ValueError:
        return datetime.strptime(s, "%Y-%m-%dT%H:%M:%SZ").timestamp()