Пример #1
0
def checkArbitrage(token):
    """ usdt -> eth -> token -> btc -> usdt 
        returns the one to one value of your investment after running through the trades outlined above
        if the value is greater than one then there is profit to be made through arbitrage
    """
    
    return 1/float(binance.prices()['ETHUSDT'])*FEE*1/float(binance.prices()[token+'ETH'])*FEE*float(binance.prices()[token+'BTC'])*FEE*float(binance.prices()['BTCUSDT'])
Пример #2
0
def sellPump(boughtPrice):
    # big function
    data = []
    data.append(float(binance.prices()[symbol]))
    for num in range(constants.MAXTIME):
        if num == 0:
            continue
        data.append(float(binance.prices()[symbol]))
        if calculateProfit(data[num], boughtPrice) >= constants.IDEALPROFIT:
            binance.order(symbol,
                          binance.SELL,
                          (btcBalance * constants.PERCENT) / boughtPrice,
                          data[num] * 0.98,
                          binance.LIMIT,
                          binance.GTC,
                          test=True)
            break
        # other stuff
        time.sleep(1)

    success = 'success' if len(data) < constants.MAXTIME else 'fail'
    print(success)
    currentPrice = binance.prices()[symbol]
    # check after a minute
    return
Пример #3
0
def gbp_to_base(gbp, symbol):
    """
    50GBP => OMG
    50GBP => USD
    USD => BTC
    BTC => OMG
    """

    usd = gbp * CURRENCY.get_rate("GBP", "USD")
    btc = usd * float(binance.prices()["BTCUSDT"])
    omg = btc * float(binance.prices()[symbol + "BTC"])
    return format(omg, ".20f")
Пример #4
0
def main():
    """
    Main method
    """
    if sys.argv[1] == "--help":
        print("Usage: {} <pair> <side>".format(sys.argv[0]))
        sys.exit(0)
    if len(sys.argv) < 3:
        print("Usage: {} <pair> <side>".format(sys.argv[0]))
        sys.exit(1)
    pair = sys.argv[1]
    side = sys.argv[2]
    base_amount = 3000
    account = config.accounts.binance[0]
    binance_auth(account)
    base = get_base(pair)

    if side == 'OPEN':
        result = binance.margin_borrow(base, base_amount)
        print("Borrow result: {}".format(result))
        quote_amount = 100/float(binance.prices()[pair])
        precise_amount = get_step_precision(pair, quote_amount)
        result = binance.margin_order(symbol=pair, side='BUY', quantity=precise_amount,
                                      orderType=binance.MARKET)

        print("Buy result: {}".format(result))
    elif side == 'CLOSE':
        result = binance.margin_order(symbol=pair, side='SELL', quantity=precise_amount,
                                      orderType=binance.MARKET)
        print("Sell result: {}".format(result))
        result = binance.margin_repay(base, base_amount)

        print("Repay result: {}".format(result))
    else:
        print('Unknown side: {}'.format(side))
Пример #5
0
def testforNumberErrors():
    list = binance.balances()
    for sym in list:
        if (sym == "USDT" or sym == "BTC"): continue

        sym = sym + "BTC"

        pof = float(binance.prices()[sym])
        if (btcBalance < pof):
            are = float(
                main.calcAmountNeeded(pof, btcBalance, constants.PERCENT))
            are = des(are, TRUNCATE, 3, DECIMAL_PLACES)
        else:
            are = int(main.calcAmountNeeded(pof, btcBalance,
                                            constants.PERCENT))

        try:

            pof = des(pof, TRUNCATE, 8, DECIMAL_PLACES)
            binance.order(sym,
                          binance.BUY,
                          are,
                          pof,
                          binance.LIMIT,
                          binance.GTC,
                          test=True)
        except Exception as e:
            print(e)
            print(sym)
        finally:
            time.sleep(1)
            print(sym)

    return
