Exemplo n.º 1
0
def before_request():
    if 'logged_in' not in session:
        if request.endpoint != 'login':
            if request.is_xhr:
                return jsonify(code=-2,message="You are not logged in.")
            else:
                return redirect(url_for('login'))
    else:
        g.bc = btcchina.BTCChina(app.config["INFO_ACCESS_KEY"],app.config["INFO_SECRET_KEY"])
        g.bc_deal = btcchina.BTCChina(app.config["DEAL_ACCESS_KEY"],app.config["DEAL_SECRET_KEY"])
Exemplo n.º 2
0
    def __init__(self, public_key, private_key):
        self.btcchina = btcchina.BTCChina(public_key, private_key)

        # minimum trade size
        self.min_btc = .001
        # maximum to be actively trading at one time
        self.max_btc = 10

        self.orders = []

        for order in self.btcchina.get_orders()['order']:
            print 'Canceled Order #%s' % order['id']
            self.btcchina.cancel(order['id'])

        print 'Setup complete'
        time.sleep(2)
#!/usr/bin/python
# -*- coding: utf-8 -*-

import btcchina

access_key = "YOUR_ACCESS_KEY"
secret_key = "YOUR_SECRET_KEY"

bc = btcchina.BTCChina(access_key, secret_key)
''' These methods have no arguments '''
#result = bc.get_account_info()
#print result

#result = bc.get_market_depth2()
#print result

# NOTE: for all methods shown here, the transaction ID could be set by doing
#result = bc.get_account_info(post_data={'id':'stuff'})
#print result
''' buy and sell require price (CNY, 5 decimals) and amount (LTC/BTC, 8 decimals) '''
#result = bc.buy(500,1)
#print result
#result = bc.sell(500,1)
#print result
''' cancel requires id number of order '''
#result = bc.cancel(2)
#print result
''' request withdrawal requires currency and amount '''
#result = bc.request_withdrawal('BTC',0.1)
#print result
''' get deposits requires currency. the optional "pending" defaults to true '''
Exemplo n.º 4
0
def main():

# Initilize everything

    access_key=raw_input("access key: ")
    secret_key=raw_input("secret key: ")


    bc = btcchina.BTCChina(access_key,secret_key)
    result = bc.get_account_info()
    print result

###################################################################################
    i = 0
    while True:

        try:
            bc_depth = bc.get_bcmarket_depth2()
            lc_depth = bc.get_lcmarket_depth2()
            lb_depth = bc.get_lbmarket_depth2()

            bc_ask = bc_depth['market_depth']['ask'][0]['price']
            lc_bid = lc_depth['market_depth']['bid'][0]['price']
            lb_ask = lb_depth['market_depth']['ask'][0]['price']
            arbitrage_btc = 1.0 / lb_ask * lc_bid / bc_ask

            bc_ask_1 = bc_depth['market_depth']['ask'][1]['price']
            lc_bid_1 = lc_depth['market_depth']['bid'][1]['price']
            lb_ask_1 = lb_depth['market_depth']['ask'][1]['price']
            arbitrage_btc_1 = 1.0 / lb_ask_1 * lc_bid_1 / bc_ask_1

            lb_bid = lb_depth['market_depth']['bid'][0]['price']
            bc_bid = bc_depth['market_depth']['bid'][0]['price']
            lc_ask = lc_depth['market_depth']['ask'][0]['price']
            arbitrage_ltc = lb_bid * bc_bid / lc_ask

            lb_bid_1 = lb_depth['market_depth']['bid'][1]['price']
            bc_bid_1 = bc_depth['market_depth']['bid'][1]['price']
            lc_ask_1 = lc_depth['market_depth']['ask'][1]['price']
            arbitrage_ltc_1 = lb_bid_1 * bc_bid_1 / lc_ask_1

            date = bc_depth['market_depth']['date']

            print lb_ask, lc_bid, bc_ask, arbitrage_btc,"\t", arbitrage_ltc, bc_bid, lc_ask, lb_bid
        
            if arbitrage_btc >= 1.0018:

                if lb_depth['market_depth']['ask'][0]['amount'] >= 3 and lc_depth['market_depth']['bid'][0]['amount'] >= 3:
                    order_btc(bc_ask, lc_bid, lb_ask, 3)

                elif lb_depth['market_depth']['ask'][0]['amount'] >= 1 and lc_depth['market_depth']['bid'][0]['amount'] >= 1:
                    order_btc(bc_ask, lc_bid, lb_ask, 1)

                order_file = open("logging.txt",'a')
                order_file.write(' '.join(["BTC:", str(date), str(arbitrage_btc), str(bc_ask), str(lc_bid), str(lb_ask), ' | ', str(lb_depth['market_depth']['ask'][0]['amount']), str(lc_depth['market_depth']['bid'][0]['amount']), '\n']))
                order_file.close()
                 

            if arbitrage_ltc >= 1.0018:


                if lb_depth['market_depth']['bid'][0]['amount'] >= 3 and lc_depth['market_depth']['ask'][0]['amount'] >= 3:
                    order_ltc(bc_bid, lc_ask, lb_bid, 3)

                elif lb_depth['market_depth']['bid'][0]['amount'] >= 1 and lc_depth['market_depth']['ask'][0]['amount'] >= 1:
                    order_ltc(bc_bid, lc_ask, lb_bid, 1)

                order_file = open("logging.txt",'a')
                order_file.write(' '.join(["LTC:", str(date), str(arbitrage_ltc), str(bc_bid), str(lc_ask), str(lb_bid), ' | ', str(lb_depth['market_depth']['bid'][0]['amount']), str(lc_depth['market_depth']['ask'][0]['amount']), '\n']))
                order_file.close()

        except:
            file = open("error.txt", 'a')
            file.write(str(i))
            file.close()
            i = i + 1
            bc = btcchina.BTCChina(access_key,secret_key)
