Esempio n. 1
0
    def __init__(
        self,
        api_key: str,
        api_secret: str,
    ) -> None:
        """
        Initialize the Binance client
        Args:
            api_key (str): api key for binance api client
            api_secret (str): api secret for binance api client
        Return:
            None
        """

        self.binance_client = BinanceClient(
            api_key=api_key,
            api_secret=api_secret
        )

        server_time_utc_iso8601 = datetime_to_iso8601(
            self.get_binance_api_server_time()
        )
        print(f"Binance API Time: {server_time_utc_iso8601}")

        if not self.is_binance_api_live():
            sys.exit("Binance API is down")
        print("Binance API is up")
def populate_historical(market, start_time):
    binance_api = config['binance']['api']
    binance_secret = config['binance']['secret']

    binance_client = BinanceClient(binance_api, binance_secret)

    # Get historical aggregated trade data as generator object and count number of historical trades
    historical_trades = binance_client.aggregate_trade_iter(
        symbol=market, start_str=start_time)

    logger.info('Counting historical trades for database population.')

    trade_count = sum(1 for trade in historical_trades)
    logger.debug('trade_count: ' + str(trade_count))

    # Get historical aggregated trade data again to refresh generator object (May make total count off by few trades)
    historical_trades = binance_client.aggregate_trade_iter(
        symbol=market, start_str=start_time)

    count = 0
    for trade in historical_trades:
        process_result = process_message(trade, populate=True, symbol=market)

        if process_result == False:
            logger.info('Database population complete.')
            break
        else:
            count += 1
            logger.info('Processed ' + str(count) + ' of ~' +
                        str(trade_count) + ' historical trades.')
Esempio n. 3
0
def get_binance_data(pairname, start_timestamp):
    binance_client = BinanceClient('api_key', 'api_secret')
    klines = binance_client.get_historical_klines(pairname, BinanceClient.KLINE_INTERVAL_1MINUTE, start_timestamp)
    df = pd.DataFrame(klines, columns=['Time', 'Open', 'High', 'Low', 'Close', 'Volume', 'Close_Time', 'quote_asset_volume', 'no_of_trades', 'taker_buy_base_asset_vol', 'taker_buy_quote_asset_volume', 'ignore'])
    df = df[['Time', 'Open', 'High', 'Low', 'Close', 'quote_asset_volume']]
    df = df.rename(columns={'quote_asset_volume': 'Volume'})
    df['Time'] = pd.to_datetime(df['Time'], unit='ms') #see cleaning
    return df
Esempio n. 4
0
def _process_binance(_, symbol):
    client = BinanceClient(s.BINANCE_API_KEY, s.BINANCE_API_SECRET)

    _symbol = "{}{}".format(*symbol)
    order_book = client.get_order_book(symbol=_symbol,
                                       limit=ORDER_BOOK_BINANCE_LIMIT)

    _process(_symbol, order_book, offset=ORDER_BOOK_BINANCE_OFFSET)
Esempio n. 5
0
    def __init__(self, *args, **kwargs):
        super(Binance, self).__init__('binance', *args, **kwargs)

        key = self.config['api_key']
        secret = self.config['api_secret']

        self.client = BinanceClient(key, secret)
        self._debpth_data_buffer = Queue()
        self._load_depth_snapshot_thread = None
Esempio n. 6
0
def populate_historical(exchange, market, start_time):
    if exchange == 'binance':
        binance_api = config['binance']['api']
        binance_secret = config['binance']['secret']

        binance_client = BinanceClient(binance_api, binance_secret)

        # Get historical aggregated trade data as generator object and count number of historical trades
        historical_trades = binance_client.aggregate_trade_iter(
            symbol=market, start_str=start_time)

        logger.info('Counting historical trades for database population.')

        trade_count = sum(1 for trade in historical_trades)
        logger.debug('trade_count: ' + str(trade_count))

        # Get historical aggregated trade data again to refresh generator object (May make total count off by few trades)
        historical_trades = binance_client.aggregate_trade_iter(
            symbol=market, start_str=start_time)

        count = 0
        for trade in historical_trades:
            process_result = process_message(trade,
                                             populate=True,
                                             exchange=exchange,
                                             market=market)

            if process_result == False:
                logger.info('Database population complete.')
                break
                #logger.info('Trade document already present in database.')
            else:
                count += 1
                completion_percentage = "{:.2f}".format(
                    (count / trade_count) * 100)
                logger.info('Processed ' + str(count) + ' of ~' +
                            str(trade_count) + ' historical trades. [' +
                            completion_percentage + '%]')

    elif exchange == 'poloniex':
        logger.warning('POLONIEX DATABASE POPULATION NOT YET IMPLEMENTED.')

    else:
        logger.error(
            'Unrecognized exchange passed to populate_historical(). Exiting.')
        sys.exit(1)