Пример #6
0
def get_balances():
    balances = binance.balances()
    prices = binance.prices()
    epoch = time.time()
    data_balances = {"balances": balances, "date": epoch}
    data_prices = {"prices": prices, "date": epoch}
    balancesCollection.insert_one(data_balances)
    pricesCollection.insert_one(data_prices)
    print("inserted data")
Пример #7
0
def update_prices(coins):
    prices = binance.prices()
    for c in coins:
        price = prices.get(c.name)
        c.add_price(price)
        # Coins have their own average function
        c.sma()
        # Changes average out of scientific notation
        printaverage="{0:0.8f}".format(c.average)
        print("Coin: {}, SMA: {}, Current Price: {}".format(c.name, printaverage, price))
Пример #8
0
def profit_calculator(market_type):

    try:
        for error in b.myTrades(market_type):
            if error == "msg":
                if "ETH" not in market_type:
                    market_type.replace("BTC", "ETH")
                else:
                    market_type.replace("ETH", "BTC")
        trade_data = b.myTrades(market_type)
        #trade_data return example
        #[{u'orderId': 46584195, u'isBuyer': True, u'price': u'0.00000927', u'isMaker': True, u'qty': u'900.00000000', u'commission': u'0.90000000', u'time': 1525044165320, u'commissionAsset': u'TRX', u'id': 25242895, u'isBestMatch': True}]
        index = 0
        total_bought_revenue = float(0)
        total_bought_qty = float(0)
        bought_price = float(0)
        while len(trade_data) > index:
            if trade_data[index]["isBuyer"] == True and int(
                    trade_data[index]['time']) >= trade_after_this_date:
                bought_price = float(trade_data[index]["price"])

            if trade_data[index]["isMaker"] == True and int(
                    trade_data[index]['time']) >= trade_after_this_date:
                bought_price = -float(trade_data[index]["price"])

            bought_qty = float(trade_data[index]["qty"])
            total_bought_qty += bought_qty
            bought_revenue = bought_price * bought_qty

            total_bought_revenue += bought_revenue
            index += 1

        avg_bought_price = (total_bought_revenue / total_bought_qty) * float(
            1.02)  #0.02 is for comission

        if avg_bought_price >= float(0.000001):
            avg_bought_price = float(0)

        #getting price for specific coin
        current_price = float(b.prices()[market_type])

        #calculating profit is percentage
        profit = ((current_price / avg_bought_price) - 1) * 100

        # print "%s profit is "%market_type + str(profit) +str(" %")
        if market_type not in summary:
            summary.append(market_type)
        if profit not in profit_list:  #problem : this makes error if prices changes very quickly!
            profit_list.append(profit)

        return market_type, profit

    except ZeroDivisionError as Zero_Division_Error:
        return str("Try_different_market")
Пример #9
0
def main():
    """ Main function """

    if len(sys.argv) > 1 and sys.argv[1] == '--help':
        print("Get current trade status")
        print("Usage {} [pair] [interval]".format(sys.argv[0]))
        sys.exit(0)

    test = sys.argv[2].lower() == "test"
    prices = binance.prices()
    binance_auth()
    dbase = Mysql(test=test, interval=sys.argv[1])

    trades = dbase.get_trades()
    profits = []
    percs = []
    print("\033[1m")  # BOLD
    print("pair buy_price current_price amount in_profit percentage profit")
    print("\033[0m")  # END

    details = []
    for trade in trades:
        pair = trade[0]
        current_price = float(prices[pair])
        trade_details = dbase.get_trade_value(pair)
        buy_price = float(trade_details[0][0])
        amount = float(trade_details[0][1])
        profit = (current_price / 0.00014 * amount) - (buy_price / 0.00014 *
                                                       amount)
        perc = 100 * (current_price - buy_price) / buy_price

        profits.append(profit)
        percs.append(perc)
        perc = float(format(perc, ".4f"))
        profit = float(format(profit, ".4f"))
        details.append(
            (pair, format(float(buy_price), ".20f"),
             format(float(current_price),
                    ".20f"), amount, current_price > buy_price, perc, profit))

    details = sorted(details, key=itemgetter(-2))
    for item in details:
        print("{0} {1} {2} {3} {4} {5} {6}".format(*item))

    print(
        "\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\n\n\n"
    )
    count = len(profits)
    count = 1 if count == 0 else count
    print("Total_profit: {0} Avg_Profit: {1} Avg_Percs: {2} count: {3}".format(
        sum(profits),
        sum(profits) / count,
        sum(percs) / count, count))
