def get_ticker_price(ticker, coin=False):
    if ticker and not coin:
        url = f"https://query1.finance.yahoo.com/v8/finance/chart/{ticker}?region=US&lang=en-US&includePrePost=false&interval=1m&useYfid=true&range=1d&corsDomain=finance.yahoo.com&.tsrc=finance"
        headers = {
            'User-Agent':
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'
        }
        res = requests.get(url, headers=headers)
        data = json.loads(res.text)
        try:
            return float(
                data["chart"]["result"][0]["meta"]["regularMarketPrice"])
        except TypeError:
            return False
    elif ticker and coin:
        b_api_key = "8AiGAyxlhYQaRpE1s7097hx5sZ12Ogtr8ir9DsyztaD5j24LrI0fEoToDzCI5lle"
        b_api_secret = "VhudTs0HsBVFNdSTghmqfCjUuIXF6rFiXIfROxHIaM71TGgib7NeZ5aOsJUHjI9f"
        client = Client(b_api_key, b_api_secret)
        res = client.get_all_tickers()
        if isinstance(ticker, str):
            for c_ticker in res:
                if ticker == c_ticker["symbol"]:
                    return c_ticker["price"]
            return False
        elif isinstance(ticker, list):
            tickers_prices = {}
            for c_ticker in res:
                if c_ticker["symbol"] in ticker:
                    tickers_prices[c_ticker["symbol"]] = c_ticker["price"]
            return tickers_prices
Example #2
0
async def test_no_secret():
    client = Client('api_key')

    for method in ['get', 'post', 'delete', 'put']:
        with pytest.raises(APISecretNotDefinedException, match='api_secret'):
            await getattr(client, method)('/foo',
                                          security_type=SecurityType.USER_DATA)
Example #3
0
def test_handler_reuse():
    client = Client('api_key')
    client2 = Client('api_key')

    handler = TickerHandlerBase()

    with pytest.raises(ReuseHandlerException, match='more than one'):
        client.handler(handler)
        client2.handler(handler)
Example #4
0
async def test_invalid_json():
    """Test Invalid response Exception"""

    with pytest.raises(InvalidResponseException, match='invalid response'):
        with aioresponses() as m:
            m.get('https://api.binance.com/api/v3/time', body='<head></html>')

            client = Client('api_key')
            await client.get_server_time()
Example #5
0
async def test_user_trades():
    if not has_private_config:
        return

    client = Client(API_KEY, API_SECRET)

    res = await client.get_trades(symbol='BTCUSDT')

    print_json('get_trades:', res)
Example #6
0
async def test_api_exception():
    """Test Status Exception"""
    with pytest.raises(StatusException, match='status'):
        with aioresponses() as m:
            json_obj = {"code": 1002, "msg": "Invalid API call"}
            m.get('https://api.binance.com/api/v3/time',
                  payload=json_obj,
                  status=400)

            client = Client('api_key')
            await client.get_server_time()
Example #7
0
async def test_api_exception_invalid_json():
    """
    Test Status Exception, StatusException comes before InvalidResponseException
    """

    with pytest.raises(StatusException):
        with aioresponses() as m:
            not_json_str = "<html><body>Error</body></html>"
            m.get('https://api.binance.com/api/v3/time',
                  body=not_json_str,
                  status=400)

            client = Client('api_key')
            await client.get_server_time()
Example #8
0
    def __init__(self,
                 api_key,
                 api_secret,
                 symbol: str,
                 base_instrument: str,
                 useTestNet: bool = False,
                 isLive: bool = False):

        self.isLive = isLive
        #self.previousBuy_price = 0.0
        self.client = Client(api_key, api_secret, testnet=useTestNet)

        # self.asset_balance = 0
        # self.base_instrument_balance = 10000.0

        self.pair = symbol + base_instrument
        print('Trading pair: ', self.pair)

        if self.isLive:
            account_info = self.client.get_account()
            print(list(account_info.items())[:9])

            if not useTestNet:
                trade_fees = self.client.get_trade_fee(
                    symbol=symbol.upper() +
                    base_instrument.upper())  ## this is a list of dict
                self.fees = trade_fees[0]['makerCommission']
                print('trading fees/commission = {} '.format(self.fees))

            self.asset_balance = self.client.get_asset_balance(
                asset=symbol.upper())["free"]
            self.base_instrument_balance = self.client.get_asset_balance(
                asset=base_instrument.upper())["free"]

            print('account balance, {} = '.format(symbol), self.asset_balance)
            print('account balance, {} = '.format(base_instrument),
                  self.base_instrument_balance)