Exemplo n.º 5
0
def main():

    # Initilize everything

    access_key = raw_input("access key: ")
    secret_key = raw_input("secret key: ")

    bc = btcchina.BTCChina(access_key, secret_key)
    result = bc.get_account_info()
    print result

    ###################################################################################
    i = 0
    while True:

        try:
            bc_depth = bc.get_bcmarket_depth2()
            lc_depth = bc.get_lcmarket_depth2()
            lb_depth = bc.get_lbmarket_depth2()

            bc_ask = bc_depth['market_depth']['ask'][0]['price']
            lc_bid = lc_depth['market_depth']['bid'][0]['price']
            lb_ask = lb_depth['market_depth']['ask'][0]['price']
            arbitrage_btc = 1.0 / lb_ask * lc_bid / bc_ask

            bc_ask_1 = bc_depth['market_depth']['ask'][1]['price']
            lc_bid_1 = lc_depth['market_depth']['bid'][1]['price']
            lb_ask_1 = lb_depth['market_depth']['ask'][1]['price']
            arbitrage_btc_1 = 1.0 / lb_ask_1 * lc_bid_1 / bc_ask_1

            lb_bid = lb_depth['market_depth']['bid'][0]['price']
            bc_bid = bc_depth['market_depth']['bid'][0]['price']
            lc_ask = lc_depth['market_depth']['ask'][0]['price']
            arbitrage_ltc = lb_bid * bc_bid / lc_ask

            lb_bid_1 = lb_depth['market_depth']['bid'][1]['price']
            bc_bid_1 = bc_depth['market_depth']['bid'][1]['price']
            lc_ask_1 = lc_depth['market_depth']['ask'][1]['price']
            arbitrage_ltc_1 = lb_bid_1 * bc_bid_1 / lc_ask_1

            date = bc_depth['market_depth']['date']

            print lb_ask, lc_bid, bc_ask, arbitrage_btc, "\t", arbitrage_ltc, bc_bid, lc_ask, lb_bid

            if arbitrage_btc >= 1.0018:

                if lb_depth['market_depth']['ask'][0][
                        'amount'] >= 18 and lc_depth['market_depth']['bid'][0][
                            'amount'] >= 18:

                    bc_price = bc_ask + 0.5
                    lc_price = lc_bid - 0.03
                    bc_quantity = 18 * lc_bid / bc_ask

                    lb_buy_order_id = bc.lbbuy(lb_ask, 18)
                    lc_sell_order_id = bc.lcsell(lc_price, 18)
                    bc_buy_order_id = bc.bcbuy(bc_price, bc_quantity)

                    print '\a'
                    print '18!!!!!!!!!!!!!'

                    order_file = open('log_order.txt', 'a')
                    order_file.write(' '.join([
                        'BTC: 18',
                        str(date),
                        str(arbitrage_btc),
                        str(lb_ask),
                        str(lc_bid),
                        str(bc_ask), ' | ',
                        str(lb_buy_order_id),
                        str(lc_sell_order_id),
                        str(bc_buy_order_id), '\n'
                    ]))
                    order_file.close()

                elif lb_depth['market_depth']['ask'][0][
                        'amount'] >= 3 and lc_depth['market_depth']['bid'][0][
                            'amount'] >= 3:

                    bc_price = bc_ask + 0.5
                    lc_price = lc_bid - 0.03
                    bc_quantity = 3 * lc_bid / bc_ask

                    lb_buy_order_id = bc.lbbuy(lb_ask, 3)
                    lc_sell_order_id = bc.lcsell(lc_price, 3)
                    bc_buy_order_id = bc.bcbuy(bc_price, bc_quantity)

                    print '\a'
                    print '3!!!!!!!!!!!!!'

                    order_file = open('log_order.txt', 'a')
                    order_file.write(' '.join([
                        'BTC: 3',
                        str(date),
                        str(arbitrage_btc),
                        str(lb_ask),
                        str(lc_bid),
                        str(bc_ask), ' | ',
                        str(lb_buy_order_id),
                        str(lc_sell_order_id),
                        str(bc_buy_order_id), '\n'
                    ]))
                    order_file.close()

            if arbitrage_ltc >= 1.0018:

                if lb_depth['market_depth']['bid'][0][
                        'amount'] >= 18 and lc_depth['market_depth']['ask'][0][
                            'amount'] >= 18:

                    bc_price = bc_bid - 0.5
                    lc_price = lc_ask + 0.03
                    bc_quantity = 18 * lc_ask / bc_bid

                    lb_sell_order_id = bc.lbsell(lb_bid, 18)
                    bc_sell_order_id = bc.bcsell(bc_price, bc_quantity)
                    lc_buy_order_id = bc.lcbuy(lc_price, 18)

                    print '\a'
                    print '18!!!!!!!!!!!!!'

                    order_file = open("xxxxx", 'a')
                    order_file.write(' '.join([
                        'LTC: 18',
                        str(date),
                        str(lb_sell_order_id),
                        str(bc_sell_order_id),
                        str(lc_buy_order_id), ' | ',
                        str(arbitrage_ltc),
                        str(lb_bid),
                        str(bc_bid),
                        str(lc_ask), '\n'
                    ]))
                    order_file.close()

                elif lb_depth['market_depth']['bid'][0][
                        'amount'] >= 3 and lc_depth['market_depth']['ask'][0][
                            'amount'] >= 3:

                    bc_price = bc_bid - 0.5
                    lc_price = lc_ask + 0.03
                    bc_quantity = 3 * lc_ask / bc_bid

                    lb_sell_order_id = bc.lbsell(lb_bid, 3)
                    bc_sell_order_id = bc.bcsell(bc_price, bc_quantity)
                    lc_buy_order_id = bc.lcbuy(lc_price, 3)

                    print '\a'
                    print '3!!!!!!!!!!!!!'

                    order_file = open("xxxxx", 'a')
                    order_file.write(' '.join([
                        'LTC: 3',
                        str(date),
                        str(lb_sell_order_id),
                        str(bc_sell_order_id),
                        str(lc_buy_order_id), ' | ',
                        str(arbitrage_ltc),
                        str(lb_bid),
                        str(bc_bid),
                        str(lc_ask), '\n'
                    ]))
                    order_file.close()

        except:
            file = open("xxxxx", 'a')
            file.write(str(i))
            file.close()
            i = i + 1
            bc = btcchina.BTCChina(access_key, secret_key)
