Пример #1
0
def validate_binance_key(api_key, api_secret):
    try:
        client = binance.Client(api_key, api_secret)

        account = client.get_account()

        # test order creation
        client.create_test_order(
            symbol='ETHBTC',
            side=binance.AsyncClient.SIDE_SELL,
            type=binance.AsyncClient.ORDER_TYPE_LIMIT,
            timeInForce=binance.AsyncClient.TIME_IN_FORCE_GTC,
            quantity=1,
            price=0.034175,
        )

        asset_id = 'BTC'
        to_addr = client.get_deposit_address(asset=asset_id)['address']
        amount = '0.0001' # this is an invalid amount to withdraw, we use this to test
        # test withdraw
        result = client.withdraw(
                asset=asset_id,
                address=to_addr,
                amount=amount)
    except BinanceAPIException as e:
        return False, f'Failed to validate your binance keys based on the keys, error: {str(e)}'
    except BinanceWithdrawException as e:
        return True, ''
    except KeyError as e: # a bug, in python-binance
        return False, f'Your key cannot withdraw assets, be sure to enable Withdrawals of your API key and run the bot in your whitelisted IPs'

    return True, ''
Пример #2
0
    def get_klines(self, pair):
        self.tts = 1000000000000
        if (self.mode == "insert"):
            self.tts = 1000000000000
        else:
            self.tts = self.get_last_timespan(pair)

        if (self.tts > time.mktime(
                datetime.datetime.strptime(self.final_date,
                                           "%d/%m/%Y").timetuple()) * 1000):
            pass
        else:
            try:
                # client = binance.Client()
                client = binance.Client(
                    "PdrOQxCfl40l11UOUrlQBVweoIcuX4LBkQUUGvMl8gsTsPWsGFiSdU3oQllKJVCp",
                    "YF9rWjve77q5frFy6HRRG52oixIRET9VMV4lZXEhTrGWq2LVzuT4DM2YvcjhEsCP",
                    {"timeout": 800})
                # for y in ["apple", "banana", "cherry"]
                klines = client.get_historical_klines(pair,
                                                      self.interval,
                                                      str(self.tts),
                                                      "1, 1, 2022",
                                                      klines_type=self.market)
                # print(klines[0][0])
                print(str(len(klines)) +
                      " candles saved!")  # , " 5min candle for Jan")
                self.save_data(klines, pair)
            except Exception as e:
                print("some errors here in :" + pair + " about: " + str(e))
Пример #3
0
async def main(loop):
    # /!\ Never hardcode your api secrets, prefer to use a config (I love toml, yaml is fine, json works)
    # Don't forget to add your config to .gitignore and give a template
    config = Config("config.toml", "config.template.toml")
    client = binance.Client(config.api_key, config.api_secret)
    # we load the client (this is not mandatory but it allows binance.py
    # to prevent you if you entered a wrong token name for example)
    await client.load()
    # we start the data stream
    await client.create_events_listener()
    # we register the events
    client.events.order_update_handlers.append(on_order_update)
Пример #4
0
async def main(loop):
    # /!\ Never hardcode your api secrets, prefer to use a config (I love toml, yaml is fine, json works)
    # Don't forget to add your config to .gitignore and give a template
    config = Config("config.toml", "config.template.toml")
    client = binance.Client(config.api_key, config.api_secret)
    # we load the client (this is not mandatory but it allows binance.py
    # to prevent you if you entered a wrong token name for example)
    await client.load()
    # we register the events
    # client.events.register_event(on_price_update, "ethbtc@bookTicker")
    client.events.register_event(on_price_change, "ethbtc@bookTicker")
    # we start the data stream
    loop.create_task(client.start_market_events_listener())
Пример #5
0
async def main(loop):
    # /!\ Never hardcode your api secrets, prefer to use a config (I love toml, yaml is fine, json works)
    # Don't forget to add your config to .gitignore and give a template
    config = Config("config.toml", "config.template.toml")
    client = binance.Client(config.api_key, config.api_secret)

    order = await client.create_order(
        "ETHPAX",
        binance.Side.BUY.value,
        binance.OrderType.MARKET.value,
        quantity=1,
        test=True,
    )
    print(order)