Пример #10
0
def initialize_coins():
    coins=[]

    # gives a dictionary which coin name as key and price as value
    prices = binance.prices()
    coinNames = list(prices.keys())
    for c in coinNames:
        # Create coin and add starting price
        tmpcoin = coin(c)
        tmpcoin.add_price(prices.get(c))
        coins.append(tmpcoin)
    return coins
def write_price():
    """writing prices to csv files"""
    data = binance.prices()  # calling prices
    print(int(time.time() * 1000))
    print(data)
    for each_market in data:
        # outputs "binance time" in miliseconds
        write_price.time_index = int(time.time() * 1000)
        current_price = float(data['%s' % each_market])
        with open('./csv_data/%s.csv' % each_market, 'a') as f:
            wr = csv.writer(f)
            wr.writerow([write_price.time_index, current_price])
Пример #12
0
def prod_loop(interval, test_trade):
    """
    Loop through collection cycle (PROD)
    """
    main_indicators = config.main.indicators.split()
    pairs = config.main.pairs.split()

    LOGGER.debug("Performaing prod loop")
    LOGGER.info("Pairs in config: %s", pairs)
    LOGGER.info("Total unique pairs: %s", len(pairs))

    max_trades = int(config.main.max_trades)

    LOGGER.info("Starting new cycle")
    LOGGER.debug("max trades: %s", max_trades)

    prices = binance.prices()
    prices_trunk = {}
    for key, val in prices.items():
        if key in pairs:
            prices_trunk[key] = val
    dataframes = get_dataframes(pairs, interval=interval)

    redis = Redis(interval=interval, test=False)
    engine = Engine(prices=prices_trunk,
                    dataframes=dataframes,
                    interval=interval,
                    redis=redis)
    engine.get_data(localconfig=main_indicators, first_run=False)
    buys = []
    sells = []
    for pair in pairs:
        result, current_time, current_price, _ = redis.get_action(
            pair=pair, interval=interval)

        if result == "BUY":
            LOGGER.debug("Items to buy")
            buys.append((pair, current_time, current_price))
        if result == "SELL":
            LOGGER.debug("Items to sell")
            sells.append((pair, current_time, current_price))
    trade = Trade(interval=interval, test_trade=test_trade, test_data=False)
    trade.sell(sells)
    trade.buy(buys)
    del engine
    del redis
Пример #13
0
def main():
    """ main function """

    if len(sys.argv) > 1 and sys.argv[1] == '--help':
        print("Sell a particular trade immediately")
        print("Usage {} [pair] [interval] [test_trade] [test_data]".format(sys.argv[0]))
        sys.exit(0)

    binance_auth()
    pair = sys.argv[1]
    interval = sys.argv[2]

    test_trade = bool(len(sys.argv) > 3 and sys.argv[3] == "test")
    test_data = bool(len(sys.argv) > 3 and sys.argv[4] == "test")
    current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
    current_price = binance.prices()[pair]
    print(current_time, current_price)

    sells = []
    trade = Trade(interval=interval, test_data=test_data, test_trade=test_trade)
    sells.append((pair, current_time, current_price))
    trade.sell(sells)
Пример #14
0
def prod_initial(interval, test=False):
    """
    Initial prod run - back-fetching data for tech analysis.
    """
    prices = binance.prices()
    prices_trunk = {}
    pairs = config.main.pairs.split()

    for key, val in prices.items():
        if key in pairs:
            prices_trunk[key] = val

    redis = Redis(interval=interval, test=test)
    main_indicators = config.main.indicators.split()
    dataframes = get_dataframes(pairs, interval=interval)
    engine = Engine(prices=prices_trunk,
                    dataframes=dataframes,
                    interval=interval,
                    test=test,
                    redis=redis)
    engine.get_data(localconfig=main_indicators, first_run=True)
    del redis