Exemplo n.º 6
0
header = "_id	width	mid	imbalance2	adj_price2	imbalance4	adj_price4	imbalance8	adj_price8	t10_count	t10_av	agg10	trend10	t15_count	t15_av	agg15	trend15	t30_count	t30_av	agg30	trend30	t45_count	t45_av	agg45	trend45	t60_count	t60_av	agg60	trend60	t75_count	t75_av	agg75	trend75	t90_count	t90_av	agg90	trend90	t105_count	t105_av	agg105	trend105	t120_count	t120_av	agg120	trend120	t135_count	t135_av	agg135	trend135	t150_count	t150_av	agg150	trend150	t165_count	t165_av	agg165	trend165	t180_count	t180_av	agg180	trend180"
y_multiplied_by = 100
#model_base_filename = "data/model_featuresNewAll_1476108655.82-1480731470.85_duration%s_times%s.pkl"
model_base_filename = "data/model_featuresNew_1482247313.0-1482762365.28_duration15_times100.pkl"
cols_filename = "data/cols_featuresNewAll.pkl"

client = pymongo.MongoClient()
db = client['cryptobot']
threshold = float(sys.argv[1]) / 100
# ticks_db = db['btcc_btccny_ticks']
timestamp_format = "%Y-%m-%d %H:%M:%S.%f"
access_key = ""  #ADD YOUR ACCESS KEY HERE
secret_key = ""  #ADD YOUR SECRET HERE
max_api_retry = 2

