示例#1
0
    def populate_binance_symbols():

        from website import config
        from binance.client import Client
        from .models import Symbol_binance, Trading
        from .extensions import db

        cryptos = Symbol_binance.query.all()
        symbol_list = [crypto.symbol for crypto in cryptos]

        # Login to Client
        client = Client(api_key=config.api_key, api_secret=config.api_secret)
        client2 = Client(api_key=config.api_key2,
                         api_secret=config.api_secret2)

        # Set Test-URL in case of testnet.binance
        if config.test_mode:
            client.API_URL = config.API_URL_BINANCE
        else:
            client2.API_URL = config.API_URL_BINANCE

        exchange_info = client.get_exchange_info()
        print(exchange_info['symbols'])

        trading_id = db.session.query(Trading).filter(
            Trading.trading == "CRT").first().id

        symbols = exchange_info['symbols']
        for symbol in symbols:

            try:
                if symbol['status'] == 'TRADING' and symbol[
                        'symbol'] not in symbol_list:
                    new_crypto = Symbol_binance(symbol=symbol['symbol'],
                                                name=symbol['baseAsset'],
                                                trading_id=trading_id)
                    db.session.add(new_crypto)
                    db.session.commit()
                    print(f"Added a new crypto: {symbol['symbol']}")
                else:
                    print(f"Crypto already existing, skip: {symbol['symbol']}")
            except Exception as e:
                print(f"Exception: {symbol['symbol']}")
        print("...populated cryptos...")
示例#2
0
def get_hist_indicator(ma_period):
    """Get historical values of indicator on booting
    """
    my_mod = Client(Config.API_KEY, Config.API_SECRET)
    my_mod.API_URL = Config.API_URL
    candlesticks = my_mod.get_historical_klines("BTCUSDT",
                                                my_mod.KLINE_INTERVAL_5MINUTE,
                                                "1 Apr, 2021", "29 Apr, 2022")
    processed_candlesticks = []
    ndict = {'time': [], 'close': []}
    for data in candlesticks:
        ndict['time'].append(data[0] / 1000)
        ndict['close'].append(float(data[4]))

    df = pd.DataFrame(ndict)
    df.drop(df.tail(1).index, inplace=True)
    ndf = df.tail(ma_period).to_dict('list')

    return ndf
# used for executing the code
from itertools import count

# we use it to time our parser execution speed
from timeit import default_timer as timer

# get binance key and secret from environment variables
api_key = os.getenv('binance_api_stalkbot_testnet')
api_secret = os.getenv('binance_secret_stalkbot_testnet')

# Authenticate with the client
client = Client(api_key, api_secret)

# The API URL is manually changed in the library to work on the testnet
#client.API_URL = 'https://testnet.binance.vision/api'
client.API_URL = os.getenv('binance_api_url_testnet')

# get vars
from botvars import *

# coins that bought by the bot since its start
coins_in_hand = {}
# initializing the volumes at hand
for coin in keywords:
    coins_in_hand[coin] = 0

# current price of CRYPTO pulled through the websocket
CURRENT_PRICE = {}


def ticker_socket(msg):
示例#4
0
文件: binance.py 项目: ofucik/binance
import os

from binance.client import Client
from binance.client import Client
from binance.websockets import BinanceSocketManager
from twisted.internet import reactor

api_key = "WK8dITaZRDlJ2DRSjxZdrHbuvMRhSafCls8WdhGrmNArF3FoSxUmjlto3iTOvWDU"
api_secret = "acEjoqKOJ0TNlVYoZgDYrKVIYvStBfxAmCJG90rj3GYi7jlOJzwqqcAeLcLZN4BK"

client = Client(api_key, api_secret)

client.API_URL = 'https://testnet.binance.vision/api'
#print(client.get_asset_balance(asset='ETH'))
print(client.get_account())

try:
    order = client.create_order(
        symbol='ETHUSDT',
        side=Client.SIDE_BUY,
        type=Client.ORDER_TYPE_MARKET,
        quantity=1,
    )

except BinanceAPIException as e:
    # error handling goes here
    print(e)
except BinanceOrderException as e:
    # error handling goes here
    print(e)
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
from binance.client import Client
import configparser
from binance.websockets import BinanceSocketManager
import time
import os

##############################################################################
# Loading keys from config file
api_key = os.environ.get('binance_api')
api_secret = os.environ.get('binance_secret')

#api_key,
client = Client(api_key, api_secret)
client.API_URL = 'https://api.binance.us/api'

# Setting up connection

# Getting account info to check balance
info = client.get_account()  # Getting account info

