Example #1
0
    def load_bitflyer_server():
        import config
        import pybitflyer
        setting = config.get_setting()
        api = pybitflyer.API(api_key=setting["bitflyer"]["api_key"],
                             api_secret=setting["bitflyer"]["api_secret"])
        executions = api.executions(product_code="BTC_JPY", count=500)
        executions = pd.DataFrame.from_dict(executions)
        executions["exec_date"] = pd.to_datetime(executions["exec_date"])
        executions.index = executions["exec_date"]
        print(executions)

        # get bitflyer for target date(today - 90)
        target_date = datetime.datetime.today() - datetime.timedelta(days=365)
        end_date = executions.iloc[-1, 1]
        while target_date < end_date:
            end_date = executions.iloc[-1, 1]
            print(end_date)
            before = executions.iloc[-1, 2]
            e1 = api.executions(product_code="BTC_JPY",
                                count=500,
                                before=before)
            e1 = pd.DataFrame.from_dict(e1)
            e1["exec_date"] = pd.to_datetime(e1["exec_date"])
            e1.index = e1["exec_date"]
            executions = executions.append(e1)
            time.sleep(1)
        executions.to_csv("data/bitflyerBTC_JPY_executions.csv", index=None)
        return executions
Example #2
0
 def __init__(self, logger, parameters):
     self._publicapi = pybitflyer.API()
     self._logger = logger
     self._parameters = parameters
     self._timelast = 0   # 前回 ヘルスチェック を実行した時間
     self._parameters.server_health = "OTHER"
     self._last_board = {'mid_price': 0, 'bids': [], 'asks': []}
Example #3
0
    def load_bitflyer_server_365():
        import config
        import pybitflyer
        setting = config.get_setting()
        api = pybitflyer.API(api_key=setting["bitflyer"]["api_key"],
                             api_secret=setting["bitflyer"]["api_secret"])
        i = 12354
        executions = pd.read_csv("data/bitflyerBTC_JPY_executions_%d.csv" % i)

        # get bitflyer for target date(today - 90)
        target_date = datetime.datetime.today() - datetime.timedelta(days=365)

        end_date = datetime.datetime.strptime(executions.iloc[-1, 1],
                                              '%Y-%m-%d %H:%M:%S.%f')
        before = executions.iloc[-1, 2]
        while target_date < end_date:
            print(end_date)
            e1 = api.executions(product_code="BTC_JPY",
                                count=500,
                                before=before)
            e1 = pd.DataFrame.from_dict(e1)
            e1["exec_date"] = pd.to_datetime(e1["exec_date"])
            e1.index = e1["exec_date"]
            end_date = e1.iloc[-1, 1]
            before = e1.iloc[-1, 2]
            time.sleep(1)
            e1.to_csv("data/bitflyerBTC_JPY_executions_%s.csv" % i,
                      index=None,
                      header=None)
            i += 1
        executions.to_csv("data/bitflyerBTC_JPY_executions.csv", index=None)
        return executions
Example #4
0
    def __init__(self, balance=0.0, name=''):
        key = os.environ['API_KEY']
        secret = os.environ['API_SECRET']
        self.pbf = pybitflyer.API(api_key=key, api_secret=secret)
        self.side = 'no-position'
        self.positions = pd.DataFrame(columns=['price', 'size'])
        self.balance = balance
        self.income = 0
        self.child_orders = pd.DataFrame(
            columns=['child_order_id', 'expire_date', 'size', 'executed'])
        self.parent_orders = pd.DataFrame(columns=['parent_order_id'])
        self.child_acceptance_ids = []
        self.parent_acceptance_ids = []

        self.mid_price = 0
        self.bids = pd.DataFrame(columns=['price', 'size'])
        self.asks = pd.DataFrame(columns=['price', 'size'])

        #汎用 取引量抑えたりに使える
        self.cnt = 0

        self.name = name

        with open("/root/model/" + self.name + "/log.csv", mode="w") as logcsv:
            logcsv.write('timestamp,income\n')