Пример #6
0
async def main(loop):
    # /!\ Never hardcode your api secrets, prefer to use a config (I love toml, yaml is fine, json works)
    # Don't forget to add your config to .gitignore and give a template
    config = Config("config.toml", "config.template.toml")
    client = binance.Client(config.api_key, config.api_secret)
    await client.load()

    order = await client.create_order(
        symbol="BTCUSDT",
        side=binance.Side.SELL,
        order_type=binance.OrderType.LIMIT,
        time_in_force=binance.TimeInForce.GTC,
        quantity=Decimal("0.0012"),  # you can use Decimals
        price="15100.00",  # or directly a string
        test=False,
    )
    print(order)
Пример #7
0
async def parser(message):
    config.read('config.ini')
    binance_key = config['Binance']['binance_key']
    binance_sec = config['Binance']['binance_sec']
    kucoin_key = config['Kucoin']['kucoin_key']
    kucoin_sec = config['Kucoin']['kucoin_sec']
    kucoin_api_pass = config['Kucoin']['kucoin_api_pass']
    coinmarketcap_apikey = config['API']['coinmarketcap_apikey']
    blockfrost_apikey = config['API']['blockfrost_apikey']
    ada_address = config['Addresses']['ada_address']
    bnb_address = config['Addresses']['bnb_address']
    total = []
    USDT = 0.
    RUB = 0.
    # * Getting coins info from Binance
    try:
        client = binance.Client(binance_key, binance_sec)
        await client.load()
        accinfo = await client.fetch_account_information(receive_window=None)
        for coin in accinfo['balances']:
            if coin['asset'] == "USDT":
                USDT += float(coin['free'])
            elif coin['asset'] == "RUB":
                RUB += float(coin['free'])
            else:
                amount = float(coin['free'])
                ticker = coin['asset'] + "USDT"
                if amount > 0.000001:
                    print(ticker[:-4] + f" amount: {amount}")
                    coin.pop('locked')
                    coin['amount'] = float(coin.pop('free'))
                    total.append(coin)
        await client.close()
    except:
        print("Wrong Binance credentials.")
        bot.send_message(message.chat.id,
                         "You entered wrong Binance credentials.")

    # * Getting the amount of ADA on Yoroi
    link_cardano = "https://cardano-mainnet.blockfrost.io/api/v0/addresses/"
    headers = {'project_id': blockfrost_apikey}

    session = Session()
    session.headers.update(headers)
    try:
        response = session.get(link_cardano + ada_address)
        data = json.loads(response.text)
    except (ConnectionError, Timeout, TooManyRedirects) as e:
        print(e)
    try:
        ada_amount = float(data['amount'][0]['quantity'])
    except:
        ada_amount = 0
        bot.send_message(
            message.chat.id,
            "You entered wrong ADA address or Blockfrost API key.")
    if ada_amount > 1e+6:
        ada_amount /= 1e+6
    print(f"Found {ada_amount} ADA in Cardano Wallet")

    if not any(d['asset'] == 'ADA' for d in total):
        total.append({'asset': 'ADA', 'amount': ada_amount})
    else:
        for x in total:
            if x['asset'] == 'ADA':
                x['amount'] += ada_amount

    # * Getting the coins from BNB Wallet

    bnb_api_link = "https://dex.binance.org/api/v1/account/"

    response = urlopen(bnb_api_link + bnb_address)
    data_json = (json.loads(response.read()))['balances']
    for coin in data_json:
        amount = float(coin['free'])
        ticker = coin['symbol']
        if "CBB" in ticker:
            ticker = ticker[:-4]
        if amount > 0.000001:
            if not any(d['asset'] == ticker for d in total):
                total.append({'asset': ticker, 'amount': amount})
                print(
                    f"creating {ticker} with {amount} in total | From BNB Wallet"
                )
            else:
                for coin in total:
                    if coin['asset'] == ticker:
                        coin['amount'] += amount
                        print(
                            f"adding to {ticker} {amount} in total | From BNB Wallet"
                        )
                        break

    # *Getting coins from Kucoin
    try:
        client = Client(kucoin_key, kucoin_sec, kucoin_api_pass)
        kucoininfo = client.get_accounts()
        for coin in kucoininfo:
            if coin['type'] != 'trade':
                continue
            amount = float(coin['balance'])
            ticker = coin['currency']
            if amount > 0.000001 and ticker != "USDT":
                if not any(d['asset'] == ticker for d in total):
                    total.append({'asset': ticker, 'amount': amount})
                    print(
                        f"creating {ticker} with {amount} in total | From Kucoin"
                    )
                else:
                    for coin in total:
                        if coin['asset'] == ticker:
                            coin['amount'] += amount
                            print(
                                f"adding to {ticker} {amount} in total | From Kucoin"
                            )
                            break
    except:
        print("Wrong Kucoin credentials.")
        bot.send_message(message.chat.id,
                         "You entered wrong Kucoin credentials.")

    try:
        coinmarketcap_url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest"
        alltickers = ""
        for coin in total:
            alltickers += (coin['asset'] + ",")
        alltickers = alltickers[:-1]
        parameters = {'symbol': alltickers}
        headers = {
            'Accepts': 'application/json',
            'X-CMC_PRO_API_KEY': coinmarketcap_apikey,
        }
        session = Session()
        session.headers.update(headers)
        response = session.get(coinmarketcap_url, params=parameters)
        data = json.loads(response.text)
        print("Got prices from Coinmarketcap")
        for coin in total:
            ticker = coin['asset']
            coin['price'] = data['data'][ticker]['quote']['USD']['price']
            coin['value_in_USD'] = coin['price'] * coin['amount']
        total = [
            i for i in total
            if not (i['value_in_USD'] < include_with_value_higher_than)
        ]
        total = sorted(total, key=itemgetter('value_in_USD'), reverse=True)

        balance = 0.
        for coin in total:
            balance += coin['value_in_USD']
        balance += USDT + (RUB / 74)
        balance = round(balance, 2)
        reply_msg = "*Total balance is " + str(balance) + " $*" + "\n\n"
        reply_msg += "*In coins:*\n"
        for coin in total:
            if coin['amount'] >= 1:
                amount = str(round(coin['amount'], 2))
            else:
                amount = str(round(coin['amount'], 6))
            reply_msg += coin['asset'] + ": " + amount + " | " + \
                str(round(coin['value_in_USD'], 2)) + " $\n"
        reply_msg += "\n*In fiat:*\n" + str(round(USDT, 2)) + " $\n"
        if RUB != 0:
            reply_msg += str(round(RUB, 2)) + " ₽\n"

        bot.reply_to(message, reply_msg, parse_mode='Markdown')
    except:
        print("Wrong API key for Coinmarketcap")
        bot.send_message(message.chat.id,
                         "You entered wrong Coinmarketcap API key.")