async def test_request_params():
    client = Client()

    with aioresponses() as m:
        redirect(m)

        with pytest.raises(
            StatusException,
            match='status 307'
        ):
            await client.get(
                URL,
                request_params={
                    'allow_redirects': False
                }
            )
Example #10
0
async def test_free_apis():
    client = Client()

    print('')

    async def go():
        for case in FREE_CASES:
            name = case['name']
            args = case.get('a', tuple())
            kwargs = case.get('ka', {})

            ret = await getattr(client, name)(*args, **kwargs)

            print_json(name + ':', ret)

    await go()
Example #11
0
async def test_user_stream():
    if not has_private_config:
        return

    client = Client(API_KEY, API_SECRET)

    with pytest.raises(UserStreamNotSubscribedException,
                       match='not subscribed'):
        await client.unsubscribe(SubType.USER)

    await client.subscribe(SubType.USER)
    await asyncio.sleep(.2)

    await client.unsubscribe(SubType.USER)

    await client.close()
Example #12
0
def bin_client() -> Client:
    """Instancia um objeto do tipo Client para utilizar a API
    da Binance. 'api_key' e 'api_secret' devem estar contidos
    num arquivo texto, de nome 'api.txt', da forma

    api_key
    api_secret

    sem pontuação e espaços.

    Returns:
        Client: objeto Client da API da Binance.
    """
    with open('api.txt', 'r') as f:
        linhas = f.readlines()
        key = linhas[0][:-1]
        pwd = linhas[1]

    return Client(api_key=key, api_secret=pwd)
async def test_force_params():
    payload = {
        'foo': 'bar'
    }

    client = Client()

    with aioresponses() as m:
        m.post(
            URL + '?foo=bar',
            payload=payload,
            status=200
        )

        res = await client.post(
            URL,
            foo='bar',
            force_params=True
        )

        assert res == payload
async def test_global_request_params():
    payload = {
        'foo': 'bar'
    }

    client = Client(
        request_params={
            'allow_redirects': True
        }
    )

    with aioresponses() as m:
        redirect(m)

        m.get(
            URL2,
            payload=payload,
            status=200
        )

        res = await client.get(URL)

        assert res == payload
Example #15
0
def client():
    return Client('api_key').start()
Example #16
0
def list_coins_binance(key, secret, type):

    api = Client(key, secret)

    tableaux = api.get_ticker()
    balances = api.get_account()

    data = {}
    balance_coins = []
    contents = []
    #print(balances['balances'][0]['free'])
    #####
    # Check coins availables with balances > 0.0
    #####
    for i in range(0, len(balances)):
        if float(balances['balances'][i]['free']) > 0.001 \
            and balances['balances'][i]['asset'] != 'BNB' \
            and balances['balances'][i]['asset'] != 'BTC':
            balance_coins.append(balances['balances'][i]['asset'])
    print('\n-----------------------Binance-------------------- \n')
    print('... Bags Holder ... \n')
    print(balance_coins)
    ###
    # Construct list of coins to trade with volume criteria
    ###
    for i in range(0, len(tableaux)):
        if type in tableaux[i]['symbol'][-4:]:
            #print(tableaux[i]['symbol'][-4:] + '------' +tableaux[i]['quoteVolume'])
            data[tableaux[i]['symbol']] = float(tableaux[i]['quoteVolume'])
            sorted_data = sorted(data.items(),
                                 key=operator.itemgetter(1),
                                 reverse=True)

    if int(read_config('binance', 'last_position')) > len(sorted_data):
        total = len(sorted_data)
    else:
        total = int(read_config('binance', 'last_position'))

    for i in range(int(read_config('binance', 'first_position')) - 1, total):
        #print(sorted_data[i][0][:-3] + '-----' + str(sorted_data[i][1]))
        contents.append(sorted_data[i][0][:-len(type)])
    results = contents
    print('------------- Coins top ------------- \n')
    print(results)
    all_contents = ''

    for result in balance_coins:
        all_contents += result + '\n'

    with open('bags_binance.txt', 'w', encoding='utf8') as f:
        f.write(all_contents)
    f.close()

    all_contents = ''

    for result in results:
        all_contents += result + '\n'

    with open('Choices_binance.txt', 'w', encoding='utf8') as f:
        f.write(all_contents)
    f.close()

    create_file_config(type)