Example #5
0
    def __init__(self):
        #pubnubから取得した約定履歴を保存するリスト
        self._lot = 0.1
        self._product_code = "FX_BTC_JPY"
        #何分足のデータを使うか.初期値は1分足.
        self._candleTerm = "1T"
        self._period = "60"
        self._number = 300

        #現在のポジション.1ならロング.-1ならショート.0ならポジションなし.
        self._pos = 0
        #onplanetz API key
        key = "Qw2S5685vueFFoUaGfeCcu"
        secret = "VKXc/Zwdx+38OTxtqpxaV6VUev5QCzIBe73fhjHSDWM="
        self.order = Order(key, secret)
        self.next_order_min = datetime.datetime.now()
        self.api = pybitflyer.API(key, secret)

        #ラインに稼働状況を通知
        self.line_notify_token = 'CHVGTfW9xeT3dPTTgJgMuhM5pBFQr2aZljEdlxw1rqY'
        self.line_notify_api = 'https://notify-api.line.me/api/notify'
        #証拠金
        self._margin = self.api.getcollateral()
        #注文執行コスト
        self._cost = 0
Example #6
0
def main():
    api = pybitflyer.API(api_key=key.bitflyer['key'],
                         api_secret=key.bitflyer['secret'])

    filename = 'test.pkl'

    with open(filename, mode="wb") as f:
        pass

    ret = api.executions(count=500)

    print(ret[0]['exec_date'])

    while True:
        executions = deque()
        for r in ret:
            executions.append(Execution(r))

        with open(filename, mode="ab") as f:
            pickle.dump(executions, f)

        print(executions[-1].exec_date)

        first_id = executions[-1].id

        time.sleep(3)
        ret = api.executions(before=first_id, count=500)
Example #7
0
def initAPI():
    """self.initData() -> None
    initialize the API of pybitflyer.
    """
    _api_timeout = 2.0
    if os.name == "nt":
        fpath = glob.glob(
            os.path.join(os.environ["USERPROFILE"], ".prv", "*.bitflyer"))[0]
    else:
        fpath = glob.glob(
            os.path.join(os.environ["HOME"], ".prv", "*.bitflyer"))[0]

    # raise the exception unless both an API key and an API secret key are not loaded.
    with open(fpath, "r", encoding="utf-8") as ff:
        try:
            _api_key = ff.readline().strip()
            _api_secret = ff.readline().strip()
        except Exception as ex:
            raise Exception(ex)

    api = pybitflyer.API(api_key=_api_key,
                         api_secret=_api_secret,
                         timeout=_api_timeout)

    try:
        endpoint = "/v1/markets"
        is_success = False
        while not is_success:
            try:
                currencies = api.request(endpoint)
                is_success = True
            except KeyboardInterrupt:
                raise KeyboardInterrupt
            except:
                continue
        if isinstance(currencies, list):
            print("Currency:")
            print([currency["product_code"] for currency in currencies])
        else:
            raise ValueError("No available currencies.")

        endpoint = "/v1/me/getpermissions"
        is_success = False
        while not is_success:
            try:
                permissions = api.request(endpoint)
                is_success = True
            except KeyboardInterrupt:
                raise KeyboardInterrupt
            except:
                continue
        if isinstance(permissions, list):
            print("Permitted API:")
            print(permissions)
        else:
            print("No permitted APIs.")
    except Exception as ex:
        raise Exception(ex)

    return api
Example #8
0
 def __init__(self, key, secret):
     self.product_code = "FX_BTC_JPY"
     self.key = key
     self.secret = secret
     self.api = pybitflyer.API(self.key, self.secret)
     #最新の注文リスト
     self.latest_exec_info = []
Example #9
0
    def __init__(self):
        #pubnubから取得した約定履歴を保存するリスト(基本的に不要.)
        self._executions = deque(maxlen=300)
        self._lot = 0.05
        self._margin = 15
        self._product_code = "FX_BTC_JPY"
        #各パラメタ.
        self._entryTerm = 5
        self._closeTerm = 15
        self._rangeTerm = 15
        self._rangeTh = 5000
        self._waitTerm = 5
        self._waitTh = 20000
        self._candleTerm = "1T"
        #現在のポジション.1ならロング.-1ならショート.0ならポジションなし.
        self._pos = 0
        #注文執行コスト.遅延などでこの値幅を最初から取られていると仮定する
        self._cost = 0.1
        self.order = Order()
        self.api = pybitflyer.API(
            "*****************************",
            "*******************************************")

        #ラインに稼働状況を通知
        self.line_notify_token = '******************************************'
        self.line_notify_api = 'https://notify-api.line.me/api/notify'