Esempio n. 7
0
    def getPriceForCoinWithProperClient(name, exchangeCoin):
        try:
            if name == 'Coinbase Pro':
                symbol = exchangeCoin.coin_change.coin.key + '-' + exchangeCoin.coin_change.coin_to_change.key
                return gdax.PublicClient().get_product_ticker(
                    product_id=symbol)['price']
            elif name == 'Binance':
                symbol = exchangeCoin.coin_change.coin.key + exchangeCoin.coin_change.coin_to_change.key
                return BinanceClient(
                    "", "").get_symbol_ticker(symbol=symbol)['price']
            elif name == 'Kucoin':
                symbol = exchangeCoin.coin_change.coin.key + '-' + exchangeCoin.coin_change.coin_to_change.key
                return KucoinClient(
                    "", "").get_tick(symbol=symbol)['lastDealPrice']

            return None
        except:
            return None
Esempio n. 8
0
async def exchange_wallet(request):
    exchange_name = request.json.get('exchange_name')

    api_key = request.json.get('api_key')
    api_secret = request.json.get('api_secret')
    assets = request.json.get('assets')

    binance_client = BinanceClient(api_key, api_secret)

    res = {}
    for asset in assets:
        binance_asset = asset
        if asset == 'WAV':
            binance_asset = 'WAVES'
        deposit_address = binance_client.get_deposit_address(asset=binance_asset)
        res[asset] = deposit_address['address']

    return json_response(res)
    def __init__(self):
        self.binanceClient = BinanceClient(BinanceSettings.api_key,
                                           BinanceSettings.api_secret)
        self.gdax_public_client = GdaxPublicClient()
        self.gdax_authenticated_client = GdaxAuthenticatedClient(
            key=GdaxSettings.api_key,
            b64secret=GdaxSettings.api_secret,
            passphrase=GdaxSettings.api_passphrase)
        self.sandbox_gdax_authenticated_client = GdaxAuthenticatedClient(
            key=GdaxSettings.sandbox_key,
            b64secret=GdaxSettings.sandbox_secret,
            passphrase=GdaxSettings.sandbox_passphrase,
            api_url='https://api-public.sandbox.gdax.com')
        self.kraken_public_client = KrakenAPI()

        self.MARKET_BINANCE = 'binance'
        self.MARKET_GDAX = 'gdax'
        self.MARKET_KRAKEN = 'kraken'
Esempio n. 10
0
 def __init__(self):
     self.client = BinanceClient(os.getenv("BINANCE_API_KEY"),
                                 os.getenv("BINANCE_SECRET_KEY"))
     self.config = get_config()
Esempio n. 11
0
 def get_client(self):
     return BinanceClient(
         self.key,
         self.secret
     )
Esempio n. 12
0
def get_client():
    """ Return a new instance with Binance API connection """
    return BinanceClient(config.get('api_key'), config.get('api_secret'))
logger = logging.getLogger(__name__)

if debug_mode == True:
    logger.setLevel(logging.DEBUG)
else:
    logger.setLevel(logging.INFO)

config_path = 'config/config.ini'

config = configparser.ConfigParser()
config.read(config_path)

binance_api = config['binance']['api']
binance_secret = config['binance']['secret']

binance_client = BinanceClient(binance_api, binance_secret)
binance_ws = BinanceSocketManager(binance_client)

db = MongoClient(config['mongodb']['uri'])[config['mongodb']['db']]

collections = {'data': 'flowmeter', 'analysis': 'analysis'}


