Esempio n. 1
0
    def create(self, validated_data):
        user = self.context['user']
        instance = Order(**validated_data)
        instance.user = user
        if validated_data['order_type'] == Order.TYPE_TRAIL:
            try:
                ret = python_bitbankcc.public().get_ticker(
                    validated_data['pair']
                ) if validated_data['market'] == 'bitbank' else json.loads(
                    CoinCheck('fake', 'fake').ticker.all())['last']
            except Exception as e:
                instance.status = Order.STATUS_FAILED_TO_ORDER
                instance.error_message = str(e.args)

            else:
                try:
                    last_price = float(ret['last'])
                except ValueError:
                    last_price = 0
                else:
                    instance.trail_price = last_price

        instance.save()

        if instance.order_type in {
                Order.TYPE_MARKET, Order.TYPE_LIMIT
        } and instance.status == Order.STATUS_READY_TO_ORDER:
            order_succeeded = instance.place()
        return instance
Esempio n. 2
0
class bbPubClient:
    # public API classのオブジェクトを取得
    pub = python_bitbankcc.public()

    # PUBLIC
    def getTicker(self, pair):
        value = self.pub.get_ticker(pair)
        return value

    def getDepth(self, pair):
        value = self.pub.get_depth(pair)
        return value

    def getTransactions(self, pair):
        value = self.pub.get_transactions(pair)
        return value

    # 同じメソッドを日にち指定で
    def getTransactionsWithDay(self, pair, day):
        value = self.pub.get_transactions(pair, day)
        return value

    def getCandlestick(self, pair, type, day):
        value = self.pub.get_candlestick(pair, type, day)
        return value
Esempio n. 3
0
    def ingest_new(self):
        # ingest new item
        today = datetime.date.today()
        table_name = "{}_{}".format(self.table_prefix,
                                    self._format_date(today))

        pub = python_bitbankcc.public()
        tic = pub.get_ticker(pair)
        dep = pub.get_depth(pair)
        if (tic is None) & (dep is None):
            return {
                'statusCode': 200,
                'body': json.dumps('Calling API did not succeed')
            }
        else:
            dt = datetime.datetime.utcfromtimestamp(
                int(str(tic['timestamp'])[:10]))
            timestamp = dt.strftime("%Y/%m/%d %H:%M:%S")
            try:
                current_table = dynamodb.Table(table_name)
                response = current_table.put_item(
                    Item={
                        'name': pair,
                        'datetime': timestamp,
                        'sell': int(tic['sell']),
                        'buy': int(tic['buy']),
                        'last': int(tic['last']),
                        'volume': int(float(tic['vol'])),
                        'depth': dep
                    })
                print('PutItem succeeded')
            except Exception as e:
                print('PutItem failed', e.args)
Esempio n. 4
0
def main():
    # by default we connect to localhost:9200
    es = Elasticsearch()
    pub = python_bitbankcc.public()

    while True:
        # every second we record cvt data
        for i in range(60):
            try:
                ret = get_ticker(pub)

                doc = {
                    'close': int(ret['last']),
                    'volume': float(ret['vol']),
                    'timestamp': int(ret['timestamp'])
                }

                print(
                    "----------------------------------------------------------------------"
                )
                print(json.dumps(doc, indent=4, separators=(',', ': ')))
            except Exception as e:
                print("Error occurred: {}".format(e))

            try:
                res = es.index(index="btcjpy", id=i + 1, body=doc)
                print(
                    "----------------------------------------------------------------------"
                )
                print("Elasticsearch collected a second data: {}".format(
                    res['result']))
            except Exception as e:
                print("Error occurred: {}".format(e))
            time.sleep(1)
Esempio n. 5
0
    def _get_market_price(self, market, pair):
        pub_bb = python_bitbankcc.public()
        pub_cc = CoinCheck('fake', 'fake')

        if market == 'bitbank':
            ret = pub_bb.get_ticker(pair)
            return float(pub_bb.get_ticker(pair)['last'])
        else:
            ret = json.loads(pub_cc.ticker.all())
            return float(ret['last'])