Example #10
0
 def __init__(self, config, pair, timeout, quiet=False):
     self.logger = logging.getLogger(__name__)
     self.bF = pybitflyer.API(api_key=config['bF']['api_key'],
                              api_secret=config['bF']['api_secret'])
     self.trade = config['trade']
     self.pair = pair
     self.timeout_delta = timedelta(seconds=int(timeout))
     self.quiet = quiet
     self.sfd_pins = np.array([0.05, 0.1, 0.15, 0.2])
     self.betting_system = self.trade.get('bet')
     self.contrary = self.trade.get('contrary')
     self.flash = self.trade.get('flash')
     self.retry = self.trade.get('retry')
     self.ticks = {}  # mutable
     self.open = None  # mutable
     self.won = False  # mutable
     self.n_load = 20  # mutable
     self.ewm_dv = {'mean': 0, 'var': 1}  # mutable
     self.bollinger = []  # mutable
     self.order_side = None  # mutable
     self.init_margin = None  # mutable
     self.margin = None  # mutable
     self.position = {}  # mutable
     self.sfd_penal_side = None  # mutable
     self.volumes = pd.DataFrame()  # mutable
     self.reserved = {}  # mutable
     self.order_datetime = None  # mutable
     self.last_open = {}  # mutable
     self.retried_side = None  # mutable
     self.anchor_margin = 0  # mutable
     self.n_size_over = 0  # mutable
     self.logger.debug(vars(self))
 def __init__(self):
     #config.jsonの読み込み
     f = open('config/config.json', 'r', encoding="utf-8")
     config = json.load(f)
     self.product_code = config["product_code"]
     self.key = config["key"]
     self.secret = config["secret"]
     self.api = pybitflyer.API(self.key, self.secret)
def set_api_info():
    api_info_dict = get_key_info(None)
    if api_info_dict:
        api = pybitflyer.API(api_key=api_info_dict["api_key"],
                             api_secret=api_info_dict["api_password"])
        return api
    else:
        print("api info set error....")
def index(request):

    # # 取得先のURL設定
    # base_url = 'https://api.bitflyer.jp'
    # endpoint = '/v1/board?product_code='
    # pair = 'FX_BTC_JPY'

    # # 1分間ごとにチェックする
    # time_count = 0 #時間計測(s)
    # limit = 3 #動かす最大時間(s)

    # while time_count < limit:

    #     # 値を取得
    #     data = requests.get(base_url + endpoint+pair, timeout=5).json()
    #     bids = data["bids"]
    #     asks = data["asks"]

    #      # 売り注文
    #     asks = asks[0]["price"] - 1
    #     print('売り注文:' + str(asks))

    #     # 買い注文
    #     bids = bids[0]["price"] + 1
    #     print('買い注文:' + str(bids))

    #     # 差額
    #     difference = asks - bids
    #     print('差額:' + str(difference))

    #     #処理を一定時間停止(一定時間ごとに起動)
    #     # time.sleep(0.1)
    #     #累計計測時間を調整
    #     time_count += 0.1
    #     #計測時間を超えた場合、処理中止
    #     if time_count > limit:
    #         break

    API_KEY = getApiKey()
    API_SECRET = getApiSecret()

    api = pybitflyer.API(api_key=API_KEY, api_secret=API_SECRET)

    balances = api.getbalance(product_code="BTC_JPY")
    print(balances)

    # buy_btc = api.sendchildorder(product_code="BTC_JPY",
    #                          child_order_type="MARKET",
    #                          side="SELL",
    #                          size=0.001,
    #                          minute_to_expire=10000,
    #                          time_in_force="GTC"
    # )

    dispList = []

    return JsonResponse(dispList, safe=False)