Example #17
0
            sentMessage = False
    return sentMessage


def main():
    flag = True
    while flag:
        flag = getPrice()
        time.sleep(300)
    print("Exit the code")


parser = argparse.ArgumentParser(description="ETH price telegram bot")
parser.add_argument("--config",
                    "-c",
                    required=False,
                    help="Config yaml location")
args = parser.parse_args()

if __name__ == "__main__":
    config = load_config(args.config)
    api_id = config["telegram"]["api_id"]
    api_hash = config["telegram"]["api_hash"]
    bot_token = config["telegram"]["bot_token"]
    api_key = config["binance"]["api_key"]
    api_secret = config["binance"]["api_secret"]
    binance_client = Client(api_key, api_secret)
    client = TelegramClient("krishna", api_id,
                            api_hash).start(bot_token=bot_token)
    main()
Example #18
0
class Binance():
    def __init__(self,
                 api_key,
                 api_secret,
                 symbol: str,
                 base_instrument: str,
                 useTestNet: bool = False,
                 isLive: bool = False):

        self.isLive = isLive
        #self.previousBuy_price = 0.0
        self.client = Client(api_key, api_secret, testnet=useTestNet)

        # self.asset_balance = 0
        # self.base_instrument_balance = 10000.0

        self.pair = symbol + base_instrument
        print('Trading pair: ', self.pair)

        if self.isLive:
            account_info = self.client.get_account()
            print(list(account_info.items())[:9])

            if not useTestNet:
                trade_fees = self.client.get_trade_fee(
                    symbol=symbol.upper() +
                    base_instrument.upper())  ## this is a list of dict
                self.fees = trade_fees[0]['makerCommission']
                print('trading fees/commission = {} '.format(self.fees))

            self.asset_balance = self.client.get_asset_balance(
                asset=symbol.upper())["free"]
            self.base_instrument_balance = self.client.get_asset_balance(
                asset=base_instrument.upper())["free"]

            print('account balance, {} = '.format(symbol), self.asset_balance)
            print('account balance, {} = '.format(base_instrument),
                  self.base_instrument_balance)

    def get_historical_klines(self,
                              trading_pair: str,
                              interval,
                              from_date: str = None,
                              to_date: str = None) -> list:

        return self.client.get_historical_klines(trading_pair, interval,
                                                 from_date, to_date)

    def check_all_open_order(self, order_side):

        list_all_open_orders = self.client.get_open_orders(symbol=self.pair)
        n_order = 0
        for order in list_all_open_orders:
            if order['side'] == order_side and order['status'] == 'NEW':
                n_order += 1

        return n_order

    def execute_buy_order(order: 'Order', base_wallet: 'Wallet',
                          quote_wallet: 'Wallet', current_price: float,
                          options: 'ExchangeOptions',
                          clock: 'Clock') -> 'Trade':
        """Executes a buy order on the exchange.

        Parameters
        ----------
        order : `Order`
            The order that is being filled.
        base_wallet : `Wallet`
            The wallet of the base instrument.
        quote_wallet : `Wallet`
            The wallet of the quote instrument.
        current_price : float
            The current price of the exchange pair.
        options : `ExchangeOptions`
            The exchange options.
        clock : `Clock`
            The clock for the trading process..

        Returns
        -------
        `Trade`
            The executed trade that was made.
        """
        if order.type == TradeType.LIMIT and order.price < current_price:
            return None

        filled = order.remaining.contain(order.exchange_pair)

        if order.type == TradeType.MARKET:
            scale = order.price / max(current_price, order.price)
            filled = scale * filled

        commission = options.commission * filled
        quantity = filled - commission

        if commission.size < Decimal(10)**-quantity.instrument.precision:
            logging.warning(
                "Commission is less than instrument precision. Canceling order. "
                "Consider defining a custom instrument with a higher precision."
            )
            order.cancel("COMMISSION IS LESS THAN PRECISION.")
            return None

        transfer = Wallet.transfer(source=base_wallet,
                                   target=quote_wallet,
                                   quantity=quantity,
                                   commission=commission,
                                   exchange_pair=order.exchange_pair,
                                   reason="BUY")

        trade = Trade(order_id=order.id,
                      step=clock.step,
                      exchange_pair=order.exchange_pair,
                      side=TradeSide.BUY,
                      trade_type=order.type,
                      quantity=transfer.quantity,
                      price=transfer.price,
                      commission=transfer.commission)

        # n_order = self.check_all_open_order(SIDE_BUY)
        # if n_order>0: print(' ======>> There are more than {} existing buy orders, not placing further order'.format(n_order))

        if self.isLive:
            order = self.client.create_order(symbol=order.exchange_pair,
                                             side=SIDE_BUY,
                                             type=ORDER_TYPE_LIMIT,
                                             timeInForce=TIME_IN_FORCE_GTC,
                                             quantity=transfer.quantity,
                                             price=transfer.price)

            print('  =============== Placing buy order ============== \n',
                  order)
        else:
            order = self.client.create_test_order(
                symbol=order.exchange_pair,
                side=SIDE_BUY,
                type=ORDER_TYPE_LIMIT,
                timeInForce=TIME_IN_FORCE_GTC,
                quantity=transfer.quantity,
                price=transfer.price)

            print('  =============== Placing test buy order ============== \n',
                  order)

        return trade

    def execute_sell_order(order: 'Order', base_wallet: 'Wallet',
                           quote_wallet: 'Wallet', current_price: float,
                           options: 'ExchangeOptions',
                           clock: 'Clock') -> 'Trade':
        """Executes a sell order on the exchange.

        Parameters
        ----------
        order : `Order`
            The order that is being filled.
        base_wallet : `Wallet`
            The wallet of the base instrument.
        quote_wallet : `Wallet`
            The wallet of the quote instrument.
        current_price : float
            The current price of the exchange pair.
        options : `ExchangeOptions`
            The exchange options.
        clock : `Clock`
            The clock for the trading process..

        Returns
        -------
        `Trade`
            The executed trade that was made.
        """
        if order.type == TradeType.LIMIT and order.price > current_price:
            return None

        filled = order.remaining.contain(order.exchange_pair)

        commission = options.commission * filled
        quantity = filled - commission

        if commission.size < Decimal(10)**-quantity.instrument.precision:
            logging.warning(
                "Commission is less than instrument precision. Canceling order. "
                "Consider defining a custom instrument with a higher precision."
            )
            order.cancel("COMMISSION IS LESS THAN PRECISION.")
            return None

        # Transfer Funds from Quote Wallet to Base Wallet
        transfer = Wallet.transfer(source=quote_wallet,
                                   target=base_wallet,
                                   quantity=quantity,
                                   commission=commission,
                                   exchange_pair=order.exchange_pair,
                                   reason="SELL")

        trade = Trade(order_id=order.id,
                      step=clock.step,
                      exchange_pair=order.exchange_pair,
                      side=TradeSide.SELL,
                      trade_type=order.type,
                      quantity=transfer.quantity,
                      price=transfer.price,
                      commission=transfer.commission)

        # n_order = self.check_all_open_order(SIDE_SELL)
        # if n_order>0: print(' ======>> There are more than {} existing sell orders, not placing further order'.format(n_order))

        if self.isLive:
            order = self.client.create_order(symbol=order.exchange_pair,
                                             side=SIDE_SELL,
                                             type=ORDER_TYPE_LIMIT,
                                             timeInForce=TIME_IN_FORCE_GTC,
                                             quantity=transfer.quantity,
                                             price=transfer.price)
            print('  =============== Placing sell order ============== \n',
                  order)
        else:
            order = self.client.create_test_order(
                symbol=order.exchange_pair,
                side=SIDE_SELL,
                type=ORDER_TYPE_LIMIT,
                timeInForce=TIME_IN_FORCE_GTC,
                quantity=transfer.quantity,
                price=transfer.price)
            print(
                '  =============== Placing test sell order ============== \n',
                order)

        return trade

    def execute_order(order: 'Order', base_wallet: 'Wallet',
                      quote_wallet: 'Wallet', current_price: float,
                      options: 'Options', clock: 'Clock') -> 'Trade':
        """Executes an order on the exchange.

        Parameters
        ----------
        order : `Order`
            The order that is being filled.
        base_wallet : `Wallet`
            The wallet of the base instrument.
        quote_wallet : `Wallet`
            The wallet of the quote instrument.
        current_price : float
            The current price of the exchange pair.
        options : `ExchangeOptions`
            The exchange options.
        clock : `Clock`
            The clock for the trading process..

        Returns
        -------
        `Trade`
            The executed trade that was made.
        """
        kwargs = {
            "order": order,
            "base_wallet": base_wallet,
            "quote_wallet": quote_wallet,
            "current_price": current_price,
            "options": options,
            "clock": clock
        }

        if order.is_buy:
            trade = execute_buy_order(**kwargs)
        elif order.is_sell:
            trade = execute_sell_order(**kwargs)
        else:
            trade = None

        return trade