Esempio n. 6
0
 def __get_candle_from_bitbank(self, year):
     # public API classのオブジェクトを取得
     pub = python_bitbankcc.public()
     value = pub.get_candlestick(self.coin_type, '1day', year)
     ohcl = {}
     candle = value['candlestick'][0]
     ohcl["open"]   = [data[0] for data in candle["ohlcv"]]
     ohcl["high"]   = [data[1] for data in candle["ohlcv"]]
     ohcl["low"]    = [data[2] for data in candle["ohlcv"]]
     ohcl["close"]  = [data[3] for data in candle["ohlcv"]]
     ohcl["volume"] = [data[4] for data in candle["ohlcv"]]
     ohcl["date"]   = [datetime.datetime.fromtimestamp(data[5]/1000).strftime("%Y-%m-%d") for data in candle["ohlcv"]]
     return ohcl
Esempio n. 7
0
def ajax_ticker(request):
    if request.user.is_anonymous or request.user.is_active == False:
        return JsonResponse({'error': 'authentication failed'}, status=401)

    if request.method == 'GET':
        pair = request.GET.get('pair')
        try:
            pub = python_bitbankcc.public()
            res_dict = pub.get_ticker(pair)

        except Exception as e:
            res_dict = {'error': e.args}
            traceback.print_exc()

        return JsonResponse(res_dict)
Esempio n. 8
0
    def __init__(self, api_key, api_secret):
        # API
        self._public_api = python_bitbankcc.public()
        self._private_api = python_bitbankcc.private(api_key, api_secret)

        # Account balance
        self.jpy_balance = 0.0
        self.xrp_balance = 0.0

        # Latest market info
        self.best_ask = 0.0
        self.best_bid = 0.0
        self.xrp_value = 0.0

        # Settings
        self.PAIR = 'xrp_jpy'
        self.TRADE_TYPE = 'limit'
Esempio n. 9
0
    def create(self, validated_data):
        user = self.context['user']

        try:
            instance = Alert(**validated_data)
            last = python_bitbankcc.public().get_ticker(
                validated_data['pair']
            )['last'] if validated_data['market'] == 'bitbank' else json.loads(
                CoinCheck('fake', 'fake').ticker.all())['last']
            instance.over_or_under = 'over' if validated_data['rate'] > float(
                last) else 'under'
            instance.user = user
            instance.is_active = True
            instance.save()
        except Exception as e:
            print(str(e.args))
        finally:
            return instance
Esempio n. 10
0
def bitbankstart():
    pair_list = ("btc_jpy", "xrp_jpy", "ltc_btc", "eth_btc", "mona_jpy",
                 "mona_btc", "bcc_jpy", "bcc_btc")
    bitbank = "https://public.bitbank.cc"

    while True:
        start = time.time()
        sum_asks = 0
        sum_bids = 0
        # 1~199
        range_dif = 50
        target = ""
        depth = getinfo(pair_list, bitbank).depth("mona_jpy")
        last = python_bitbankcc.public().get_ticker("mona_jpy")["last"]
        depth_json = json.loads(depth)
        depth_asks = depth_json["data"]["asks"]
        depth_bids = depth_json["data"]["bids"]
        for math in range(range_dif):
            # sum_asks = sum_asks + Decimal(depth_asks[math][1]) * Decimal(depth_asks[math][0])
            sum_asks = sum_asks + Decimal(depth_asks[math][1])
            # print(str(math) + " 値段: " + str(depth_list[math][0]) + " 量: " + str(depth_list[math][1]) + " 総額:" + str(Decimal(depth_list[math][1]) * Decimal(depth_list[math][0])))

        for math in range(range_dif):
            # sum_bids = sum_asks + Decimal(depth_bids[math][1]) * Decimal(depth_bids[math][0])
            sum_bids = sum_asks + Decimal(depth_bids[math][1])
        if (sum_asks - sum_bids) > 0:
            target = "上昇"
        elif (sum_bids - sum_asks) > 0:
            target = "降下"
        else:
            target = "エラー"

        mesg = target + " 最新値段:" + last + " 買う数:" + str(
            sum_asks) + " 売る数" + str(sum_bids) + " timelag:" + str(start -
                                                                   time.time())
        print(mesg)
        # sys.stdout.write(
        #         #     "\r" + target + " 最新値段:" + last + " 買う数:" + str(sum_asks) + " 売る数" + str(sum_bids) + " timelag:" + str(
        #         #         start - time.time())
        #         #     )
        #         # sys.stdout.flush()

        # .sendMessage(mesg)
        time.sleep(1)