Пример #15
0
def prod_int_check(interval, test):
    """Check price between candles for slippage below stoploss"""
    prices = binance.prices()
    dbase = Mysql(test=False, interval=interval)
    current_trades = dbase.get_trades()
    redis = Redis(interval=interval, test=False, db=0)
    current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
    sells = []
    for trade in current_trades:
        pair = trade[0]
        buy_price = dbase.get_trade_value(pair)[0][0]
        result, current_time, current_price = redis.get_intermittant(
            pair, buy_price=buy_price, current_price=prices[pair])
        buy_price = dbase.get_trade_value(pair)[0][0]
        LOGGER.debug("%s int check result: %s Buy:%s Current:%s Time:%s", pair,
                     result, buy_price, current_price, current_time)
        if result == "SELL":
            LOGGER.debug("Items to sell")
            sells.append((pair, current_time, current_price))

    trade = Trade(interval=interval, test_trade=test, test_data=False)
    trade.sell(sells)
    del redis
    del dbase
Пример #16
0
#this is a bridge between binance api and lpmbot. please write binance API details in here
#https://github.com/toshima/binance this is the link to the binance api i`m using
import binance
import sys 
binance.set("API", "SECRET")
# api first and then secret

if sys.argv[ 1 ] == ("prices"):
    print(binance.prices())
elif sys.argv[ 1 ] == ("balances"):
     
   print(binance.balances())
else:
    print ("Please write a valid argument")
	
	
	



Пример #17
0
def binance_summary():

    # instead of having the API in the script..not a perfect solution
    sign_key, sign_SECRET = get_credentials('binance_api')

    api_info = {
        'sign_key': sign_key,
        'sign_SECRET': sign_SECRET,
        'sign_id': 'anyone',
        'coin_symbol': 'ZEC',
    }

    binance.set(api_info['sign_key'], api_info['sign_SECRET'])
    relation = {'ZEC': 'ZECBTC', 'BTC': 'BTCUSDT'}

    prices = binance.prices()
    balances = binance.balances()

    btc_price = float(prices['BTCUSDT'])
    # print ("The current Bitcoin price is $ {0:.2f}").format(btc_price)
    print

    # print float(prices['ZECBTC'])

    # cycle thru all coins balances
    for key in balances.keys():

        # if balance is greater than 0, display balance info
        if float(balances[key]['free']) > 0:

            # determine 'free' balance
            balance_coin = float(balances[key]['free'])

            # handle BTC different because other coins are based on BTC
            if key == 'BTC':

                # determine the coins current price
                coin_price = float(prices[relation[key]])

                # calculate the coin balance in USD
                balance_usd = balance_coin * float(prices[relation[key]])

                # display information to screen
                template = ("The {0} price is currently $ {1:.2f}")
                print template.format(key, coin_price)

            else:

                # calculate the price of the coin in USD not BTC
                coin_price = float(prices[relation[key]]) * btc_price

                # calculate the coin balance in USD
                balance_usd = (float(prices[relation[key]]) * balance_coin *
                               btc_price)

                # display information to screen
                template = ("The {0} price is currently $ {1:.2f}")
                print template.format(key, coin_price)

            print("\n\tYour {0} balance is {1}").format(key, balance_coin)
            print("\tYour {0} balance is worth $ {1:.2f}".format(
                key, balance_usd))
            print