Example #19
0
import os
from dotenv import load_dotenv
load_dotenv()
from binance import Client
client = Client(os.getenv('API_KEY'), os.getenv('API_SECRET'))

details = client.get_max_margin_loan(asset='BTC')
print(details)
Example #20
0
def test_no_api_key():
    """create a client with no args"""
    Client()
Example #21
0
def parse_precision(precision: str, symbol: str) -> int:
    if precision == "Auto":
        symbol_info = Client().get_symbol_info(symbol)
        tickSize = float(symbol_info['filters'][0]['tickSize'])
        precision = abs(round(math.log(tickSize, 10)))
    return int(precision)
Example #22
0
"""
Initialization file.
"""
from binance import Client

from algobot.helpers import get_current_version, get_latest_version, get_logger

MAIN_LOGGER = get_logger(log_file='algobot', logger_name='algobot')

CURRENT_VERSION = get_current_version()
LATEST_VERSION = get_latest_version()

try:
    BINANCE_CLIENT = Client()
except Exception as e:
    MAIN_LOGGER.exception(repr(e))
    BINANCE_CLIENT = None
Example #23
0
def test_init_client_key():
    """create a client only with key"""
    Client('key')
Example #24
0
def test_init_client():
    """create a client with key and secret"""
    Client('key', 'secret')