trade_api = btcchina.BTCChina(access_key, secret_key)

with open(cols_filename, 'r') as file:
    cols = pickle.load(file)
file.close()
models = {}
for prediction_period in prediction_periods:
    #model_filename = model_base_filename%(prediction_period,y_multiplied_by)
    model_filename = model_base_filename
    with open(model_filename, 'r') as file:
        models[prediction_period] = pickle.load(file)
    file.close()


def get_formatted_time_string(this_time):
    return datetime.utcfromtimestamp(this_time).strftime(timestamp_format)
Exemplo n.º 7
0
	def __init__(self,access=None,secret=None):
		self.service = btcchina.BTCChina(access,secret)
		self._priceURL = "https://data.btcchina.com/data/ticker"
Exemplo n.º 8
0
				orderID = result["order"][0]["id"]
				print "cancel orderID: ", orderID
				result = self.service.cancel(orderID)
				
				print "canceling order..."
				print "Result : ",result
				if(result and result["result"] == True):
					break
			except Exception as e:
				print "cancel error: ", e
			else:
				print "Now retry cancel : ", j
				
		return {"price":price, "result":False}

if __name__ == '__main__':
	ACCESS_KEY="bcf78b6d-83fa-4411-a330-9e386494d3ad"
	SECRET_KEY="323e18cc-0fa2-4f92-bfc8-9f044f3c424a"
	SERVICE = btcchina.BTCChina(ACCESS_KEY,SECRET_KEY)
	
	info = SERVICE.get_orders()["result"]
	
	print info
	
	# TOTAL_AMOUNT = float(info['result']['balance']['btc']['amount'])
	# amount = "0.0100"
	
	# print  amount
	# result = SERVICE.sell("9000.00", str(amount))
	# print "result: ", result
Exemplo n.º 9
0
        for id in order_ids:
            res = bc.cancel(id)
            if res == True:
                print Fore.GREEN + "\r挂单" + str(id) + "已取消!"
            else:
                try:
                    print Fore.RED + "\r操作未完成,服务器返回:" + res["message"]
                except:
                    print Fore.RED + "\r未知错误,业务未受理!"
        print "正在返回主菜单..."
    else:
        print "操作已取消,正在返回主菜单..."


