예제 #1
0
class TestBinanceApiEndPoints(unittest.TestCase):

    def setUp(self):
        self.client = BinanceAPI(API_KEY,API_SECRET)

    def test_a_get_current_server_time(self):
        """ Test that we can get the current time. """
        time = self.client.time()
        self.assertTrue(time.get("serverTime", None) is not None)
        logger.info("Able to get current server time.")
    
    def test_b_get_all_prices(self):
        """ Test that we can get all prices """
        prices = self.client.allPrices()
        self.assertTrue(len(prices) > 0)
        logger.info("We got prices.")
        for each in prices: 
            # assert we have {"symbol" : "<symbol>", "price":<price>}.
            self.assertTrue("price" in each and "symbol" in each)
            # assert that each price can be of float type / for calculations.
            self.assertTrue(isinstance(float(each["price"]), float))
        logger.info("We can get all prices listed with this endpoint.")
    
    def test_c_get_all_orders(self):
        """ Test that the we get an exception if there are no orders for given <symbol> """
        with self.assertRaises(excepts.MalformedRequest):
            self.client.allOrders('ETHBTC')
        logger.info("We have no orders from ETHBTC so the API raises MalformedRequest.")
    
    def test_d_get_time_stats(self):
        pass
예제 #2
0
async def quote_qty_from_usd(client: aiohttp.ClientSession, api: BinanceAPI,
                             usd_symbol: dict) -> float:
    """ get quote quantity by its value in USD
        <usd_symbol>: a <quote>/BUSD or <quote>/USDT symbol """
    if api.env.usd_value < 0:
        raise CException('USD quote value cannot be negative')
    if usd_symbol == {}:
        raise CException('No BUSD/USDT trade symbol found, aborting!')
    api.set_pair(usd_symbol)
    return await api.last_price(client)
예제 #3
0
def public_api():

    client = BinanceAPI()

    print(client.ping())

    print(client.time())

    print(client.depth('BTCUSDT', limit=10))

    print(client.aggTrades('ETHBTC'))

    print(client.klines('BNBBTC', '1h', limit=10))

    print(client.stats24hr('ETHUSDT'))

    print(client.allPrices())

    print(client.allBookTickers())
예제 #4
0
async def quote_symbols(api: BinanceAPI):
    """ Get all */quote and quote/BUSD symbols """
    async with aiohttp.ClientSession() as client:
        exinfo, tickers = await asyncio.gather(
            api.exchange_info(client), api.ticker_24h(client, single=False))
    dtickers = {val['symbol']: val for val in tickers}
    qsymbols = {}
    for symbol in exinfo['symbols']:
        if symbol['status'] != 'TRADING' or \
           not symbol['isSpotTradingAllowed'] or \
           not symbol['quoteOrderQtyMarketAllowed']:
            continue
        # inject ticker data inside a symbol
        symbol['ticker'] = dtickers[symbol['symbol']]
        if symbol['quoteAsset'] == api.env.qcoin:
            qsymbols[symbol['baseAsset']] = symbol
        elif symbol['quoteAsset'] == 'BUSD' and \
             symbol['baseAsset'] == api.env.qcoin:
            qsymbols[api.env.qcoin] = symbol
    return qsymbols
예제 #5
0
async def buy_from_source(client: aiohttp.ClientSession, api: BinanceAPI,
                          src_symbols: dict, balances: dict, bqty: float):
    """ Buy <val> of quote coin """
    for asset, (free, _) in balances.items():
        if free == 0 or asset not in src_symbols:
            continue
        symbol = src_symbols[asset]
        api.set_pair(symbol)
        avg, last = await asyncio.gather(api.avg_price(client),
                                         api.last_price(client))
        qqty = bqty * last
        if free < qqty:
            continue
        low, high = api.qty_bound(avg, True)
        bqty = max(low, bqty)
        qqty = bqty * last
        if free < qqty or bqty > high:
            continue
        succ, qty, _ = await api.buy_coin_market(client, qqty)
        if not succ:
            continue
        return qty
    raise CException('Failed to buy quote coin')