Example #25
0
async def test_order_book():
    with aioresponses() as m:
        a00, b00, b01, a10 = [100, 10], [99, 100], [98, 2], [101, 3]
        asks = [a00]
        bids = [b00, b01]
        bids_sort = [b01, b00]

        asks1 = [a10, a00]
        asks1_sort = [a00, a10]

        client = Client('api_key')

        def preset_10():
            m.get(
                'https://api.binance.com/api/v3/depth?limit=100&symbol=BTCUSDT',
                payload=dict(lastUpdateId=10, asks=asks, bids=bids),
                status=200)

        def assert_state_a():
            assert orderbook.asks == asks
            assert orderbook.bids == bids_sort

        def preset_13():
            m.get(
                'https://api.binance.com/api/v3/depth?limit=100&symbol=BTCUSDT',
                payload=dict(lastUpdateId=13, asks=asks1, bids=bids),
                status=200)

        def assert_state_b():
            assert orderbook.asks == asks1_sort
            assert orderbook.bids == bids_sort

        def assert_state_c():
            assert orderbook.asks == [[95, 1], *asks1_sort]
            assert orderbook.bids == bids_sort

        print('\nround one  : normal initialization')

        preset_10()

        orderbook = OrderBook('BTCUSDT', client)

        assert not orderbook.ready
        await orderbook.updated()
        assert orderbook.ready

        assert_state_a()

        print(
            'round two  : wrong update, refetch, retry policy and finally fetched'
        )

        f = orderbook.updated()

        # wrong stream message,
        # and orderbook will fetch the snapshot again
        updated = orderbook.update(
            dict(
                # U=11 is missing
                U=12,
                u=13,
                a=[],
                b=[]))

        assert not updated
        assert not orderbook.ready

        await asyncio.sleep(0.5)
        # delay initialize preset b
        preset_13()

        await f
        assert orderbook.ready

        assert_state_b()

        # valid stream message
        assert orderbook.update(dict(U=14, u=15, a=[[95, 1]], b=[]))

        assert orderbook.asks == [[95, 1], *asks1_sort]

        print('round three: new update when still refetching')

        preset_13()

        f = orderbook.updated()

        updated = orderbook.update(
            dict(
                # U=16 is missing
                U=17,
                u=18,
                a=[],
                b=[]))

        assert not updated

        # orderbook is fetching
        updated = orderbook.update(dict(U=14, u=15, a=[[95, 1]], b=[]))

        assert not updated

        await f

        assert_state_c()

        print('round four : retry policy -> abandon')

        def no_retry_policy(fails):
            return True, 0

        orderbook.set_retry_policy(no_retry_policy)

        async def test_no_retry_policy():
            orderbook.update(dict(
                # U=16 is missing
                U=17,
                u=18,
                a=[],
                b=[]))

            exc = None

            try:
                await orderbook.updated()
            except Exception as e:
                exc = e

            assert exc is not None

            preset_13()

            await orderbook.fetch()

            assert orderbook.ready

            orderbook.update(dict(U=14, u=15, a=[[95, 1]], b=[]))

            assert_state_c()

        await test_no_retry_policy()

        print('round five : no retry policy')

        orderbook.set_retry_policy(None)

        await test_no_retry_policy()

        print('round six  : part of unsolved_queue is invalid')

        preset_10()
        # will fetch twice
        preset_10()

        def allow_retry_once(fails: int):
            if fails > 1:
                return True, 0

            return False, 0

        orderbook.set_retry_policy(allow_retry_once)

        # however, use private method, do not do this unless for testing

        orderbook._fetching = True

        asyncio.create_task(orderbook._fetch())

        f = orderbook.updated()

        # valid, but now is fetching
        orderbook.update(dict(U=11, u=12, a=[], b=[]))

        # invalid, and it will also clean the previous one
        orderbook.update(dict(U=14, u=15, a=[[95, 1]], b=[]))

        # orderbook will refetch

        orderbook.update(dict(U=11, u=12, a=[a10], b=[]))

        await f

        assert_state_b()