Esempio n. 11
0
def main():
    pb = python_bitbankcc.public()
    btc = pb.get_ticker(pair)

    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = SUBSCRIBE_KEY
    pubnub = PubNub(pnconfig)

    # inherits SubscribeCallBack class
    my_listener = BitbankSubscriberCallback(float(btc['sell']),
                                            float(btc['buy']))
    pubnub.add_listener(my_listener)
    pubnub.subscribe().channels(TICKER_CHANNEL).execute()

    while True:
        print("Calling the trade logic, best_ask {0}: best_bid {1}".format(
            my_listener.ask, my_listener.bid))
        logic.trade(my_listener.ask, my_listener.bid)
        time.sleep(10)
Esempio n. 12
0
def get_eff_quote(amount, symbol):
    pub = python_bitbankcc.public()
    board = pub.get_depth(symbol)
    # board['bids'].sort(key = lambda x : float(x[0]))
    # board['asks'].sort(key = lambda x : float(x[0]), reverse=True)
    # 実効ASK計算
    i = 0
    s = 0
    while s <= amount:
        s += float(board['asks'][i][1])
        i += 1

    # 実効BID計算
    j = 0
    t = 0
    while t <= amount:
        t += float(board['bids'][j][1])
        j += 1

    return float(board['bids'][i - 1][0]), float(board['asks'][j - 1][0])
Esempio n. 13
0
def get_board(symbol, board, ticker, num = 10):
    pub = python_bitbankcc.public()
    dict_data = {}
    if 'timestamp' in board:
        dict_data['time'] = board['timestamp']
    else:
        dict_data['time'] = datetime.now().timestamp()*1000
    if 'last' in ticker:
        dict_data['last'] = ticker['last']
    else:
        dict_data['last'] = pub.get_ticker(symbol)['last']
    #print(board['asks'][0]['price'])
    asks_price = {'asks_price_{}'.format(i) : board['asks'][i]['price'] for i in range(num)}
    dict_data.update(asks_price)
    asks_size = {'asks_size_{}'.format(i) : board['asks'][i]['size'] for i in range(num)}
    dict_data.update(asks_size)
    bids_pirce = {'bids_price_{}'.format(i) : board['bids'][i]['price'] for i in range(num)}
    dict_data.update(bids_pirce)
    bids_size = {'bids_size_{}'.format(i) : board['bids'][i]['size'] for i in range(num)}
    dict_data.update(bids_size)

    return pd.Series(dict_data)
Esempio n. 14
0
import python_bitbankcc
import json
import os

BITBANK_API_KEY = os.environ['BITBANK_API_KEY']
BITBANK_API_SECRET = os.environ['BITBANK_API_SECRET']