Example #14
0
def config_test():
    sql = "select * from entry"
    repository.read_sql(database=DATABASE, sql=sql)

    api = pybitflyer.API(api_key=Bitflyer.Api.value.KEY.value,
                         api_secret=Bitflyer.Api.value.SECRET.value)
    balance = api.getbalance()
    if "error_message" in balance:
        raise ConfigException()
Example #15
0
    def __init__(self, product, apiKey, apiSecret, path):

        self.api = pybitflyer.API(api_key=apiKey, api_secret=apiSecret)
        self.ticker = self.api.ticker(product_code=product)
        self.board = self.api.board(product_code=product)
        self.product = product
        self.apiKey = apiKey
        self.apiSecret = apiSecret
        self.path = path
Example #16
0
 def close(self):
     api = pybitflyer.API(api_key=os.environ['API_KEY'], api_secret=os.environ['API_SECRET'])
     positions = api.getpositions(product_code="FX_BTC_JPY")
     if len(positions) > 0:
         side = self.get_position_status(positions)
         size = sum([float(p.get('size')) for p in positions])
         return getattr(self, self.utils.reverse_action(side.lower()))(round(size, 4))
     else:
         return None
Example #17
0
 def sell(self, amount):
     api = pybitflyer.API(api_key=os.environ['API_KEY'], api_secret=os.environ['API_SECRET'])
     r = api.sendchildorder(product_code="FX_BTC_JPY",
                    child_order_type="MARKET",
                    side="SELL",
                    size=amount,
                    minute_to_expire=10000,
                    time_in_force="GTC"
                    )
     return r
Example #18
0
    def handler(self):

        self.key = self.key_edit.text()
        self.secret = self.secret_edit.text()
        self.api = pybitflyer.API(self.key, self.secret)
        res = self.api.gettradingcommission(product_code='FX_BTC_JPY')
        if 'commission_rate' in res:  # May be better to handle HTTP response status code.
            self.accept()
        else:
            QMessageBox.warning(self, 'Error', 'Invalid API key or secret!')
Example #19
0
def buy(currency='BTC', price=0):
    api = pybitflyer.API(api_key=os.env['BITFLYER_API_KEY'],
                         api_secret=os.env['BITFLYER_API_SECRET'])
    api.sendchildorder(product_code="%s_JPY" % currency,
                       child_order_type="MARKET",
                       side="BUY",
                       size=jpy_to_size(currency, price),
                       minute_to_expire=10000,
                       time_in_force="GTC")

    return
Example #20
0
 def __init__(self, setting):
     self.setting = setting
     self.exchangename = self.setting["realtime"]["exchange"]
     self.pair = self.setting["realtime"]["pair"]
     self.api_key = self.setting["bitflyer"]["api_key"]
     self.api_secret = self.setting["bitflyer"]["api_secret"]
     self.api = pybitflyer.API(api_key=self.api_key,
                               api_secret=self.api_secret)
     self.pirivatethreshold = 200  # per minutes per key
     self.publicthreshold = 500  # per minutes per ip
     self.expireorder = 30  # minute max:43200 (30 days)
     self.minimalOrder = 0.00000001  # 1 satoshi
Example #21
0
def main():

    #板情報を取得。本来API keyが必要だが、板情報取得だけなら不要。
    api = pybitflyer.API()

    #本来は以下のように指定する。
    #api = pybitflyer.API(api_key="...", api_secret="...")

    #BTC_JPYを指定して取得。
    board = api.board(product_code="BTC_JPY")

    #JSONに変換して表示する。
    print("{}".format(json.dumps(board, sort_keys=True, indent=4)))
Example #22
0
class Command(BaseCommand):
    print("key.py に情報を書き込みます。")

    api = input("api_keyを入力してください")
    secret = input("api_secretを入力してください")
    with open("key.py", "w") as key:
        key.write(f"api_key='{api}' \n")
        key.write(f"api_secret='{secret}' ")
    print("書き込みました。")
    bitflyerapi = pybitflyer.API(api, secret)
    balances = bitflyerapi.getbalance()[0]
    if "amount" in balances.keys():
        print("権限が与えられたapikeyです。")
    else:
        print("apikeyに権限がないようです。権限を確認してください。")