Example #26
0
# Functions
from analyse_tweet import analyse_tweet

load_dotenv()

# Api Keys
binance_api_key = os.getenv('BINANCE_API')
binance_api_secret = os.getenv('BINANCE_SECRET')
twitter_api_key = os.getenv('CONSUMER_KEY')
twitter_api_secret = os.getenv('CONSUMER_SECRET')
twitter_api_token = os.getenv('ACCESS_TOKEN')
twitter_api_secret_token = os.getenv('ACCESS_TOKEN_SECRET')

# Binance API
client = Client(binance_api_key, binance_api_secret)

# Twitter API
auth = tweepy.OAuthHandler(twitter_api_key, twitter_api_secret)
auth.set_access_token(twitter_api_token, twitter_api_secret_token)
twitter_api = tweepy.API(auth, wait_on_rate_limit=True)

# #
#  Check for new tweets
# #


def checkForNewTweet(twitter_api):
    print('🟢 Checking tweets..' + '\n')

    # Elon musk most recent tweet
Example #27
0
def account():
    client = Client(api_key, api_secret)
    info = client.get_account_snapshot(type='SPOT')
    info_data = json.dumps(info['snapshotVos'][1])
    print(info_data)
    return info_data
Example #28
0
from bot4binance import settings
import datetime
from binance import Client