Пример #8
0
 def setUp(self):
     config = Config("config.toml", "config.template.toml")
     self.client = binance.Client(config.api_key, config.api_secret)
Пример #9
0
 def test_object_created(self):
     client = binance.Client()
Пример #10
0
async def connect():
    binance_client = binance.Client(BINANCE_API_KEY, BINANCE_API_SECRET)
    await binance_client.load()
    return binance_client
Пример #11
0
#-*-coding:utf-8-*-
'''

@author:HANDSOME_JERRY
@time:'18-8-1下午1:58'
'''
import json
import requests, re, time
import pandas as pd
import binance

api_key = 'H7qN5zkKv52lp4jQ83UXAf8d6TZf2uOTaTpVidjMKLPthSnu5ontYXQh07v9dpuF'
api_secret = 'l4swxv53RzI61IoNKYge2Q9AeZvg7pDtdiBphFShTTnVrdXSTFhLjvUITzc7HWGN'
client = binance.Client(api_key, api_secret)

# get market depth
#depth = client.get_order_book(symbol='BNBBTC')

# place a test market buy order, to place an actual order use the create_order function
# order = client.create_test_order(
#     symbol='BNBBTC',
#     side=Client.SIDE_BUY,
#     type=Client.ORDER_TYPE_MARKET,
#     quantity=100)

# get all symbol prices
#prices = client.get_all_tickers()

# withdraw 100 ETH
# check docs for assumptions around withdrawals
# from binance.exceptions import BinanceAPIException, BinanceWithdrawException