Esempio n. 1
0
class prediction:
    config=config()
    API_KEY=config.getApiKey()
    API_SECRET=config.getApiSecret()
    count=int(config.getCount())
    CURRENCY_PAIR="btc_jpy"
    candle_type="1min"
    datetime=datetime()
    bbservice=bbService(API_KEY,API_SECRET,CURRENCY_PAIR)

    def print_price(self, data):
        print( "時間: " + datetime.fromtimestamp(data["close_time"]).strftime('%Y/%m/%d %H:%M') + " 始値: " + str(data["open_price"]) + " 終値: " + str(data["close_price"]) )


    def check_candle(self, data):
        realbody_rate = abs(data["close_price"] - data["open_price"]) / (data["high_price"]-data["low_price"]) 
        increase_rate = data["close_price"] / data["open_price"] - 1

        if data["close_price"] < data["open_price"] : return False
        elif increase_rate < 0.0005 : return False
        elif realbody_rate < 0.5 : return False
        else : return True


    def check_ascend(self, data, last_data):
        if data["open_price"] > last_data["open_price"] and data["close_price"] > last_data["close_price"]:
            return True
        else:
            return False

    def predition(self):
        flag = 0

        while True:
            now = self.datetime.today().strftime("%Y%m%d")
            candle_stick=self.bbservice.getCandleStick(self.CURRENCY_PAIR, self.candle_type, now)
            last_data = self.convert_data(candle_stick[-2])
            data = self.convert_data(candle_stick[-1])
            
            if data["close_time"] != last_data["close_time"]:
                
                if flag == 0 and self.check_candle( data ):
                    flag = 1
                elif flag == 1 and self.check_candle( data )  and self.check_ascend( data,last_data ):
                    print("2本連続で陽線")
                    flag = 2
                elif flag == 2 and self.check_candle( data )  and self.check_ascend( data,last_data ):
                    print("3本連続で陽線 なので 買い!")
                    flag = 3
                else:
                    flag = 0
                
                last_data["close_time"] = data["close_time"]
                last_data["open_price"] = data["open_price"]
                last_data["close_price"] = data["close_price"]
                
            time.sleep(60)

    def convert_data(self, single_data):
        return { "close_time" : datetime.datetime.fromtimestamp(single_data[5])strftime("%Y%m%d"),
            "open_price" : int(single_data[0]),
            "high_price" : int(single_data[1]),
            "low_price" : int(single_data[2]),
            "close_price": int(single_data[3]) }
Esempio n. 2
0
class tradeBb:
    config = config()
    API_KEY = config.getApiKey()
    API_SECRET = config.getApiSecret()
    #取引所のパラメータ
    order_min_size = 0  #数量最小値
    order_digit = 0  #数量の桁数 ex. 3=0.001
    fee_rate = 0  #取引手数料のレート(%)
    #取引パラメータ
    buy_unit = 0  #購入単位
    profit = 0  #価格差
    CURRENCY_PAIR = ""

    bbservice = bbService(API_KEY, API_SECRET, CURRENCY_PAIR)
    slackService = slackService()
    pair = ""

    exceptionCnt = 0
    oidArray = []

    buyadd = 0
    add = 0
    buy_price = 0
    stay = True

    #コンストラクタ
    def __init__(self, buyUnit, profit, orderDigit, currencyPair):
        self.order_min_size = buyUnit
        self.order_digit = orderDigit
        self.buy_unit = buyUnit
        self.profit = float(profit)
        self.pair = currencyPair
        self.CURRENCY_PAIR = currencyPair

    def tradeBb(self):
        while True:
            self.buyadd = 0
            self.add = 0
            ob = self.bbservice.orderbook(self.pair)
            buy_price = float(ob["bids"][0][0])
            self.buy_price = buy_price
            #購入数量を計算。 購入数量 = 数量*(1+fee*2) - BTC残高
            balance = self.bbservice.balance()
            print("Log : JPY {0}".format(float(balance["jpy"])))
            #self.slackService.requestOnSlack("Log : JPY {0}".format(float(balance["jpy"])))
            buy_amount = round(
                float(self.buy_unit) * (1 + 0.01 * self.fee_rate * 2) -
                float(balance["btc"]), self.order_digit)
            if float(self.buy_price) > float(buy_price):
                if (float(self.buy_price) - float(buy_price)) > 500:
                    self.stay = False
            if buy_amount > 0:
                #BTC残高が不十分なら注文の最小値を考慮して追加購入。
                buy_amount = max(self.order_min_size, buy_amount)
                #単位の整形
                #
                #JPY残高の確認
                if float(balance["jpy"]) < buy_amount * buy_price:
                    print("Log : Insufficient JPY balance")
                    break
                #注文 BTCの場合はpriceを整数に強制する。
                if self.stay:
                    print("Log : Buy order {0} x {1}".format(
                        float(buy_price), buy_amount))
                    #self.slackService.requestOnSlack("Log : Buy order {0} x {1}".format(float(buy_price),buy_amount))
                    for i in range(0, 5):
                        time.sleep(2)
                        try:
                            self.buyadd -= 10
                            ob = self.bbservice.orderbook(self.pair)
                            buy_price_add = float(ob["bids"][0][0])
                            price = buy_price + self.buyadd
                            oid = self.bbservice.order(self.pair, float(price),
                                                       float(buy_amount),
                                                       "buy", "limit")
                            self.oidArray.append(oid)
                        except Exception as e:
                            print("exception buy limit")
                            print(e)
                            self.exceptionCnt += 1
                            if self.exceptionCnt > 5:
                                self.bbservice.cancel(self.pair, oid)
                                print(
                                    "Log : Sell canceled! oid={0}".format(oid))
                                self.exceptionCnt = 0
                            continue
                    #注文がサーバーで処理されるまで少し待つ
                    time.sleep(5)
                    #さらに最大30秒間、注文が約定するのを待つ
                    for oid in self.oidArray:
                        try:
                            self.bbservice.cancel(self.pair, oid)
                            print("Log : Buy canceled! oid={0}".format(oid))
                        except:
                            print("exception sell limit")
                            print(e)
                        break
                    print("Log : Buy Wait")
                    time.sleep(1)
            else:
                #売却するBTCがすでにあるなら何もしない
                print("Log : Sufficient BTC balance")
            #BTC残高を調べる
            balance = self.bbservice.balance()
            #売却数量は,BTC残高*(1-fee)
            sell_amount = float(balance["btc"])
            if sell_amount < self.order_min_size:
                if self.stay:
                    #部分的な約定などで最小売却単位に届かないなら買いましする
                    print("Log : Insufficient BTC balance")
                    ob = self.bbservice.orderbook(self.pair)
                    buy_price_add = float(ob["bids"][0][0])
                    oid = self.bbservice.order(self.pair, buy_price_add, 0.001,
                                               "buy", "limit")
                    self.oidArray.append(oid)
            #print("Log : Sell order {0} x {1}".format(float(buy_price+self.profit),sell_amount))
            #self.slackService.requestOnSlack("Log : Sell order {0} x {1}".format(float(buy_price+self.profit),sell_amount))
            #利益をのせて注文 BTCの場合はpriceを整数に強制する。
            #for i in range(0,5):
            time.sleep(2)
            try:
                #self.add += 10
                ob = self.bbservice.orderbook(self.pair)
                buy_price = float(ob["bids"][0][0])
                oid = self.bbservice.order(self.pair,
                                           float(buy_price + self.profit),
                                           float(sell_amount), "sell", "limit")
                #self.oidArray.append(oid)
            except Exception as e:
                print("exception sell limit")
                print(e)
                self.exceptionCnt += 1
                if self.exceptionCnt > 5:
                    activeOrders = self.bbservice.getActiveOrders(self.pair)
                    for i in activeOrders:
                        self.bbservice.cancel(self.pair, i["order_id"])
                        print("Log : Sell canceled! oid={0}".format(oid))
                    self.exceptionCnt = 0
                continue
            #注文が成立するまで永遠に待つ
            count = 0
            for i in self.bbservice.getActiveOrders(self.pair):
                print("Log : Sell Wait count")
                count += 1
                time.sleep(3)
                #15byou売れなかったら
                if (count > 5):
                    #for r in self.oidArray:
                    oid = self.bbservice.cancel(self.pair, oid)
                break
            time.sleep(5)