# Saving different tokens and respective quantities into lists
assets = []
values = []
for index in range(len(info['balances'])):
    for key in info['balances'][index]:
        if key == 'asset':
            assets.append(info['balances'][index][key])
        if key == 'free':
            values.append(info['balances'][index][key])
            if x not in event.message.message:
                continue
            else:
                for y in dictionary['wordsForConfirmation']:
                    if y in event.message.message:
                        flag =True
                        coinToBuy = x
                        print(x)
                        buy(coinToBuy)
                        break
                    else:
                        continue
                break

if __name__ == '__main__':

    stream = open("config.yaml", 'r')
    dictionary = yaml.load(stream, Loader=yaml.FullLoader)

    if dictionary['testnet']:
        binanceClient = Client(dictionary['TEST_API_KEY'], dictionary['TEST_API_SECRET'])
    else:
        binanceClient = Client(dictionary['LIVE_API_KEY'], dictionary['LIVE_API_SECRET'])

    if dictionary['testnet']:
        binanceClient.API_URL = dictionary['testnet_URL']

    client = TelegramClient(dictionary['bot_token'], dictionary['api_id'], dictionary['api_hash']).start()
    bsm = BinanceSocketManager(binanceClient)
    checkMessage(client)
    client.run_until_disconnected()
示例#7
0
from binance.websockets import BinanceSocketManager
import time

##############################################################################
# Loading keys from config file
config = configparser.ConfigParser()
config.read_file(
    open(
        '/home/venom/GitHub/blog_code/building_cryptocurrency_dashboard_plotly_binanceAPI/secret.cfg'
    ))
test_api_key = config.get('BINANCE', 'TEST_API_KEY')
test_secret_key = config.get('BINANCE', 'TEST_SECRET_KEY')

# Setting up connection
client = Client(test_api_key, test_secret_key)
client.API_URL = 'https://testnet.binance.vision/api'  # To change endpoint URL for test account

# Getting account info to check balance
info = client.get_account()  # Getting account info

# Saving different tokens and respective quantities into lists
assets = []
values = []
for index in range(len(info['balances'])):
    for key in info['balances'][index]:
        if key == 'asset':
            assets.append(info['balances'][index][key])
        if key == 'free':
            values.append(info['balances'][index][key])

token_usdt = {}  # Dict to hold pair price in USDT
示例#8
0
from binance.websockets import BinanceSocketManager
from twisted.internet import reactor

try:
    API_URL = os.environ['BINANCE_API_URL']
    API_KEY = os.environ['BINANCE_API_KEY']
    API_SECRET = os.environ['BINANCE_SECRET_KEY']
    TICKERS = split_strip(os.environ.get('TICKERS', ''))
    PRICE_ALERTS = split_strip(os.environ.get('PRICE_ALERTS', ''))
    DATA_PATH = os.environ['DATA_PATH']
except KeyError as er:
    print('Missing env var %s', er)
    sys.exit(1)

client = Client(API_KEY, API_SECRET)
client.API_URL = API_URL
bm = BinanceSocketManager(client)

def validate_tickers():
    print(f'Validating tickers {TICKERS}')
    valid_tickers = set([it['symbol']for it in client.get_all_tickers()])

    invalid_tickers = set(TICKERS) - valid_tickers
    if invalid_tickers:
        print(f'Invalid or unsupported ticker {invalid_tickers}')
        sys.exit(1)

def setup_ticker_files():
    print(f'Setting up files for {TICKERS}')
    ticker_files = {}
示例#9
0
def bnb_to_wish():
    client = Client(BINANCE_PAYMENT_ADDRESS, BINANCE_PAYMENT_PASSWORD)
    client.API_URL = 'https://dex.binance.org/api'
    wish_price = client.get_ticker(symbol='WISH-2D5_BNB')[0]['lastPrice']
    return 1 / float(wish_price)
示例#10
0
from binance.client import Client
from binance.enums import *

BINANCE_API = ''
BINANCE_SECRET = ''

TEST_BINANCE_API = ''
TEST_BINANCE_SECRET = ''

# for testnet trading
TEST_CLIENT = Client(TEST_BINANCE_API, TEST_BINANCE_SECRET)
TEST_CLIENT.API_URL = 'https://testnet.binance.vision/api'
# test_socket = "wss://testnet.binance.vision/ws/bnbusdt@kline_1m"

# for real trading and prices
CLIENT = Client(BINANCE_API, BINANCE_SECRET)
SOCKET = "wss://stream.binance.com:9443/ws/bnbusdt@kline_1m"

# global variables
BASE = "BNB"
QUOTE = "USDT"
SYMBOL = BASE + QUOTE
LEVER = 2
示例#11
0
#   Need defaults to load basic data
MA_PERIOD = 400
TRADE_SYMBOL = 'BTCUSDT'