예제 #6
0
async def main():
    """ Entrypoint """
    klen = 241  # 4h remanence
    thresh = 5, 900  # 5% positive price fluctuation, 900% positive volume fluctuation
    min_vol = 0.1  # do not alert under 0.1 executed quote volume (tuned for BTC)
    min_chg = 0.1  # minimum acceptable price change, regardless of volume
    limits = KlineLimits(*thresh, min_vol, min_chg)

    env = Environment('.env')
    api = BinanceAPI(env)
    wapi = BinanceWSAPI(env)

    # fetch symbols to track
    qsymbols = await quote_symbols(api)
    qvalues = qsymbols.values()
    symb_names = [symb['symbol'] for symb in qvalues]
    qlen = len(qvalues)
    CColors.iprint(
        f'DawnSpotter online.\nTracking {qlen} pairs: {", ".join(symb_names)}')

    # prepare the kline data structure
    manager = KlineManager(qvalues, klen, limits)
    # Pull historical data from the API
    maxrun = 1200 // (qlen + 41)
    print(
        f'Pulling historical data from REST API, do not rerun this more than {maxrun}x/min!'
    )
    async with aiohttp.ClientSession() as client:
        coros = (api.last_klines(client, '1m', klen, symbol)
                 for symbol in qvalues)
        preconf = await asyncio.gather(*coros)
    manager.fill(zip(symb_names, preconf))

    # read trade data from WS
    print('Updating data from WebSockets...')
    async for tdata in wapi.klines_bulk(symb_names, '1m'):
        manager.update(tdata['data']['k'])
예제 #7
0
def private_api():

    client = BinanceAPI(API_KEY, API_SECRET)
    # or
    # client = BinanceAPI()
    # client.set_api(API_KEY, API_SECRET)

    print(client.openOrders('KNCETH'))

    print(client.allOrders('KNCETH'))

    print(client.account())

    print(client.myTrades('KNCETH'))

    print(client.newLimitBuyOrder('BTCUSDT', quantity=1.0, price=5203.0))

    print(client.queryOrder('BNBETH', orderId=387643))

    print(client.deleteOrder('BNBETH', orderId=387643))
예제 #8
0
def main():
    """ Entrypoint """
    env = Environment('.env')
    api = BinanceAPI(env)
    wapi = BinanceWSAPI(env)

    if env.override:
        print('Want to skip prompts? Set PROMPT_OVERRIDE to 0!')

    loop = asyncio.get_event_loop()
    # initialize Market Manager (prepare everything)
    manager = MarketManager(api, wapi, *loop.run_until_complete(setup(api)))

    # Start coin name listeners: stdin and HTTP
    http_thr = Thread(target=coin_from_http, args=(manager, ), daemon=True)
    stdin_thr = Thread(target=coin_from_stdin, args=(manager, ), daemon=True)
    print(
        f'Starting HTTP listener at {env["SERVER_HOST"]}:{env["SERVER_PORT"]}')
    http_thr.start()
    stdin_thr.start()

    if env.bailout:
        print(
            'Bailout enabled: once trading starts, press Ctrl+C to sell immediately'
        )

    # wait for coin lock
    try:
        with manager.cvar:
            manager.cvar.wait_for(lambda: manager.ready)
    except KeyboardInterrupt:
        return

    # start trading
    try:
        loop.run_until_complete(manager.start())
    except KeyboardInterrupt:
        try:
            loop.run_until_complete(manager.bailout())
        except CException as exc:
            print(str(exc))
예제 #9
0
import json
import asyncio
from api import BinanceAPI

with open("logs.json") as file:
    data = json.load(file)
    api_key = data["KEY"]
    api_secret = data["SECRET"]

client = BinanceAPI(api_key, api_secret)


def extract_balance(json_data):

    for key in json_data.keys():

        try:
            return float(json_data[key])
        except KeyError:
            return 0


def get_balance():
    res = client.get_account_status()
    final_balance = []

    for coin in res["balances"]:
        if float(coin["free"]) > 0.0001:
            final_balance.append({"%s" % coin["asset"]: coin["free"]})

    with open("results.json", "w") as outfile:
예제 #10
0
from api import BinanceAPI
client = BinanceAPI(
    '8SqwIw1lYhaxQZa9LSCUx2wjN1GqguDDAuewtKUCKmUlO4uwXoQ3ylz0Efs',
    '5Phlc0ldADa6rQYJANguTIe1mSekiSTN2SiaowBPcs2gXi3wsgQ2TCQssmo4B')

ping = client.time()
print(ping)
예제 #11
0
 def setUp(self):
     self.client = BinanceAPI(API_KEY,API_SECRET)
예제 #12
0
######   Inspired by the Turtle Traders from the 1980s
######   More information at http://www.tradingblox.com/originalturtles/
######   Testing suggests this strategy does NOT work well with crypto
######   This is in the middle of a refactor