Example #23
0
 def get_balance(self):
     api = pybitflyer.API(api_key=os.environ['API_KEY'], api_secret=os.environ['API_SECRET'])
     result = {}
     positions = api.getpositions(product_code="FX_BTC_JPY")
     collateral = api.getcollateral()
     print(positions)
     if len(positions) > 0:
         pos = positions.pop()
         result["BTC"] = pos['size']
         result["JPY"] = 0.0
     else:
         result["BTC"] = 0.0
         result["JPY"] = collateral['collateral']
     print(result)
     return result
Example #24
0
    def buy_sell(self, ordertype, ordersize, orderprice,product,apiKey,apiSecret):
        api = pybitflyer.API(api_key=apiKey, api_secret=apiSecret)
        ticker = api.ticker(product_code=product)
        board = api.board(product_code=product)

        if ordertype == "BUY":
            contrary = "SELL"
            profit = int(orderprice * 1.002) # 買いポジのときの利確
            loss = int(orderprice * 0.99) # 同上、損切ライン
        elif ordertype == "SELL":
            contrary = "BUY"
            profit = int(orderprice * 0.998)
            loss = int(orderprice * 1.01)


        buy_btc = api.sendparentorder(
                                     order_method="IFDOCO",
                                     parameters=[{
                                         "product_code": product,
                                         "condition_type": "LIMIT",
                                         "side": ordertype, # 買いか?
                                         "price": orderprice,
                                         "size": ordersize
                                     },
                                         {
                                             "product_code": product,
                                             "condition_type": "LIMIT",
                                             "side": contrary,
                                             "price": profit, ###
                                             "size": ordersize ### 所持しているビットコインの数量を入れる
                                         },
                                         {
                                             "product_code": product,
                                             "condition_type": "STOP", # ストップ注文
                                             "side": contrary,
                                             "price": 0, # ここら??
                                             "trigger_price": loss,
                                             "size": ordersize
                                         }],
                                     #minute_to_expire=10000,
                                     #time_in_force="GTC"
                                     )

        print("ordered: "+ ordertype + str(ordersize) + "BTC at the price of " + str(orderprice))

        print(buy_btc)

        return buy_btc
Example #25
0
 def __init__(self, end_point, public_channels, private_channels, key,
              secret):
     self._end_point = end_point
     self._public_channels = public_channels
     self._private_channels = private_channels
     self._key = key
     self._secret = secret
     self._JSONRPC_ID_AUTH = 1
     self.position = 'no-position'
     self.asks = pd.DataFrame(columns=['price', 'size'])
     self.bids = pd.DataFrame(columns=['price', 'size'])
     self.httpclient = pybitflyer.API(api_key=key, api_secret=secret)
     self.span_before = time.time()
     self.request_count = 0
     self.parent_orders = pd.DataFrame(columns=[])
     self.child_orders = pd.DataFrame(columns=[])
Example #26
0
def bit_flyer_func():
    bid_list = []
    aks_list = []
    bit_flyer_api = pybitflyer.API()
    for i in range(60):
        ticker = bit_flyer_api.ticker(product_code="BTC_JPY")
        bid = ticker["best_bid"]
        ask = ticker["best_ask"]
        print("bid:" + str(bid))
        print("ask:" + str(ask))
        bid_list.append(bid)
        aks_list.append(ask)
        sleep(60)
    print("bid_list:" + str(bid_list))
    print("ask_list:" + str(aks_list))
    data.append(max(bid_list))
    data.append(min(bid_list))
    data.append(max(aks_list))
    data.append(min(aks_list))
    diff_max = int(data[0] - data[2])
    diff_min = int(data[1] - data[3])
    diff_max_min = int(data[0] - data[3])
    data.append(diff_max)
    data.append(diff_min)
    data.append(diff_max_min)
    print("bid_list" + str(bid_list))
    print("ask_list" + str(aks_list))

    # Display the data to be filled in the cell on the console
    result = 0
    while (result < len(data)):
        if result == 0:
            print("bid_max:" + str(data[result]))
        elif result == 1:
            print("bid_min:" + str(data[result]))
        elif result == 2:
            print("ask_max:" + str(data[result]))
        elif result == 3:
            print("ask_min:" + str(data[result]))
        elif result == 4:
            print("diff_max:" + str(data[result]))
        elif result == 5:
            print("diff_min:" + str(data[result]))
        else:
            print("diff_max_min:" + str(data[result]))
        result += 1
    return data