client = Client(settings.APIKEY, settings.SECRET)
trades = client.get_my_trades(symbol='IOTABTC')

for trade in trades:
    etime = int(trade['time']) / 1000
    tradetime = datetime.datetime.fromtimestamp(etime)
    print("Time: {} | Price: {} | Quantity: {} | Commission: {}".format(
        str(tradetime), trade['price'], trade['qty'], trade['commission']))
def historical_klines(symbol, interval, start_str, end_str=None):
    """Get Historical Klines from Binance

    See dateparse docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/

    If using offset strings for dates add "UTC" to date string e.g. "now UTC", "11 hours ago UTC"

    :param symbol: Name of symbol pair e.g BNBBTC
    :type symbol: str
    :param interval: Biannce Kline interval
    :type interval: str
    :param start_str: Start date string in UTC format
    :type start_str: str
    :param end_str: optional - end date string in UTC format
    :type end_str: str

    :return: list of OHLCV values

    """
    # create the Binance client, no need for api key
    client = Client("", "")

    # init our list
    output_data = []

    # setup the max limit
    limit = 500

    # convert interval to useful value in seconds
    timeframe = interval_to_milliseconds(interval)

    # convert our date strings to milliseconds
    start_ts = date_to_milliseconds(start_str)

    # if an end time was passed convert it
    end_ts = None
    if end_str:
        end_ts = date_to_milliseconds(end_str)

    idx = 0
    # it can be difficult to know when a symbol was listed on Binance so allow start time to be before list date
    symbol_existed = False
    while True:
        # fetch the klines from start_ts up to max 500 entries or the end_ts if set
        temp_data = client.klines(symbol=symbol,
                                  interval=interval,
                                  limit=limit,
                                  startTime=start_ts,
                                  endTime=end_ts)

        # handle the case where our start date is before the symbol pair listed on Binance
        if not symbol_existed and len(temp_data):
            symbol_existed = True

        if symbol_existed:
            # append this loops data to our output data
            output_data += temp_data

            # update our start timestamp using the last value in the array and add the interval timeframe
            start_ts = temp_data[len(temp_data) - 1][0] + timeframe
        else:
            # it wasn't listed yet, increment our start date
            start_ts += timeframe

        idx += 1
        # check if we received less than the required limit and exit the loop
        if len(temp_data) < limit:
            # exit the while loop
            break

        # sleep after every 3rd call to be kind to the API
        if idx % 3 == 0:
            time.sleep(1)

    return output_data
Example #30
0
import configparser
from binance.enums import *
from binance import Client
import datetime
import requests
import json

config = configparser.ConfigParser()
config.read('C:/Users/HP/Desktop/Dev/Binance_telegran/config.ini')

api_key = config['BINACE_API']['api_key']
api_secret = config['BINACE_API']['secret_key']

client = Client(api_key, api_secret)

try:
    secret = (config['taapi_io']['secret_key'])
except Exception as e:
    print(e)


def rsi_return():
    with open('C:/Users/HP/Desktop/Dev/Binance_telegran/telegram/moeda.txt',
              'r') as flag_moeda:
        moeda_ = flag_moeda.readline()
        moeda = moeda_.replace('BRL', '/BRL')
    endpoint = 'https://api.taapi.io/rsi'
    parameters = {
        'secret': secret,
        'exchange': 'binance',
        'symbol': moeda,