cc_pub = python_bitbankcc.public()
cc_prv = python_bitbankcc.private(BITBANK_API_KEY, BITBANK_API_SECRET)
Esempio n. 15
0
    def handle(self, *args, **options):
        logger = logging.getLogger('batch_logger')
        #logger.info('started')
        time_started = time.time()
        n = 0
        while True:
            time.sleep(1)
            n = n + 1
            time_elapsed = time.time() - time_started
            if time_elapsed > 57.0:
                break
            pub = python_bitbankcc.public()
            for user in User.objects.all():
                # API KEYが登録されているユーザのみ処理
                if user.api_key == "" or user.api_secret_key == "":
                    continue

                # キー情報セット
                try:
                    prv = python_bitbankcc.private(user.api_key,
                                                   user.api_secret_key)
                except Exception as e:
                    logger.error('user:'******' message: ' +
                                 str(e.args))
                    continue

                # 通貨ペアをイテレーション
                for pair in OrderRelation.PAIR:

                    # Tickerの取得
                    try:
                        ticker_dict = pub.get_ticker(pair)
                    except Exception as e:
                        logger.error('user:'******' pair:' + pair +
                                     ' error:' + str(e.args))
                        continue

                    # 通知処理
                    alerts_by_pair = Alert.objects.filter(pair=pair).filter(
                        is_active=True)

                    for alert in alerts_by_pair:
                        try:
                            if (alert.over_or_under == '以上' and float(ticker_dict.get('last')) >= alert.threshold) or \
                                (alert.over_or_under == '以上' and float(ticker_dict.get('last')) >= alert.threshold):

                                if user.use_alert == 'ON':
                                    context = {
                                        "user": user,
                                        "ticker_dict": ticker_dict,
                                        "pair": pair
                                    }
                                    subject = get_template(
                                        'bitbank/mail_template/rate_notice/subject.txt'
                                    ).render(context)
                                    message = get_template(
                                        'bitbank/mail_template/rate_notice/message.txt'
                                    ).render(context)
                                    user.email_user(subject, message)
                                    #logger.info('rate notice sent to:' + user.email_for_notice)
                                    alert.alerted_at = timezone.now()

                                alert.is_active = False
                                alert.save()
                        except Exception as e:
                            alert.is_active = False
                            alert.save()
                            logger.error('user:'******' pair:' +
                                         pair + ' alert:' + str(alert.pk) +
                                         ' error:' + str(e.args))

                    # 逆指値の注文取得
                    stop_market_orders_by_pair = BitbankOrder.objects.filter(
                        user=user).filter(pair=pair).filter(
                            order_type=BitbankOrder.TYPE_STOP_MARKET
                        ).filter(order_id__isnull=True).filter(
                            status__in=[BitbankOrder.STATUS_READY_TO_ORDER])

                    # 各注文を処理
                    for stop_market_order in stop_market_orders_by_pair:
                        # 売りの場合
                        logger.info('Stop market order found. side:' +
                                    stop_market_order.side + ' stop price:' +
                                    str(stop_market_order.price_for_stop) +
                                    ' market sell:' + ticker_dict.get('sell') +
                                    ' market buy:' + ticker_dict.get('buy'))
                        if (stop_market_order.side == 'sell' and (float(ticker_dict.get('sell')) <= stop_market_order.price_for_stop)) or \
                            (stop_market_order.side == 'buy' and (float(ticker_dict.get('buy')) >= stop_market_order.price_for_stop)):
                            _util.place_order(prv, stop_market_order)

                    # ストップリミットの注文取得
                    stop_limit_orders_by_pair = BitbankOrder.objects.filter(
                        user=user).filter(pair=pair).filter(
                            order_type=BitbankOrder.TYPE_STOP_LIMIT
                        ).filter(order_id__isnull=True).filter(
                            status__in=[BitbankOrder.STATUS_READY_TO_ORDER])

                    # 各注文を処理
                    for stop_limit_order in stop_limit_orders_by_pair:
                        logger.info('Stop limit order found. side:' +
                                    stop_limit_order.side + ' stop price:' +
                                    str(stop_limit_order.price_for_stop) +
                                    ' market sell:' + ticker_dict.get('sell') +
                                    ' market buy:' + ticker_dict.get('buy'))

                        if (stop_limit_order.side == 'sell' and (float(ticker_dict.get('sell')) <= stop_limit_order.price_for_stop)) or \
                            (stop_limit_order.side == 'buy' and (float(ticker_dict.get('buy')) >= stop_limit_order.price_for_stop)):
                            _util.place_order(prv, stop_limit_order)
        logger.info('completed')