from api import BinanceAPI
client = BinanceAPI('[API key]','[API secret]')
# import time
# from data_checks import Data_checks
# import pandas
# from datetime import datetime
# import matplotlib.pyplot as plt
import datetime
from excepts import MalformedRequest, StatusUnknown, InternalError
from requests.exceptions import ConnectionError
from http.client import RemoteDisconnected
from http.client import HTTPException
from urllib3.exceptions import ProtocolError


class turtle:
    def __init__(self):
        self.pair = ""
        self.pip_sats = None
        self.price_mult = 1
        self.interval = None
        self.capital = None
        self.limit = None
        self.exit_trigger = None
예제 #13
0
##### Executer for mult_arbit

from api import BinanceAPI
client = BinanceAPI('[API key]', '[API secret]')
client.set_offset()
import time
from data_checks import Data_checks
from price_monitor import mon
from mult_arbit import Trades
from log import log_c

dc = Data_checks()
mn = mon()
lg = log_c()
tr = Trades()
ready = False

t = str(time.time())[:10]
f = open('log' + t + '.txt', 'w')
f.write('log file for run starting at time ' + str(time.time()))
f.close()
f_name = 'log' + t + '.txt'

lg.set_file(f_name)
mn.setfile(f_name)
dc.setfile(f_name)
tr.setfile(f_name)

while not ready:
    a = tr.get_open_ords('XLMBNB')
    b = tr.get_open_ords('BNBETH')
예제 #14
0
async def setup(api: BinanceAPI) -> (dict, float):
    """ main parameter setup
        return exchange info and quote amount to sell """
    env = api.env

    def set_stdin(prompt: str, default):
        if not env.override:
            return default
        ret = input(prompt)
        return ret if ret else default

    prompt = f'Enter quote coin symbol (coin to trade for) [default: {env.qcoin}]: '
    env.qcoin = set_stdin(prompt, env.qcoin).upper()

    async with aiohttp.ClientSession() as client:
        info, lbals = await asyncio.gather(api.exchange_info(client),
                                           api.balances(client))
        symbols, src_symbols, usd_symbol = api.quote_symbols(info)
        bals = filter_balances(lbals, [env.qcoin] + env.src_coins)
        if env.qcoin not in bals:
            raise CException('Quote coin is invalid')
        qbal, qloc = bals[env.qcoin]
        del bals[env.qcoin]
        print(
            f'Your free balance for {env.qcoin} is {ffmt(qbal)} (locked: {ffmt(qloc)})'
        )
        def_qty = env.buy_perc / 100 * qbal
        if env.usd_value:
            # fixed USD quote balance feature
            usd_price = await quote_qty_from_usd(client, api, usd_symbol)
            qqty = env.usd_value / usd_price
            while qqty > qbal:
                diff = 1.02 * (qqty - qbal)
                qbal += await buy_from_source(client, api, src_symbols, bals,
                                              diff)
        else:
            prompt = f'Enter {env.qcoin} amount to sell ' + \
                     f'[default: {ffmt(def_qty)} ({env.buy_perc:.2f}%)]: '
            qqty = float(set_stdin(prompt, def_qty))
            if qqty <= 0:
                raise CException(
                    f'Cannot sell non-positive amount of {env.qcoin}')
            if qqty > qbal:
                raise CException('Insufficient quote balance')

    prompt = f'Enter sell type (LIMIT|MARKET) [default: {env.sell_type.name}]: '
    env.sell_type = SellType(set_stdin(prompt, env.sell_type))

    prompt = f'Enter desired profit in % [default: {env.profit:.2f}]: '
    env.profit = float(set_stdin(prompt, env.profit))

    if env.profit <= 0:
        CColors.wprint(
            'You have set a non-positive profit. Proceeding may net you a loss!'
        )

    prompt = f'Enter stop level in % to manage risk [default: {env.stop:.2f}]: '
    env.stop = float(set_stdin(prompt, env.stop))
    if not -100 <= env.stop < env.profit:
        raise CException('Stop percentage must be lower than profits!')

    print('---- SELECTED OPTIONS ----')
    print(f'Selected quote coin: {env.qcoin}')
    print(f'Selected quote amount to sell: {ffmt(qqty)} {env.qcoin} ' + \
          f'(available: {ffmt(qbal)} {env.qcoin})')
    print(f'Selected sell strategy: {env.sell_type.name}')
    print(f'Selected target profit: {env.profit:.2f}%')
    print(f'Selected stop percentage: {env.stop:.2f}%')
    print('--------------------------')
    return symbols, qqty