def process_message(msg, populate=False, symbol=None):
    process_message_success = True

    try:
        logger.debug('msg: ' + str(msg))

        trade_doc = {}
Esempio n. 14
0
example content for keys.py, obtain keys from kucoin.com &
keys = dict(
    kuClient_key         =  'blah',
    kuClient_secret      =  'blah',
    BinanceClient_key    =  'blah',
    BinanceClient_secret =  'blah',
)
"""

KUCLIENT_KEY = keys['kuClient_key']
KUCLIENT_SECRET = keys['kuClient_secret']
BINANCECLIENT_KEY = keys['BinanceClient_key']
BINANCECLIENT_SECRET = keys['BinanceClient_secret']

client = kuClient(KUCLIENT_KEY, KUCLIENT_SECRET)
bclient = BinanceClient(BINANCECLIENT_KEY, BINANCECLIENT_SECRET)


def watch():
    try:
        orders = client.get_buy_orders('DASH-ETH', limit=5)
        sellorders = client.get_sell_orders('DASH-ETH', limit=5)
        depth = bclient.get_order_book(symbol='DASHETH')
        bsell = depth['asks'][0][0]
        bbuy = depth['bids'][0][0]
        ksell = sellorders[0][0]
        kbuy = orders[0][0]
        kbuyAdd = kbuy + 0.01
    except:
        print('problem grabbing order books')
        kbuyAdd = 2
Esempio n. 15
0
poloniex_gas_add = "AX8UxpFQcp3LYEEk9j4K8CPbZTWwyjHJdT"

binance_gas_add = "AexzA2PoEytX3nKwTpx4fgXovFPhUzydxb"
poloniex_btc_add = "1KGFzwUrLtQc8GfmWT8NRV4XfikbYKFqZh"
kucion_btc_add = "14eg4a5q1tucRcBipC8aD5tS4a5i9gb5hv"
binance_btc_add = "14eg4a5q1tucRcBipC8aD5tS4a5i9gb5hv"

poloniex_bitcoin_withdrawl_fee = 0.0005
binance_bitcoin_withdrawl_fee = 0.001
kucoin_bitcoin_withdrawl_fee = 0.0005

binance_trading_fee = 0.001
kucoin_trading_fee = 0.001
poloniex_trading_fee = 0.0015

binance_client = BinanceClient(binance_api_key, binance_api_secret)
poloniex_client = poloniex.Poloniex(poloniex_api_key, poloniex_api_secret)
kucion_client = KucoinClient(kucoin_api_key, kucoin_api_secret)

fixes = [{
    'coinmarketcap': 'MIOTA',
    'binance': 'IOTA'
}, {
    'coinmarketcap': 'BCH',
    'binance': 'BCC'
}]

max_principal_btc = 0.1


def main():
        operationsIndex += 1

    return queryObject


# Read configuration
config = configparser.ConfigParser()
config.read('config.ini')
apiKey = config['authentication']['apikey']
apiSecret = config['authentication']['apisecret']
symbol = config['symbol']['name']
depth = config['symbol']['depth']
dbHost = config['datastore']['dbhost']
dbName = config['datastore']['dbname']
dbPassword = config['datastore']['dbpassword']
dbPort = config['datastore']['dbport']
dbUser = config['datastore']['dbuser']

# connect to database
dbClient = influxdb.InfluxDBClient(host=dbHost,
                                   port=dbPort,
                                   username=dbUser,
                                   password=dbPassword,
                                   database=dbName)

# Create connection and websocket to Binance API
bnClient = BinanceClient(apiKey, apiSecret)
wsManager = BinanceSocketManager(bnClient)
connection = wsManager.start_depth_socket(symbol, writeToInflux, depth=depth)
wsManager.start()
Esempio n. 17
0
import environs
import numpy as np
import pandas as pd
from binance.client import Client as BinanceClient
from tqdm import tqdm

env = environs.Env()
env.read_env()


BINANCE_API_KEY = env.str('BINANCE_API_KEY')
BINANCE_API_SECRET = env.str('BINANCE_API_SECRET')


client = BinanceClient(BINANCE_API_KEY, BINANCE_API_SECRET)


def get_market_bars(symbol: str, interval: str, start_dt: dt.datetime, end_dt: dt.datetime) -> pd.DataFrame:
    headers = (
        'Open time',
        'Open',
        'High',
        'Low',
        'Close',
        'Volume',
        'Close time',
        'Quote volume',
        'Trades',
        'Buy base volume',
        'Buy quote volume',
Esempio n. 18
0
 def __init__(self):
     self._client = BinanceClient("", "")
     self._limit = 1000
Esempio n. 19
0
 def _get_binance_client():
     api_key, api_secret = Unity.get_api_keys()
     return BinanceClient(api_key, api_secret)
Esempio n. 20
0
 def __init__(self, account_name='', api_key='', api_secret=''):
     super().__init__("binance", account_name, api_key, api_secret)
     self.binanceClient = BinanceClient(self.api_key, self.api_secret)
Esempio n. 21
0
from binance.client import Client as BinanceClient

logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

config_path = '../config/config_testing.ini'

if __name__ == '__main__':
    config = configparser.ConfigParser()
    config.read(config_path)

    api = config['binance']['api']
    secret = config['binance']['secret']

    binance_client = BinanceClient(api, secret)

    historical_trades = binance_client.aggregate_trade_iter(
        symbol='XLMBTC', start_str='15 minutes ago UTC')

    trade_info = {}
    for trade in historical_trades:
        first_trade_id_agg = trade['a']
        first_trade_id_first = trade['f']
        first_trade_id_last = trade['l']
        break

    pprint(trade)

    ## WORKS ##
    print('Aggregate Trade ID Test:')
Esempio n. 22
0
 def _binance_client(self, api_key=None, api_secret=None) -> BinanceClient:
     return BinanceClient(api_key=api_key, api_secret=api_secret)
Esempio n. 23
0
def get_tickers_by_quote_dict() -> dict:
    """
    Returns dictionary: key - some currency, value - list of binance tickers with key as a quote currency

    Example: get_tickers_by_quote_dict() = {
    'BTC': [{'symbol': 'TRXBTC', 'lastPrice': '0.00000350', ...}, {'symbol': 'ETHBTC', 'lastPrice': '0.032', ...}]
    'USDT': [{'symbol': 'BTCUSDT', 'lastPrice': '20151.05', ...}, {'symbol': 'XLMUSDT', 'lastPrice': '0.277', ...}]
    ...
    }
    """
    tickers = {q: [] for q in ALL_QUOTE_CURRENCIES}
    for ticker in binance.get_ticker():
        ticker['base'] = get_base_currency(ticker['symbol'])
        ticker['quote'] = get_quote_currency(ticker['symbol'])
        tickers[ticker['quote']].append(ticker)
    return tickers


def get_current_time() -> int:
    """
    Returns current timestamp in milliseconds
    """
    return int(datetime.datetime.now().timestamp() * 1000)


"""Global Binance client instance"""
binance = BinanceClient(api_keys.get_public(), api_keys.get_secret())
"""Global information about step sizes and precision"""
precision_by_symbol = get_precision_by_symbol_dict()
    elif statusCode == "CANCELED": return "Отменен"
    elif statusCode == "TRADE": return "Исполнен"
    elif statusCode == "EXPIRED": return "Просрочен"
    elif statusCode == "REJECTED": return "Отклонен"
    elif statusCode == "FILLED": return "Исполнен"
    elif statusCode == "PARTIALLY_FILLED": return "Частично исполнен"

    else: return "Статус неизвестен(?)"


messageSender = MessageSender(MessageType.TELEGRAM)
messageSender.setTelegramRecipient(TelegramRecipient.ARBITRAGE_GROUP)
#messageSender.setTelegramRecipient(TelegramRecipient.KOROVAEV_USER)

clientArbitrageExmo = BinanceClient(
    "cpVoAC6GOvchaOtNKEBevnKypS2ruQoz5VMoCZHmF2GqoiVkaQiHGO8eFObwXkPn",
    "xaLFuFrLUL89pnXRTwKcLggT7HgLD3rcKSzWGza6ZHE9twsvD5HsQqwrRGJHGWQO")

clientArbitrageCexIO = BinanceClient(
    "3AXtPzcT9Hrbt0il8DGhlnY8oqSwVDc8XGOOaRYC9PL2mehTGyZz984NvYG561yn",
    "oyo7KC54D02uCZkfP7Sm7IdW0rHp3LSVhs7sboc8opkkkHTFc4ie0EXP5VN0EpTz")

bmExmo = BinanceSocketManager(clientArbitrageExmo)
key_user = bmExmo.start_user_socket(UserExmoEventCallback)
# then start the socket manager
bmExmo.start()

bmCex = BinanceSocketManager(clientArbitrageCexIO)
key_user2 = bmCex.start_user_socket(UserCEXEventCallback)
# then start the socket manager
bmCex.start()
Esempio n. 25
0
import time
import requests
import dateparser

from binance.client import Client as BinanceClient
from kucoin.client import Client

# In[3]:

client = Client('5b63c73008d8b104b0add6b0',
                'd239ffe0-0120-49eb-9a85-04e712244f47')
# client = Client('5b7c872808d8b15529c035c3', 'fc3810e5-462d-413b-9a88-aac40203f8cc')

bclient = BinanceClient(
    'wZUkR3OrwI953kvURKvRXiwTT41xT0Qsh1G7UfB6rz5kbGM0t9qspLAYaUCpfk7z',
    'ybvMtTm4PeOGT0bJ5CrQugI5Wpdi2OcvaIoB0wAD462lekazGP0wRirDXL5kIbJM')
# bclient = BinanceClient('EDSFRPjwir0HhT4oZhCUHace2wIVxtqKpmdtpjla47Dxlp07WRoRCAVVrtKjEXso', 'V6JY4yWcPbhMleYUWacgItMaECdxY0TcDW1mD3SZZje8pwYFepnjlzRcUabCwQxX')

# In[4]:

# KUCOIN
currencies = client.get_currencies()

orders = client.get_buy_orders('ETH-BTC', limit=50)
sellorders = client.get_sell_orders('ETH-BTC', limit=50)

# account balance
userFee = 0.002
# accountBalanceKucoin = 0.0009027 * (1 - userFee)# 0.0009145 * (1 - userFee)
accountBalanceKucoinBTC = (float(
Esempio n. 26
0
import time

from binance.client import Client as BinanceClient
from binance.exceptions import BinanceAPIException, BinanceWithdrawException

API_KEY = ''
API_SECRET = ''

bclient = BinanceClient(API_KEY, API_SECRET)

##binance tickers
tickers = {}
coins = []
try:
    ticker_collections = bclient.get_all_tickers()
except BinanceAPIException as e:
    print(e)
except BinanceWithdrawException as e:
    print(e)
else:
    for item in ticker_collections:
        tickers[item['symbol']] = item['price']

        try:
            symbol_info = bclient.get_symbol_info(item['symbol'])
            print(symbol_info)

            coin_name = symbol_info['baseAsset']
            if coin_name not in coins:
                coins.append(coin_name)
            coin_name = symbol_info['quoteAsset']
Esempio n. 27
0
from automation.bomberman_coins import BombermanCoins
from automation.functions import load_config
from automation.logger import Logger
from automation.order_storage import OrderStorage
from automation.parser.message_parser import UnknownMessage

OFFICIAL_DISCORD_CHANNEL = 759070661888704613

if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument('--config-file')
    args = parser.parse_args()
    config = load_config(args.config_file)

    discord_client = DiscordClient()
    binance_client = BinanceClient(config['binance_api']['key'],
                                   config['binance_api']['secret'])
    binance_socket = BinanceSocketManager(binance_client)
    spot_api = SpotApi(binance_client)
    futures_api = FuturesApi(config['app']['futures']['margin_type'], binance_client)
    order_storage = OrderStorage('data/orders.pickle')
    logger = Logger('log/bomberman_coins.log',
                    config['email']['recipient'],
                    config['email']['host'],
                    config['email']['user'],
                    config['email']['password'])
    bomberman_coins = BombermanCoins(config['app']['market_type'],
                                     config['app']['spot']['trade_amount'],
                                     config['app']['futures']['trade_amount'],
                                     config['app']['futures']['leverage'],
                                     config['app']['futures']['max_leverage'],
                                     spot_api, futures_api, order_storage, logger)