def create_coincheck_buy_order(symbol, amount): exchange_id = exchange.ExchangeId.COINCHECK client = CcxtClient(exchange_id) tick = client.fetch_tick() ask = float(tick.ask) bid = float(tick.bid) if amount < 0.005: n = int(amount * 1000) amount_buy = 0.007 amount_sell = 0.006 order_info = [] for _ in range(n): info = create_buy_order(exchange_id, ccxtconst.SYMBOL_BTC_JPY, amount_buy, ask) order_info.append(info) time.sleep(1) info = create_sell_order(exchange_id, ccxtconst.SYMBOL_BTC_JPY, amount_sell, bid) order_info.append(info) time.sleep(1) else: order_info = create_buy_order(exchange_id, symbol, amount, ask) return order_info
def ping(exchange_id, eff=False): client = CcxtClient(exchange_id, ccxtconst.SYMBOL_BTC_JPY) print("PING {}".format(exchange_id.value)) while True: start_timestamp = datetime.datetime.now() if not eff: tick = client.fetch_tick() else: tick = client.fetch_eff_tick() if tick: end_timestamp = datetime.datetime.now() ping_time_msec = round( (end_timestamp - start_timestamp).microseconds / 1000, 2) print("{} ping {} time={} ms ".format(start_timestamp, exchange_id, ping_time_msec)) else: print("{} can't access {}".format(start_timestamp, exchange_id)) time.sleep(1)
def create_bitbank_sell_order(symbol, amount): exchange_id = exchange.ExchangeId.BITBANK ex = Exchange(exchange_id, symbol) client = CcxtClient(exchange_id) tick = client.fetch_tick() bid = float(tick.bid) order_info = ex.order_sell(amount, bid) return order_info
def create_bitbank_buy_order(symbol, amount): exchange_id = exchange.ExchangeId.BITBANK ex = Exchange(exchange_id, symbol) client = CcxtClient(exchange_id) tick = client.fetch_tick() ask = float(tick.ask) order_info = ex.order_buy(amount, ask) return order_info
def fetch_ticks(exchange_id, symbol=ccxtconst.SYMBOL_BTC_JPY, eff=False): client = CcxtClient(exchange_id, symbol) while True: time.sleep(exchange.TICK_INTERVAL_SEC) if not eff: tick = client.fetch_tick() else: tick = client.fetch_eff_tick() if not tick: print("no data...") continue timestamp = dt.now_timestamp_ms() tick = Tick(timestamp, int(tick.bid), int(tick.ask)) print(tick)
def get_positions(exchange_id): client = CcxtClient(exchange_id) positions = client.get_positions() # 取得できる情報が多すぎるのて間引く data = [] for position in positions: if position["currentQty"] == 0: continue output = { "symbol": position["symbol"], "timestamp": position["openingTimestamp"], "size": position["currentQty"], } data.append(output) print(data)
def __init__(self, exchange_id, symbol): self.__exchange_id = exchange_id self.__symbol = symbol self.__queue = Queue() self.__wsclient = WebsocketClient(self.__queue, exchange_id, symbol) self.__ccxtclient = CcxtClient(exchange_id, symbol) self.__logger = get_ccxt_logger() self.bids = SortedDict() self.asks = SortedDict() self.__build_board() producer_worker = threading.Thread(target=self.__wsclient.fetch_ticks, daemon=True) consumer_worker = threading.Thread(target=self.__update_board, daemon=True) producer_worker.start() consumer_worker.start()
def fetch_balance(exchange_id): client = CcxtClient(exchange_id) return client.fetch_balance()['total']
def fetch_trades(exchange_id, mode=ccxtconst.TradeMode.NORMAL, since=None): client = CcxtClient(exchange_id) return client.fetch_trades(mode, since=since)
def save_ticks(): dir_path = _get_dir_path() os.mkdir(dir_path) bf_file_path = _get_file_path(dir_path, exchange.ExchangeId.BITFLYER) ex1_file_path = _get_file_path(dir_path, exchange.ExchangeId.COINCHECK) ex2_file_path = _get_file_path(dir_path, exchange.ExchangeId.LIQUID) bb_file_path = _get_file_path(dir_path, exchange.ExchangeId.BITBANK) fs_bf = open(bf_file_path, mode='w') fs_ex1 = open(ex1_file_path, mode='w') fs_ex2 = open(ex2_file_path, mode='w') fs_bb = open(bb_file_path, mode='w') header_string = 'timestamp,bid,ask\n' fs_bf.write(header_string) fs_ex1.write(header_string) fs_ex2.write(header_string) fs_bb.write(header_string) client_bf = CcxtClient(exchange.ExchangeId.BITFLYER) client_ex1 = CcxtClient(exchange.ExchangeId.COINCHECK) client_ex2 = CcxtClient(exchange.ExchangeId.LIQUID) client_bb = CcxtClient(exchange.ExchangeId.BITBANK) try: for _ in range(1000000): tick_bf = client_bf.fetch_tick() tick_ex1 = client_ex1.fetch_tick() tick_ex2 = client_ex2.fetch_tick() tick_bb = client_bb.fetch_tick() if tick_bf and tick_ex1 and tick_ex2 and tick_bb: output_bf = _format_csv(tick_bf.timestamp, tick_bf.bid, tick_bf.ask) output_ex1 = _format_csv(tick_ex1.timestamp, tick_ex1.bid, tick_ex1.ask) output_ex2 = _format_csv(tick_ex2.timestamp, tick_ex2.bid, tick_ex2.ask) output_bb = _format_csv(tick_bb.timestamp, tick_bb.bid, tick_bb.ask) fs_bf.write(output_bf + '\n') fs_bf.flush() fs_ex1.write(output_ex1 + '\n') fs_ex1.flush() fs_ex2.write(output_ex2 + '\n') fs_ex2.flush() fs_bb.write(output_bb + '\n') fs_bb.flush() time.sleep(exchange.TICK_INTERVAL_SEC) else: time.sleep(10) finally: fs_bf.close() fs_ex1.close() fs_ex2.close() fs_bb.close()
class Board(): def __init__(self, exchange_id, symbol): self.__exchange_id = exchange_id self.__symbol = symbol self.__queue = Queue() self.__wsclient = WebsocketClient(self.__queue, exchange_id, symbol) self.__ccxtclient = CcxtClient(exchange_id, symbol) self.__logger = get_ccxt_logger() self.bids = SortedDict() self.asks = SortedDict() self.__build_board() producer_worker = threading.Thread(target=self.__wsclient.fetch_ticks, daemon=True) consumer_worker = threading.Thread(target=self.__update_board, daemon=True) producer_worker.start() consumer_worker.start() def __append_to_board(self, board, order_list): if len(order_list) == 0: return for order in order_list: rate = int(float(order[0])) amount = float(order[1]) if amount != 0: board[rate] = amount elif rate in board: del board[rate] def __build_board(self): res = self.__ccxtclient.fetch_order_book() bids = res["bids"] asks = res["asks"] self.__append_to_board(self.bids, bids) self.__append_to_board(self.asks, asks) def __update_board(self): while True: if not self.__queue.empty(): data = self.__queue.get() if data.type == WsDataType.TRADES: self.__remove_order(data) else: self.__append_order(data) self.__queue.task_done() def __append_order(self, data): self.__append_to_board(self.bids, data.bids) self.__append_to_board(self.asks, data.asks) def __remove_order(self, data): rate = int(data.rate) amount = data.amount side = data.side if data.side == "sell": board = self.bids else: board = self.asks if amount != 0: if rate in board: board[rate] = float( Decimal(str(board[rate])) - Decimal(str(amount))) if board[rate] <= 0: del board[rate] elif rate in board: del board[rate] rates = [] if side == 'sell': for k in board.keys()[::-1]: if k > rate: rates.append(k) else: break else: for k in board.keys(): if k < rate: rates.append(k) else: break for rate in rates: del board[rate] def __logging_tick(self, bid, ask): self.__logger.info('tick bid=%s ask=%s (%s:%s)', bid, ask, self.__exchange_id.value, self.__symbol) def get_eff_tick(self, amount=1.0): bids = self.bids.items()[::-1] asks = self.asks.items() if len(bids) == 0 or len(asks) == 0: return None bid_total_amount = 0 bid_rate = bids[0][0] for bid in bids: bid_total_amount += bid[1] if bid_total_amount >= amount: bid_rate = bid[0] break ask_total_amount = 0 ask_rate = asks[0][0] for ask in asks: ask_total_amount += ask[1] if ask_total_amount >= amount: ask_rate = ask[0] break self.__logging_tick(bid_rate, ask_rate) timestamp = dt.now_timestamp_ms() tick = Tick(self.__exchange_id, timestamp, bid_rate, ask_rate) return tick def display(self): print("=== bids(買い注文) ===") print(list(self.bids.items())) print("=== asks(売り注文) ===") print(list(self.asks.items())) print()
def _get_tick(self, exchange_id): c = CcxtClient(exchange_id) tick = c.fetch_tick() return tick.bid, tick.ask
class ExchangeTrading(ExchangeBase): def __init__(self, exchange_id, symbol, demo_mode=False): self.exchange_id = exchange_id self.symbol = symbol self.demo_mode = demo_mode self.client = CcxtClient(exchange_id, symbol, demo_mode=demo_mode) def fetch_tick(self, eff=False): if not eff: return self.client.fetch_tick() else: # 取引が成立しないのでamountを設定しない。 # return self.client.fetch_eff_tick() return self.client.fetch_eff_tick() def _format_order_response(self, response, amount, extinfo=None): info = response["info"] def _to_json(jpy, btc, rate): return { "exchange_id": self.exchange_id.value, "symbol": self.symbol, "jpy": format_jpy_float(jpy), "btc": btc, "rate": rate } if self.exchange_id == exchange.ExchangeId.COINCHECK: btc = float(amount) rate = float(extinfo) if info["order_type"] == "market_buy": jpy = float(info["market_buy_amount"]) else: jpy = rate * btc return _to_json(jpy, btc, rate) elif self.exchange_id == exchange.ExchangeId.LIQUID: btc = float(info["quantity"]) rate = float(info["price"]) jpy = rate * btc return _to_json(jpy, btc, rate) elif amount and extinfo: btc = amount rate = extinfo jpy = rate * btc return _to_json(jpy, btc, rate) else: return {} def order_buy(self, amount, extinfo_ask=None): # coincheckは amountにBTCではなくて、JPYを指定する。 # https://coincheck.com/ja/documents/exchange/api#order-new if self.exchange_id == exchange.ExchangeId.COINCHECK: # coincheckでは buyでどうも実際よりも低い値で注文が成立されるので # 補正値でrequestを出してみる adjusted_amount = amount + COINCHECK_ORDER_BUY_ADJUST_AMOUNT_BTC price = int(extinfo_ask * adjusted_amount) response = self.client.create_market_buy_order(price) else: response = self.client.create_market_buy_order(amount) if self.demo_mode or not response: return None else: return self._format_order_response(response, amount, extinfo=extinfo_ask) def order_sell(self, amount, extinfo_bid=None): response = self.client.create_market_sell_order(amount) if self.demo_mode or not response: return None else: return self._format_order_response(response, amount, extinfo=extinfo_bid)
def __init__(self, exchange_id, symbol, demo_mode=False): self.exchange_id = exchange_id self.symbol = symbol self.demo_mode = demo_mode self.client = CcxtClient(exchange_id, symbol, demo_mode=demo_mode)
def fetch_tick(exchange_id, symbol=ccxtconst.SYMBOL_BTC_JPY): client = CcxtClient(exchange_id, symbol) return client.fetch_tick()
def fetch_open_orders(exchange_id): client = CcxtClient(exchange_id) open_orders = client.fetch_open_orders() print(open_orders)
def symbols(c, exchange_id): __exchange_id = exchange.EXCHANGE_ID_DICT[exchange_id] c = CcxtClient(__exchange_id) print(c.symbols())
def _get_tick(exchange_id): c = CcxtClient(exchange_id) tick = c.fetch_tick() return tick["bid"], tick["ask"]