if __name__ == '__main__':
    bc = btcchina.BTCChina(info_access_key, info_secret_key)
    bc_deal = btcchina.BTCChina(deal_access_key, deal_secret_key)
    while True:
        try:
            result = bc.get_account_info()
            title = result["profile"]["username"].title()
            btc_amount = result["balance"]["btc"]["amount"] or 0
            cny_amount = result["balance"]["cny"]["amount"] or 0
            f_btc_amount = result["frozen"]["btc"]["amount"] or 0
            f_cny_amount = result["frozen"]["cny"]["amount"] or 0
            bid_price, ask_price = get_current_price("both")
            os.system('clear')
            print '''%s%s,您目前可用%g个比特币以及%g元人民币,冻结%g比特币,%g元人民币.
                                \r当前Bid Price %g,当前Ask Price %g.请输入您要执行的交易类型:
                                \r\tb: 买入比特比(或直接Enter)
                                \r\ts: 卖出比特币
Exemplo n.º 10
0
def main():
    try:
        cf = ConfigParser.ConfigParser()
        cf.read(os.path.join(cwd, "btc.conf"))
        info_access_key = cf.get("info", "access_key")
        info_secret_key = cf.get("info", "secret_key")
        deal_access_key = cf.get("deal", "access_key")
        deal_secret_key = cf.get("deal", "secret_key")
        logger.info("Read config successfully.")
    except:
        logger.error(
            "Parse config file error.Please make sure that btc.conf file exists. Exiting.."
        )
        sys.exit(-1)

    bc = btcchina.BTCChina(info_access_key, info_secret_key)
    bc_deal = btcchina.BTCChina(deal_access_key, deal_secret_key)
    logger.info("Daemon Started..")

    max_price = 0
    min_price = 0
    t_date = 0
    is_max = is_min = False
    prev_price = 0
    while True:
        logger.info("Read config..")
        try:
            cf.read(os.path.join(cwd, "btc.conf"))
        except:
            logger.error("Please check if btc.conf exists.")

        try:
            USE_DAEMON = cf.get("global", "use")
        except:
            USE_DAEMON = False

        if USE_DAEMON != "true":
            max_price = 0
            min_price = 0
            t_date = 0
            is_max = is_min = False
            prev_price = 0
            logger.info("DO_NOT_USE_DAEMON..Sleep 30 seconds.")
            sleep(30)
            continue

        try:
            LOW_SELL_RATIO = float(cf.get("risk", "low_sell_ratio"))
            LOW_SELL_RATIO = LOW_SELL_RATIO if LOW_SELL_RATIO < 1 else 0
        except:
            LOW_SELL_RATIO = 0

        try:
            HIGH_SELL_RATIO = float(cf.get("risk", "high_sell_ratio"))
            HIGH_SELL_RATIO = HIGH_SELL_RATIO if HIGH_SELL_RATIO > 1 else 0
        except:
            HIGH_SELL_RATIO = 0

        try:
            FALLDOWN_SELL = float(cf.get("risk", "falldown_sell"))
            FALLDOWN_SELL = FALLDOWN_SELL if FALLDOWN_SELL > 0 else 0
        except:
            FALLDOWN_SELL = 0

        try:
            LOW_SELL_PRICE = float(cf.get("risk", "low_sell_price"))
        except:
            LOW_SELL_PRICE = 0

        try:
            HIGH_SELL_PRICE = float(cf.get("risk", "high_sell_price"))
        except:
            HIGH_SELL_PRICE = 0

        logger.info(
            "\x1b[1mLOW_SELL_RATIO = %g; HIGH_SELL_RATIO = %g; FALLDOW_SELL = %g;\x1b[0m"
            % (LOW_SELL_RATIO, HIGH_SELL_RATIO, FALLDOWN_SELL))

        logger.info(
            "\x1b[1mLOW_SELL_PRICE = %s; HIGH_SELL_PRICE = %s;\x1b[0m" %
            (LOW_SELL_PRICE, HIGH_SELL_PRICE))
        logger.info("Refresh info..")
        try:
            result = bc.get_account_info()
            fee = float(result['profile']['trade_fee']) / 100
            if float(result["balance"]["btc"]["amount"]) < 0.001:
                logger.info(
                    "You have no btccoins now...Let me sleep one minute :)\n")
                prev_price = 0
                sleep(60)
            else:
                amount = float(result["balance"]["btc"]["amount"])
                #amount = (1-fee)*amount
                amount = math.floor(amount * 1000) / 1000
                #GET THE LAST BUYBTC TRANSACTION
                result = bc.get_transactions("buybtc", 1)
                t = result["transaction"][0]
                last_price = abs(
                    float(t["cny_amount"]) / float(t["btc_amount"]))

                #CHECK IF CURRENT PRICE IS TOO LOWER THAN LAST TRANSACTION PRICE
                try:
                    r = requests.get('https://data.btcchina.com/data/ticker')
                    result = r.json()
                    cur_price = float(result['ticker']['buy'])
                except (requests.exceptions.RequestException, ValueError):
                    result = bc.get_market_depth()
                    cur_price = float(
                        result["market_depth"]['bid'][0]["price"])
                except:
                    continue

                if t_date == int(t["date"]):
                    if cur_price > max_price:
                        is_max = True
                        max_price = cur_price
                    else:
                        is_max = False
                    if cur_price < min_price:
                        is_min = True
                        min_price = cur_price
                    else:
                        is_min = False
                else:
                    t_date = int(t["date"])
                    is_max = is_min = True
                    max_price = min_price = cur_price

                LOW_SELL_RATIO = float(LOW_SELL_RATIO)
                if LOW_SELL_RATIO > 1.0:
                    LOW_SELL_RATIO = 1.0
                ratio = cur_price / last_price

                if is_max == True and prev_price != 0:
                    logger.info(
                        "\n\r\033[1m\033[36m##The price reached the highest price %g since your last buy transaction.\x1b[0m"
                        % (max_price))

                if is_min == True and prev_price != 0:
                    logger.info(
                        "\n\r\033[1m\033[31m##The price fell down to the lowest price %g since your last buy transaction.\x1b[0m"
                        % (min_price))

                if LOW_SELL_PRICE and cur_price < LOW_SELL_PRICE:
                    reason = "\n\r\033[1;31m$$_Ratio: %g; Current bid price %g; LOW_SELL_PRICE: %g;\n\rFuck, selling all %g bitcoins.\x1b[0m" % (
                        ratio, cur_price, LOW_SELL_PRICE, amount)
                    logger.info(reason)
                    sell_price = get_must_sell_price(bc)
                    res = bc_deal.sell(str(sell_price - 0.1),
                                       str(amount - 0.00001))
                    if res == True:
                        reason = "$$_Ratio: %g; \nCurrent bid price %g; \nLOW_SELL_PRICE: %g;\n\nFuck, selling all %g bitcoins." % (
                            ratio, cur_price, LOW_SELL_PRICE, amount)
                        mail(
                            "Sorry to sell all your bitcoins",
                            reason + "\n\nSell with price " + str(sell_price) +
                            " successfully!")
                        logger.info(
                            "$~_Commit order at price %g successfully!\n" %
                            sell_price)
                        prev_price = 0
                        continue
                    else:
                        try:
                            logger.warning(
                                "\033[1;31m$!_Failed, server says: %s \x1b[0m\n"
                                % res["message"])
                        except:
                            logger.error(
                                "\033[1;31m$!_Failed, unknow error! \x1b[0m\n")

                if HIGH_SELL_PRICE and cur_price > HIGH_SELL_PRICE:
                    reason = "\n\r\033[1;32m$$_Ratio: %g; Current bid price %g; HIGH_SELL_PRICE: %g;\n\rNice, selling all %g bitcoins.\x1b[0m" % (
                        ratio, cur_price, HIGH_SELL_PRICE, amount)
                    logger.info(reason)
                    res = bc_deal.sell(str(cur_price - 0.1),
                                       str(amount - 0.00001))
                    if res == True:
                        reason = "$$_Ratio: %g; \nCurrent bid price %g; \nHIGH_SELL_PRICE: %g;\n\nNice, selling all %g bitcoins." % (
                            ratio, cur_price, HIGH_SELL_PRICE, amount)
                        mail("Happly to sell all your bitcoins.", reason)
                        logger.info("$~_Commit order successfully!\n")
                        prev_price = 0
                        continue
                    else:
                        try:
                            logger.warning(
                                "\033[1;31m$!_Failed, server says: %s \x1b[0m\n"
                                % res["message"])
                        except:
                            logger.error(
                                "\033[1;31m$!_Failed, unknow error! \x1b[0m\n")

                if LOW_SELL_RATIO and ratio <= LOW_SELL_RATIO:
                    #SELL ALL
                    reason = "\n\r\033[1;31m$$_Ratio: %g; Current bid price %g; Your last buybtc price %g; LOW_SELL_RATIO: %g;\n\rFuck, selling all %g bitcoins.\x1b[0m" % (
                        ratio, cur_price, last_price, LOW_SELL_RATIO, amount)
                    logger.info(reason)
                    sell_price = get_must_sell_price(bc)
                    res = bc_deal.sell(str(sell_price - 0.1),
                                       str(amount - 0.00001))
                    if res == True:
                        reason = "$$_Ratio: %g; \nCurrent bid price %g; \nYour last buybtc price %g; \nLOW_SELL_RATIO: %g;\n\nFuck, selling all %g bitcoins." % (
                            ratio, cur_price, last_price, LOW_SELL_RATIO,
                            amount)
                        mail(
                            "Sorry to sell all your bitcoins",
                            reason + "\n\nSell with price " + str(sell_price) +
                            " successfully!")
                        logger.info(
                            "$~_Commit order at price %g successfully!\n" %
                            sell_price)
                        prev_price = 0
                        continue
                    else:
                        try:
                            logger.warning(
                                "\033[1;31m$!_Failed, server says: %s \x1b[0m\n"
                                % res["message"])
                        except:
                            logger.error(
                                "\033[1;31m$!_Failed, unknow error! \x1b[0m\n")

                if HIGH_SELL_RATIO and ratio >= HIGH_SELL_RATIO:
                    #SELL ALL
                    reason = "\n\r\033[1;32m$$_Ratio: %g; Current bid price %g; Your last buybtc price %g; HIGH_SELL_RATIO: %g;\n\rNice, selling all %g bitcoins.\x1b[0m" % (
                        ratio, cur_price, last_price, HIGH_SELL_RATIO, amount)
                    logger.info(reason)
                    res = bc_deal.sell(str(cur_price - 0.1),
                                       str(amount - 0.00001))
                    if res == True:
                        reason = "$$_Ratio: %g; \nCurrent bid price %g; \nYour last buybtc price %g; \nHIGH_SELL_RATIO: %g;\n\nNice, selling all %g bitcoins." % (
                            ratio, cur_price, last_price, HIGH_SELL_RATIO,
                            amount)
                        mail("Happly to sell all your bitcoins.", reason)
                        logger.info("$~_Commit order successfully!\n")
                        prev_price = 0
                        continue
                    else:
                        try:
                            logger.warning(
                                "\033[1;31m$!_Failed, server says: %s \x1b[0m\n"
                                % res["message"])
                        except:
                            logger.error(
                                "\033[1;31m$!_Failed, unknow error! \x1b[0m\n")

                if FALLDOWN_SELL and prev_price - cur_price > FALLDOWN_SELL:
                    reason = "\n\r\033[1m\x1b[32m!!Sorry to sell all your %g bitcoins because its price has fallen down %g RMB in the past 30 seconds.\x1b[0m" % (
                        amount, prev_price - cur_price)
                    logger.info(reason)
                    try:
                        sell_price = get_must_sell_price(bc)
                        res = bc_deal.sell(str(sell_price - 0.1),
                                           str(amount - 0.00001))
                        if res == True:
                            reason = "Sorry to sell all your %g bitcoins because its price has fallen down %g RMB in the past 30 seconds." % (
                                amount, prev_price - cur_price)
                            mail(
                                "I am selling all your bitcoins",
                                reason + "\n\nSell with price " +
                                str(sell_price) + " successfully!")
                            logger.info(
                                "$~_Commit order at price %g successfully!\n" %
                                sell_price)
                            prev_price = 0
                    except Exception as e:
                        logger.error("\n!!!Selling error: %s ...\n" % e)
                    continue
                else:
                    prev_price = cur_price

                if HIGH_SELL_RATIO and ratio >= 1:
                    logger.info(
                        "\n\r$#_Ratio:\x1b[1;32m %g\x1b[0m; Current bid price %g; Your last buybtc price %g; HIGH_SELL_RATIO %g;\n\r\033[1m\x1b[33mDo nothing with total %g bitcoins.\x1b[0m\n"
                        % (ratio, cur_price, last_price, HIGH_SELL_RATIO,
                           amount))

                if LOW_SELL_RATIO and ratio < 1:
                    logger.info(
                        "\n\r$#_Ratio:\x1b[1;31m %g\x1b[0m; Current bid price %g; Your last buybtc price %g; LOW_SELL_RATIO: %g;\n\r\033[1m\x1b[33mDo nothing with total %g bitcoins.\x1b[0m\n"
                        %
                        (ratio, cur_price, last_price, LOW_SELL_RATIO, amount))

                sleep(30)

        except Exception as e:
            logger.error("\n!!!Error: %s ..\nRetring...\n" % e)
            prev_price = 0
            sleep(5)