Пример #18
0
def executeTrades(token):
    """
    carries out the trades identified and specified in checkArbitrage(token)
    
    Flooring and rounding is used in the quantity calculations so as to make sure that the amount
    matches the step size and minimum quantities required by binance for the given asset
    """
    binance.marketBuy("ETHUSDT", binance.BUY, round(math.floor(100000*int(float(binance.balances()["USDT"]['free'])))*1/float(binance.prices()["ETHUSDT"]) / 100000, 5), test=False)
    binance.marketBuy(token+"ETH", binance.BUY, math.floor((10**getDigits(token)*int(float(binance.balances()["ETH"]['free'])*1/float(binance.prices()[token+"ETH"]))))/(10**getDigits(token)), test=False)
    binance.marketBuy(token+"BTC", binance.SELL, math.floor((10**getDigits(token))*float(binance.balances()[token]["free"]))/(10**getDigits(token)), test=False)
    binance.marketBuy("BTCUSDT", binance.SELL, math.floor(float(binance.balances()["BTC"]['free'])*1000000) / 1000000, test=False) # precision will always be 10^6 for BTC
Пример #19
0
def get_binance_values():
    """Get totals for each crypto from binance and convert to USD/GBP"""

    mydict = lambda: defaultdict(mydict)
    result = mydict()
    binance_auth()
    all_balances = binance.balances()
    prices = binance.prices()
    bitcoin_totals = 0
    gbp_total = 0
    usd_total = 0
    currency = CurrencyRates()

    for key in all_balances:
        current_value = float(all_balances[key]["free"]) + float(
            all_balances[key]["locked"])

        if float(current_value) > 0:  # available currency
            result["binance"][key]["count"] = current_value

            if key == "BTC":
                bcoin = float(current_value)
                bitcoin_totals += float(bcoin)

            elif key == "USDT":
                bcoin = float(current_value) / float(prices["BTCUSDT"])
                bitcoin_totals += bcoin

            else:  # other currencies that need converting to BTC
                try:
                    bcoin = float(current_value) * float(
                        prices[key + "BTC"])  # value in BTC
                    bitcoin_totals += bcoin
                except KeyError:
                    LOGGER.critical("Error: Unable to quantify currency: %s ",
                                    key)
                    continue

            add_value(key, bcoin)
            usd2gbp = lambda: currency.get_rate("USD", "GBP")

            usd = bcoin * float(prices["BTCUSDT"])
            gbp = usd2gbp() * usd
            usd_total += usd
            gbp_total += gbp
            result["binance"][key]["BTC"] = bcoin
            result["binance"][key]["USD"] = usd
            result["binance"][key]["GBP"] = gbp

    usd_total = bitcoin_totals * float(prices["BTCUSDT"])
    result["binance"]["TOTALS"]["BTC"] = bitcoin_totals
    result["binance"]["TOTALS"]["USD"] = usd_total
    result["binance"]["TOTALS"]["count"] = ""
    for _ in range(3):
        # Try to get exchange rate 3 times before giving up
        try:
            gbp_total = currency.get_rate("USD", "GBP") * usd_total
        except RatesNotAvailableError:
            continue
        break
    result["binance"]["TOTALS"]["GBP"] = gbp_total
    add_value("USD", usd_total)
    add_value("GBP", gbp_total)

    return default_to_regular(result)
Пример #20
0
def get_current_price(pair):
    """Get current price from binance"""
    prices = binance.prices()
    return prices[pair]
Пример #21
0
secret = 'add secrect'
binance.set(api_key, secret)  # setting up

boughtCryptos = {}

# reterives my btc balance
btcBalance = float(binance.balances()["BTC"]['free'])
print("Your bitcoin balance is %s" % btcBalance)  # my btc balance

symbol = input("what currency") + "BTC"  # symbol of first
symbol = symbol.upper()
print(symbol)

# dec.decimal_to_precision()

priceOfWanted = float(binance.prices()[symbol])  # how much coin->btc is worth
print(priceOfWanted)

# binance.or
# binance.order(symbol,binance.BUY,)
#exchange.enableRateLimit = True


def calculateProfit(coinPrice, boughtPrice):
    return coinPrice / boughtPrice


def calcAmountNeeded(coinAmount, Volume, percent):
    # volume = current have 0-> inf
    # percent = how much of btc 0->1
    # coinAmount = how much is coin in terms of btc