Esempio n. 16
0
 def __init__(self):
     self.pub = python_bitbankcc.public()
 def __init__(self, pair):
     """
     :param pair:       string コインの種類
     """
     self._pair = pair
     self._pub = python_bitbankcc.public()
Esempio n. 18
0
# Trade key
API_KEY = 'public key'
API_SECRET = 'your private key'

TIME = 100  # run-time (min)
BUDGET = 10000  # Initial available budget
RANGE = 0.0001  # Price range
PAIR = 'xrp_jpy'  # Currency pair to order
CHECK_INTERVAL = 3  # Interval time of order check (sec)
MAKER_FEE_RATE = -0.0005
TAKER_FEE_RATE = 0.0015

# Get instance
prv = pbcc.private(API_KEY, API_SECRET)
pub = pbcc.public()


def make_order_info(pair, amount, price, orderside, ordertype='limit'):
    order_info = {
        "pair": pair,  # ペア
        "amount": amount,  # 注文枚数
        "price": price,  # 注文価格
        "orderside": orderside,  # buy or sell
        "ordertype": ordertype  # 指値注文の場合はlimit
    }

    return order_info


#order process
Esempio n. 19
0
MIN_MARGIN = 0
LOW_RATIO = 2  # when are funds considered low
STABLE_VOL_FLOAT = 0.1
COLORS = ['blue', 'green', 'red', 'orange']

# import credentials
with open('config.yml', 'r') as ymlfile:
    cfg = yaml.load(ymlfile)
auth = cfg['auth']

# instantiate clients
bf_client = pybitflyer.API(api_key=auth['bf']['key'],
                           api_secret=auth['bf']['secret'])
bb_client_pte = python_bitbankcc.private(auth['bb']['key'],
                                         auth['bb']['secret'])
bb_client = python_bitbankcc.public()
zf_pclient = ZaifTradeApi(auth['zf']['key'], auth['zf']['secret'])
zf_client = ZaifPublicApi()
qn_client = Quoinex(auth['qn']['key'], auth['qn']['secret'])


def bb_trade(direction, price, size=SIZE):
    bb_client_pte.order('btc_jpy', '', size, direction.lower(), 'market')


def bf_trade(direction, price, size=SIZE):
    bf_client.sendchildorder(product_code='BTC_JPY',
                             child_order_type='MARKET',
                             side=direction,
                             size=size)
Esempio n. 20
0
 def __init__(self, pair):
     self.pair = pair
     self.pub = python_bitbankcc.public()
     self.prv = python_bitbankcc.private(API_KEY, API_SECRET)
 def __init__(self, api_key=None, api_secret=None):
     self.__pub = python_bitbankcc.public()
     self.__pri = None
     if api_key is not None and api_secret is not None:
         self.__pri = python_bitbankcc.private(api_key=api_key,
                                               api_secret=api_secret)
Esempio n. 22
0
def _get_ticker(market, pair):
    res = python_bitbankcc.public().get_ticker(pair) if market == 'bitbank' else json.loads(CoinCheck('fake', 'fake').ticker.all())
    if 'error' in res:
        raise Exception(res['error'])
    return res
Esempio n. 23
0
 def __init__(self, api_key: str = None, api_secret: str = None, timeout: float = None, **__):
     super().__init__(api_key, api_secret, timeout)
     self.public = python_bitbankcc.public()
     self.private = python_bitbankcc.private(self.api_key, self.api_secret)
Esempio n. 24
0
 def __init__(self):
     """ コンストラクタ """
     self.pubApi = python_bitbankcc.public()
     self.myLogger = MyLogger("MyTechnicalAnalysisUtil")
     self.RSI_N = 14