hist_data = gt.get_hist_indicator(MA_PERIOD)
in_position = False
side = ''
with open('static/data.json') as json_file:
    data = json.load(json_file)
previous_boot_data = data['sys_config'][-1]
last_params = [
    previous_boot_data['ma_period'], previous_boot_data['ma_up'],
    previous_boot_data['ma_dn'], previous_boot_data['risk']
]
client = Client(Config.API_KEY, Config.API_SECRET)
client.API_URL = Config.API_URL


def order(side, quantity, symbol, order_type=ORDER_TYPE_MARKET):
    #   Prepare and send trade order.
    #   Return boolean value for in_trade variable,
    #   to control trade status.

    try:
        print("Sending order")
        order = client.create_order(symbol=symbol,
                                    side=side,
                                    type=order_type,
                                    quantity=quantity)
        pprint.pprint(order)
示例#12
0
    def populate_binance_symbol_prices():

        from website import config
        from binance.client import Client
        import tulipy, numpy
        from datetime import date, datetime
        from .models import Symbol_binance, Symbol_binance_price
        from .extensions import db
        # https://www.youtube.com/watch?v=Ni8mqdUXH3g

        cryptos = Symbol_binance.query.all()

        symbols = []
        crypto_dict = {}
        for crypto in cryptos:
            symbol = crypto.symbol
            symbols.append(symbol)
            crypto_dict[symbol] = crypto.id

        # Login to Client
        client = Client(api_key=config.api_key, api_secret=config.api_secret)
        client2 = Client(api_key=config.api_key2,
                         api_secret=config.api_secret2)

        # Set Test-URL in case of testnet.binance
        if config.test_mode:
            client.API_URL = config.API_URL_BINANCE
        else:
            client2.API_URL = config.API_URL_BINANCE

        current_date = date.today().isoformat()
        print(current_date)

        for symbol in symbols:
            candlesticks = client2.get_historical_klines(
                symbol, Client.KLINE_INTERVAL_1DAY, "1 Jan, 2012",
                current_date)

            recent_closes = []
            crypto_id = crypto_dict[symbol]

            date = db.session.query(func.max(
                Symbol_binance_price.date)).filter(
                    Symbol_binance_price.crypto_id == crypto_id).scalar()
            print(f"Date_max 1: {date}")

            try:
                max_date = datetime.strptime(date,
                                             '%Y-%m-%d').date().isoformat()
            except Exception as e:
                # print(f"No data {e}")
                max_date = datetime.strptime('2000-01-01',
                                             '%Y-%m-%d').date().isoformat()
            print(f"Date_max 2: {max_date}")

            for candlestick in candlesticks:
                close = candlestick[4]  # close
                recent_closes.append(float(close))

                close_time = candlestick[6]  # timestamp unix
                bar_date = datetime.fromtimestamp(int(
                    close_time / 1000)).strftime('%Y-%m-%d')

                if bar_date > max_date and bar_date < current_date:
                    sma_20, sma_50, rsi_14 = None, None, None

                    if len(recent_closes) > 20:
                        sma_20 = tulipy.sma(numpy.array(recent_closes),
                                            period=20)[-1]

                    if len(recent_closes) > 50:
                        sma_50 = tulipy.sma(numpy.array(recent_closes),
                                            period=50)[-1]

                    if len(recent_closes) > 14:
                        rsi_14 = tulipy.rsi(numpy.array(recent_closes),
                                            period=14)[-1]

                    try:

                        # open_time = candlestick[0] # timestamp unix
                        open = candlestick[1]  # open
                        high = candlestick[2]  # high
                        low = candlestick[3]  # low
                        # close = candlestick[4] # close
                        volume = candlestick[5]  # volume
                        # close_time = candlestick[6] # timestamp unix
                        # quote_asset_volume = candlestick[7] # timestamp unix
                        # number_of_trades = candlestick[8] # timestamp unix
                        # taker_buy_base_asset_volume = candlestick[9] # timestamp unix
                        # taker_buy_quote_asset_volume = candlestick[10] # timestamp unix

                        new_crypto_price = Symbol_binance_price(
                            crypto_id=crypto_id,
                            date=bar_date,
                            open=open,
                            high=high,
                            low=low,
                            close=close,
                            volume=volume,
                            sma_20=sma_20,
                            sma_50=sma_50,
                            rsi_14=rsi_14)
                        db.session.add(new_crypto_price)
                        print(f"added price to {symbol}")

                    except Exception as e:
                        print(f"No stock-price added {e}")

            db.session.commit()
        print("...populated crypto prices...")