Example #27
0
 def get_balance(self):
     api = pybitflyer.API(api_key=os.environ['API_KEY'], api_secret=os.environ['API_SECRET'])
     result = {}
     positions = api.getpositions(product_code="FX_BTC_JPY")
     collateral = api.getcollateral()
     if len(positions) > 0:
         size = 0.0
         for pos in positions:
             if pos["side"] == "BUY":
                 size += float(pos['size'])
             else:
                 size += float(pos['size']) * -1
         result["BTC"] = size
         result["JPY"] = collateral['collateral']
     else:
         result["BTC"] = 0.0
         result["JPY"] = collateral['collateral']
     return result
Example #28
0
    def reset(self):
        BitFlyer.api = pybitflyer.API()

        self.listbox.delete(0, END)

        self.ret = self.getOrderBook()

        for i in range(BitFlyer.N if BitFlyer.N < len(self.ret['asks']) else
                       len(self.ret['asks'])):
            self.listbox.insert(END, '')

        for i in range(BitFlyer.N if BitFlyer.N < len(self.ret['bids']) else
                       len(self.ret['bids'])):
            self.listbox.insert(END, '')

        self.listbox.insert(END, '')

        self.listbox.see((BitFlyer.N if BitFlyer.N < len(self.ret['asks']) else
                          len(self.ret['asks'])) - 3)
Example #29
0
    def __init__(self):
        # ロガーの初期化
        self._logger = setup_logger()
        update_filehandler(self._logger)

        # パラメータ管理クラス
        self._parameters = parameters.Parameters(self._logger)

        if len(sys.argv) == 1:
            # configファイル読み込み
            self._parameters.load_config_file('trade.yaml')

        else:
            # configファイル読み込み
            self._parameters.load_config_file(sys.argv[1])

        if self._parameters._config[
                'apikey'] != '' and self._parameters._config['secret'] != '':
            # 売買用クラス
            self._api = pybitflyer.API(self._parameters._config['apikey'],
                                       self._parameters._config['secret'])
            self._order = bforder.order(self._logger,
                                        self._api,
                                        self._parameters,
                                        self,
                                        server_mode=True)
        else:
            self._order = None

        # データ保管用
        self._database = {}
        self._last_base_value = {}

        # データ更新中ロック
        self.lock = Lock()

        self.api = 0
        self._pos_history = {}
        self._today = -1
        self._minute = -1

        self._profit_history = deque(maxlen=1440)  # 1分毎、24H分の損益履歴
Example #30
0
 def collect_data(self):
     api = pybitflyer.API(api_key=os.environ['API_KEY'], api_secret=os.environ['API_SECRET'])
     board = api.board(product_code="FX_BTC_JPY")
     positions = api.getpositions(product_code="FX_BTC_JPY")
     require_collateral = 0.0
     profit = 0.0
     if len(positions) > 0:
         trade_id = hashlib.sha256(''.join([p['open_date'] for p in positions]).encode('utf-8')).hexdigest()[0:20]
         for position in positions:
             profit += float(position.get('pnl'))
             require_collateral += float(position.get('require_collateral'))
             #if position.get("side") == "BUY":
             #    # profit += (float(board.get("mid_price")) - float(position.get("price"))) * float(position.get("size"))
             #else:
             #    profit += (float(position.get("price")) - float(board.get("mid_price"))) * float(position.get("size"))
     else:
         positions = None
         profit = None
         trade_id = hashlib.sha256(str(datetime.now()).encode('utf-8')).hexdigest()[0:20]
     return {'trade_id': trade_id, 'price': board.get("mid_price"), 'positions': positions, 'profit': profit, 'require_collateral': require_collateral}