Esempio n. 25
0
def get_ohlcv_per_sec(start_timestamp, delta_timestamp, symbol):
    """
    argument
    --------
    start_timestamp : float
        timestamp(msec)
    delta_timestamp : float
        timestamp(msec)
        ローソク足間隔
    """
    pub = python_bitbankcc.public()
    now = datetime.now()
    today_0900 = datetime(now.year, now.month, now.day, 9, 0)
    yesterday_0900 = datetime(now.year, now.month, now.day - 1, 9, 0)
    latest_0900 = today_0900 if today_0900 <= now else yesterday_0900
    second_latest_0900 = latest_0900 - timedelta(days=1)
    startday = datetime.fromtimestamp(start_timestamp / 1000)
    flag = False
    if latest_0900 <= startday:
        # 直近の約定履歴60個
        transactions = pub.get_transactions(symbol)
        transactions['transactions'].reverse()
        flag = True
    elif second_latest_0900 <= startday < latest_0900:
        transactions = pub.get_transactions(
            symbol, second_latest_0900.strftime('%Y%m%d'))
    else:
        transactions = pub.get_transactions(symbol,
                                            startday.strftime('%Y%m%d'))

    trans_size = len(transactions['transactions'])
    # print(startday)
    # print(trans_size)
    timestamp_down = start_timestamp
    timestamp_up = timestamp_down + delta_timestamp
    timestamp = transactions['transactions'][0]['executed_at']
    i = 0
    ohlcv = []
    # pprint(transactions)
    # return None

    while timestamp < timestamp_down:
        if i >= trans_size:
            break
        timestamp = transactions['transactions'][i]['executed_at']
        i += 1
    while i < trans_size:
        # print(i)
        # print(timestamp)
        # print(timestamp_down)
        # print(timestamp_up)
        data_unit = []
        ohlcv_unit = dict()
        while timestamp_down <= timestamp and timestamp < timestamp_up and i < trans_size:
            data_unit.append(transactions['transactions'][i])
            i += 1
            if i < trans_size:
                timestamp = transactions['transactions'][i]['executed_at']
        if len(data_unit) == 0:
            if len(ohlcv) == 0:
                ohlcv_unit = {
                    'timestamp': timestamp_down,
                    'open': np.nan,
                    'high': np.nan,
                    'low': np.nan,
                    'close': np.nan,
                    'volume': 0
                }
            else:
                ohlcv_unit = {
                    'timestamp': timestamp_down,
                    'open': ohlcv[-1]['close'],
                    'high': ohlcv[-1]['close'],
                    'low': ohlcv[-1]['close'],
                    'close': ohlcv[-1]['close'],
                    'volume': 0
                }
        else:
            ohlcv_unit['timestamp'] = timestamp_down
            ohlcv_unit['open'] = float(data_unit[0]['price'])
            ohlcv_unit['high'] = max(
                [float(data['price']) for data in data_unit])
            ohlcv_unit['low'] = min(
                [float(data['price']) for data in data_unit])
            ohlcv_unit['close'] = float(data_unit[-1]['price'])
            ohlcv_unit['volume'] = sum(
                [float(data['amount']) for data in data_unit])
        ohlcv.append(ohlcv_unit)
        timestamp_down = timestamp_up
        timestamp_up += delta_timestamp
    if flag:
        while now.timestamp() * 1000 > timestamp_down:
            if len(ohlcv) == 0:
                ohlcv_unit = {
                    'timestamp': timestamp_down,
                    'open': np.nan,
                    'high': np.nan,
                    'low': np.nan,
                    'close': np.nan,
                    'volume': 0
                }
            else:
                ohlcv_unit = {
                    'timestamp': timestamp_down,
                    'open': ohlcv[-1]['close'],
                    'high': ohlcv[-1]['close'],
                    'low': ohlcv[-1]['close'],
                    'close': ohlcv[-1]['close'],
                    'volume': 0
                }
            ohlcv.append(ohlcv_unit)
            timestamp_down += delta_timestamp

    return ohlcv