Esempio n. 3
0
class watcher_xrp:
    config = config()
    API_KEY = config.getApiKey()
    API_SECRET = config.getApiSecret()
    count = int(config.getCount())
    CURRENCY_PAIR = "xrp_jpy"
    sellMean = []
    buyMean = []
    highMean = []
    lowMean = []
    lastMean = []
    sellList = []
    buyList = []
    highList = []
    lowList = []
    lastList = []
    init = 0

    bbservice = bbService(API_KEY, API_SECRET, CURRENCY_PAIR)
    tradeStop = tradeStop()
    slackService = slackService()

    def watch(self):
        res = False
        for num in range(((int(self.count) * 3)) // int(self.count)):
            for num in range(int(self.count)):
                if self.init == 0:
                    self.sellMean = []
                    self.buyMean = []
                    self.highMean = []
                    self.lowMean = []
                    self.lastMean = []
                    self.sellList = []
                    self.buyList = []
                    self.highList = []
                    self.lowList = []
                    self.lastList = []

                ticker = self.getTicker()
                self.sellList.append(float(ticker['sell']))
                self.buyList.append(float(ticker['buy']))
                self.highList.append(float(ticker['high']))
                self.lowList.append(float(ticker['low']))
                self.lastList.append(float(ticker['last']))
                self.init += 1

            self.sellMean.append(mean(self.sellList))
            self.buyMean.append(mean(self.buyList))
            self.highMean.append(mean(self.highList))
            self.lowMean.append(mean(self.lowList))
            self.lastMean.append(mean(self.lastList))

        over0 = self.sellMean[0] > self.buyMean[0]
        print(over0)
        over1 = self.sellMean[1] > self.buyMean[1]
        print(over1)
        over2 = self.sellMean[2] > self.buyMean[2]
        print(over2)
        golden = (self.getTake(over0, over1, over2) == True)
        dead = (self.getTake(over0, over1, over2) == False)
        print("golden {0}".format(golden))
        print("dead {0}".format(dead))

        if golden:
            self.slackService.requestOnSlack("Log : golden {0}".format(golden))
            res = True
        elif dead:
            self.slackService.requestOnSlack("Log : dead {0}".format(dead))
            res = False

        print("finish {0}".format(self.count))
        return res

    def getTicker(self):
        ticker = self.bbservice.getTicker(self.CURRENCY_PAIR)
        sleep(5)
        return ticker

    def getTake(self, a, b, c):
        return (not (a) and b
                and c) or (a and not (b)
                           and c) or (a and b and not (c)) or (a and b and c)

    def calculate_mean(self, data):
        s = sum(data)
        N = len(data)
        mean = s / N

        return mean

    #平均からの偏差を求める
    def find_difference(self, data):
        mean = self.calculate_mean(data)
        diff = []

        for num in data:
            diff.append(num - mean)
        return diff

    def calculate_variance(self, data):
        diff = self.find_difference(data)
        #差の2乗を求める
        squared_diff = []
        for d in diff:
            squared_diff.append(d**2)

        #分散を求める
        sum_squared_diff = sum(squared_diff)
        variance = sum_squared_diff / len(data)
        return variance