Esempio n. 26
0
 def __init__(self):
     self.public_api = bitcc.public()
     self.private_api = bitcc.private(os.environ["API_KEY"],
                                      os.environ["API_SECRET"])
Esempio n. 27
0
class get_data():
  #APIオブジェクトを取得
  API = python_bitbankcc.public()

  def __init__(self,pair):
    self.pair = pair

  def get_ticker(self):
    #ティッカー情報を表示
    ticker = get_data.API.get_ticker(self.pair)
    
    ticker_info = "{:8}".format('Pair') + '\t' + 'Now' + '\t'  + 'Sell' + '\t' + 'Buy' \
          + '\t' + 'High' + '\t' +  'Low' + '\t' + 'Vol' + '\t' + '\n' \
          "{:8}".format(self.pair) + '\t' \
              + ticker['last'] + '\t' \
              + ticker['sell'] + '\t' \
              + ticker['buy'] + '\t' \
              + ticker['high'] + '\t' \
              + ticker['low'] + '\t' \
              + ticker['vol']

    return ticker_info

  #RSIクラス
  def close_and_rsi(self):

    #間隔を指定
    candle_type = '1day'
    #取得開始日を指定
    start_day = "20210101"
    start_dt = datetime.strptime(start_day,"%Y%m%d")
    #取得終了日を指定
    today =  datetime.today()
    today = today - timedelta(hours=8)

    dt = start_dt
      
    #ローソク足情報
    ohlcv = []
      
    while dt <= today:
      #指定期間のロウソク足データの取得
      ohlcv.extend(get_data.API.get_candlestick(self.pair,candle_type,datetime.strftime(dt,"%Y"))['candlestick'][0]['ohlcv'])
      dt = dt + timedelta(days=365)

    #DataFrame形式に変更
    df = pd.DataFrame(ohlcv,columns = ['open', 'high','low','close','volume','time']);
    #日時のフォーマットを変更
    df['time'] = [datetime.fromtimestamp(float(time)/1000) for time in df['time']]
    #日時をインデックスに変更
    df.set_index('time',inplace=True)
    #中身の型変換
    df = df[['open', 'high','low','close','volume']].astype('float64')

    #終値抽出
    close = df['close']
    #前日差分
    diff = close.diff()
    #最初の欠損を削除
    diff = diff[1:]

    up,down = diff.copy(),diff.copy()
    up[up < 0] = 0
    down[down > 0] = 0

    #RS(Relative Strength)の計算
    up_sma_14 = up.rolling(window = 14 ,center= False).mean()
    down_sma_14 = down.abs().rolling(window = 14,center = False).mean()

    #RSI(Relative Strength Index)計算
    RS = up_sma_14 / down_sma_14
    RSI = 100.0 - (100.0 / (1.0 + RS))

    #グラフの作成 close と RSI
    fig,(ax1,ax2) = plt.subplots(2,1,gridspec_kw={'height_ratios':[1,1]})
    #close plot
    ax1.plot(close.index,close)
    
    #RSI plot
    ax2.plot(RSI.index,RSI)
    
    #グラフ周りの設定
    #グリッド
    plt.ion()
    ax1.grid()
    ax2.grid()
    #タイトル
    ax1.set_title(str(self.pair) + '/JPY',fontsize=20)
    ax2.set_title('RSI(Relative Strength Index)',fontsize=20)

    #買われ過ぎ 売られ過ぎ可視化
    ax2.axhspan(0,30,facecolor = 'red',alpha = 0.5)
    ax2.axhspan(70,100,facecolor = 'lime',alpha = 0.5)

    #重なり防止
    fig.tight_layout()

    #画像保存
    plt.savefig('Close_and_RSI_'+ str(self.pair)+'.png')

    plt.close()

    #serise型の末尾の値のみ抽出
    return int(RSI.iloc[-1])

  def candle_plot(self):

    #取得開始日を指定
    start_day = "20210101"
    start_dt = datetime.strptime(start_day,"%Y%m%d")
    #取得終了日を指定
    today =  datetime.today()
    today = today - timedelta(hours=8)
    dt = start_dt
    
    #間隔を指定
    candle_type = '1day'

    #ローソク足情報
    ohlcv_day = []
    ohlcv_4hour = []

    #日足ローソク足情報取得 
    while dt <= today:
      #指定期間のロウソク足データの取得
      ohlcv_day.extend(get_data.API.get_candlestick(self.pair,candle_type,datetime.strftime(dt,"%Y"))['candlestick'][0]['ohlcv'])
      dt = dt + timedelta(days=365)
  
    #初期化
    dt_4hour = start_dt
    #間隔を指定
    candle_type = '4hour'

    #4時間足ローソク足情報取得
    while dt_4hour <= today:
      #指定期間のロウソク足データの取得
      ohlcv_4hour.extend(get_data.API.get_candlestick(self.pair,candle_type,datetime.strftime(dt_4hour,'%Y'))['candlestick'][0]['ohlcv'])
      dt_4hour = dt_4hour + timedelta(days=365)

    #DataFrame形式に変更
    data_day = pd.DataFrame(ohlcv_day,columns = ['open', 'high','low','close','volume','time']);
    #日時のフォーマットを変更
    data_day['time'] = [datetime.fromtimestamp(float(time)/1000) for time in data_day['time']]
    #日時をインデックスに変更
    data_day.set_index('time',inplace=True)

    #DataFrame形式に変更
    data_4hour = pd.DataFrame(ohlcv_4hour,columns = ['open', 'high','low','close','volume','time']);
    #日時のフォーマットを変更
    data_4hour['time'] = [datetime.fromtimestamp(float(time)/1000) for time in data_4hour['time']]
    #日時をインデックスに変更
    data_4hour.set_index('time',inplace=True)

    #中身の型変換
    df_day = data_day[['open', 'high','low','close','volume']].astype('float64')
    df_4hour = data_4hour[['open', 'high','low','close','volume']].astype('float64')

    fig_day = plt.figure(figsize=(10,4),dpi=120)
    plt.ion()
    #ローソク足チャートを作成する
    mpf.plot(df_day, type='candle', figratio=(24,8),
      volume=True, mav=(5, 25), style='yahoo')
    plt.close(fig_day)
    #画像保存
    plt.savefig('candle_day_'+ str(self.pair) + '.png')

    fig_4hour = plt.figure(figsize=(10,4),dpi=120)
    plt.ion()
    #ローソク足チャートを作成する
    mpf.plot(df_4hour, type='candle', figratio=(24,8),
      volume=True, mav=(12,25), style='yahoo')
    plt.close(fig_day)
    #画像保存
    plt.savefig('candle_4hour_'+ str(self.pair) + '.png')
Esempio n. 28
0
# coding: utf-8

import os, json

import requests
import python_bitbankcc

API_KEY = os.environ['BITBANK_API_KEY']
API_SECRET = os.environ['BITBANK_API_SECRET']
SLACK_WEBHOOK = os.environ['SLACK_WEBHOOK']

public_api = python_bitbankcc.public()
private_api = python_bitbankcc.private(API_KEY, API_SECRET)

pair_cache = {}

convertable = {
    'btc': 'jpy',
    'xrp': 'jpy',
    'ltc': 'btc',
    'eth': 'btc',
    'mona': 'jpy',
    'bcc': 'jpy'
}


def get_jpy_rate(from_asset):
    if from_asset == 'jpy':
        return 1.0
    to_asset = convertable[from_asset]
    pair = f'{from_asset}_{to_asset}'