update
This commit is contained in:
parent
37840311e0
commit
1edfa96cde
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
__pycache__/
|
||||
/secret.json
|
330
bitbank.py
Normal file
330
bitbank.py
Normal file
@ -0,0 +1,330 @@
|
||||
import asyncio
|
||||
import datetime
|
||||
import logging
|
||||
import pybotters
|
||||
|
||||
import logic
|
||||
import util.candlestick
|
||||
import util.depth
|
||||
import util.pair
|
||||
import util.ticker
|
||||
|
||||
|
||||
PUBLIC_API_ENTRYPOINT = "https://public.bitbank.cc"
|
||||
PRIVATE_API_ENTRYPOINT = "https://api.bitbank.cc/v1"
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
_k = asyncio.Lock()
|
||||
|
||||
async def init(cli):
|
||||
pair = Pair(cli, "mona_jpy")
|
||||
logic.Hige(
|
||||
logging.getLogger("bitbank/mona/Hige"),
|
||||
pair, 51)
|
||||
|
||||
pair = Pair(cli, "btc_jpy")
|
||||
logic.Hige(
|
||||
logging.getLogger("bitbank/btc/Hige"),
|
||||
pair, 0.001)
|
||||
|
||||
pair = Pair(cli, "eth_jpy")
|
||||
logic.MM(
|
||||
logging.getLogger("bitbank/eth/MM"),
|
||||
pair, 0.001, 1)
|
||||
logic.Hige(
|
||||
logging.getLogger("bitbank/eth/Hige"),
|
||||
pair, 0.001)
|
||||
|
||||
|
||||
class Pair(util.pair.Pair):
|
||||
def __init__(self, cli, name):
|
||||
super().__init__(name)
|
||||
self._cli = cli
|
||||
self._store = pybotters.bitbankDataStore()
|
||||
|
||||
self.ticker = Ticker(self._store, name)
|
||||
|
||||
#self.candlestick_1s = Candlestick(cli, self.ticker, None, 1)
|
||||
#self.candlestick_1m = Candlestick(cli, self.ticker, "1min", 60)
|
||||
#self.candlestick_1h = Candlestick(cli, self.ticker, "1hour", 60*60)
|
||||
|
||||
self.depth = Depth(self._store)
|
||||
|
||||
asyncio.create_task(cli.ws_connect(
|
||||
'wss://stream.bitbank.cc/socket.io/?EIO=3&transport=websocket',
|
||||
send_str=[
|
||||
f'42["join-room","ticker_{name}"]',
|
||||
f'42["join-room","transactions_{name}"]',
|
||||
f'42["join-room","depth_whole_{name}"]',
|
||||
f'42["join-room","depth_diff_{name}"]',
|
||||
],
|
||||
hdlr_str = self._store.onmessage,
|
||||
))
|
||||
|
||||
async def _order(self, amount, side, type, trigger = None, price = None, post_only = None):
|
||||
data = {
|
||||
"pair" : self.name,
|
||||
"amount": str(amount),
|
||||
"side" : side,
|
||||
"type" : type,
|
||||
}
|
||||
if price is not None: data["price"] = price
|
||||
if trigger is not None: data["trigger_price"] = trigger
|
||||
if post_only is not None: data["post_only"] = post_only
|
||||
async with _k:
|
||||
res = await self._cli.post(PRIVATE_API_ENTRYPOINT+"/user/spot/order", data=data)
|
||||
res = await res.json()
|
||||
_check_response(res)
|
||||
return Order(self._cli, self, res["data"]["order_id"])
|
||||
|
||||
def buy_market(self, amount):
|
||||
return self._order(amount, "buy", "market")
|
||||
|
||||
def sell_market(self, amount):
|
||||
return self._order(amount, "sell", "market")
|
||||
|
||||
def buy_limit(self, amount, price, post_only = False):
|
||||
return self._order(amount, "buy", "limit", None, price, post_only)
|
||||
|
||||
def sell_limit(self, amount, price, post_only = False):
|
||||
return self._order(amount, "sell", "limit", None, price, post_only)
|
||||
|
||||
def buy_stop(self, amount, trigger):
|
||||
return self._order(amount, "buy", "stop", trigger)
|
||||
|
||||
def sell_stop(self, amount, trigger):
|
||||
return self._order(amount, "sell", "stop", trigger)
|
||||
|
||||
def buy_stop_limit(self, amount, trigger, price):
|
||||
return self._order(amount, "buy", "stop", trigger, price)
|
||||
|
||||
def sell_stop_limit(self, amount, trigger, price):
|
||||
return self._order(amount, "sell", "stop", trigger, price)
|
||||
|
||||
|
||||
class Order(util.pair.Order):
|
||||
def __init__(self, cli, pair, id):
|
||||
super().__init__()
|
||||
self._cli = cli
|
||||
self._pair = pair
|
||||
self._id = id
|
||||
|
||||
async def update(self):
|
||||
async with _k:
|
||||
res = await self._cli.get(PRIVATE_API_ENTRYPOINT+"/user/spot/order", params={
|
||||
"pair": self._pair.name,
|
||||
"order_id": self._id,
|
||||
})
|
||||
res = await res.json()
|
||||
_check_response(res)
|
||||
res = res["data"]
|
||||
self.amount = float(res["start_amount"])
|
||||
self.remain = float(res["remaining_amount"])
|
||||
self.price = float(res["average_price"])
|
||||
self.done = \
|
||||
res["status"] == "FULLY_FILLED" or \
|
||||
res["status"] == "CANCELED_UNFILLED" or \
|
||||
res["status"] == "CANCELED_PARTIALLY_FILLED"
|
||||
|
||||
async def cancel(self):
|
||||
async with _k:
|
||||
res = await self._cli.post(PRIVATE_API_ENTRYPOINT+"/user/spot/cancel_order", data={
|
||||
"pair": self._pair.name,
|
||||
"order_id": self._id,
|
||||
})
|
||||
res = await res.json()
|
||||
_check_response(res)
|
||||
|
||||
|
||||
class Ticker(util.ticker.Ticker):
|
||||
def __init__(self, store, pair):
|
||||
super().__init__(pair)
|
||||
self._store = store
|
||||
asyncio.create_task(self._main())
|
||||
|
||||
async def _main(self):
|
||||
while True:
|
||||
await self._store.ticker.wait()
|
||||
ticker = self._store.ticker.find()
|
||||
for i in range(len(ticker)):
|
||||
if ticker[i]["pair"] == self.pair:
|
||||
self.price = float(ticker[i]["last"])
|
||||
self.sell = float(ticker[i]["sell"])
|
||||
self.buy = float(ticker[i]["buy"])
|
||||
self.volume = float(ticker[i]["vol"])
|
||||
self.ts = int(ticker[i]["timestamp"])
|
||||
self._event.set()
|
||||
self._event.clear()
|
||||
break
|
||||
|
||||
|
||||
class Candlestick(util.candlestick.Candlestick):
|
||||
def __init__(self, cli, ticker, unit, interval):
|
||||
super().__init__(ticker, interval)
|
||||
self._cli = cli
|
||||
self._unit = unit
|
||||
|
||||
async def _fetch(self, date, depth = 0, rem = util.candlestick.MAX_CANDLES):
|
||||
if self._unit is None:
|
||||
return []
|
||||
|
||||
long_term = \
|
||||
self._unit == "4hour" or \
|
||||
self._unit == "8hour" or \
|
||||
self._unit == "12hour" or \
|
||||
self._unit == "1day" or \
|
||||
self._unit == "1week" or \
|
||||
self._unit == "1month"
|
||||
if long_term:
|
||||
strdate = date.strftime("%Y")
|
||||
else:
|
||||
strdate = date.strftime("%Y%m%d")
|
||||
|
||||
pair = self._ticker.pair
|
||||
async with _k:
|
||||
data = await self._cli.get(PUBLIC_API_ENTRYPOINT+f"/{pair}/candlestick/{self._unit}/{strdate}")
|
||||
data = await data.json()
|
||||
_check_response(data)
|
||||
data = data["data"]["candlestick"][0]["ohlcv"]
|
||||
|
||||
first_index = 0
|
||||
if depth == 0: first_index = 1
|
||||
|
||||
ret = []
|
||||
for i in range(first_index, len(data)):
|
||||
ret.append([
|
||||
float(data[i][0]),
|
||||
float(data[i][1]),
|
||||
float(data[i][2]),
|
||||
float(data[i][3]),
|
||||
])
|
||||
|
||||
if len(ret) < rem:
|
||||
back = datetime.timedelta(days=1)
|
||||
if long_term:
|
||||
back = datetime.timedelta(years=1)
|
||||
ret = [*ret, *await self._fetch(date-back, depth+1, rem-len(ret))]
|
||||
return ret
|
||||
|
||||
|
||||
class Depth(util.depth.Depth):
|
||||
def __init__(self, store):
|
||||
super().__init__()
|
||||
self._store = store
|
||||
asyncio.create_task(self._main())
|
||||
|
||||
async def _main(self):
|
||||
while True:
|
||||
await self._store.depth.wait()
|
||||
items = self._store.depth.sorted()
|
||||
asks = items["asks"]
|
||||
bids = items["bids"]
|
||||
|
||||
self.asks = []
|
||||
for i in range(len(asks)):
|
||||
self.asks.append([float(asks[i][0]), float(asks[i][1])])
|
||||
self.bids = []
|
||||
for i in range(len(bids)):
|
||||
self.bids.append([float(bids[i][0]), float(bids[i][1])])
|
||||
self._event.set()
|
||||
self._event.clear()
|
||||
|
||||
|
||||
def _check_response(res):
|
||||
if res["success"] == 1:
|
||||
return
|
||||
|
||||
code = str(res["data"]["code"])
|
||||
if code in ERROR_CODES:
|
||||
raise Exception(ERROR_CODES[code])
|
||||
raise Exception("unknown error")
|
||||
|
||||
ERROR_CODES = {
|
||||
'10000': 'URLが存在しません',
|
||||
'10001': 'システムエラーが発生しました。サポートにお問い合わせ下さい',
|
||||
'10002': '不正なJSON形式です。送信内容をご確認下さい',
|
||||
'10003': 'システムエラーが発生しました。サポートにお問い合わせ下さい',
|
||||
'10005': 'タイムアウトエラーが発生しました。しばらく間をおいて再度実行して下さい',
|
||||
'20001': 'API認証に失敗しました',
|
||||
'20002': 'APIキーが不正です',
|
||||
'20003': 'APIキーが存在しません',
|
||||
'20004': 'API Nonceが存在しません',
|
||||
'20005': 'APIシグネチャが存在しません',
|
||||
'20011': '2段階認証に失敗しました',
|
||||
'20014': 'SMS認証に失敗しました',
|
||||
'20023': '2段階認証コードを入力して下さい',
|
||||
'20024': 'SMS認証コードを入力して下さい',
|
||||
'20025': '2段階認証コードとSMS認証コードを入力して下さい',
|
||||
'20026': '一定回数以上2段階認証に失敗したためロックしました。60秒待ってから再度お試しください',
|
||||
'30001': '注文数量を指定して下さい',
|
||||
'30006': '注文IDを指定して下さい',
|
||||
'30007': '注文ID配列を指定して下さい',
|
||||
'30009': '銘柄を指定して下さい',
|
||||
'30012': '注文価格を指定して下さい',
|
||||
'30013': '売買どちらかを指定して下さい',
|
||||
'30015': '注文タイプを指定して下さい',
|
||||
'30016': 'アセット名を指定して下さい',
|
||||
'30019': 'uuidを指定して下さい',
|
||||
'30039': '出金額を指定して下さい',
|
||||
'30101': 'トリガー価格を指定してください',
|
||||
'40001': '注文数量が不正です',
|
||||
'40006': 'count値が不正です',
|
||||
'40007': '終了時期が不正です',
|
||||
'40008': 'end_id値が不正です',
|
||||
'40009': 'from_id値が不正です',
|
||||
'40013': '注文IDが不正です',
|
||||
'40014': '注文ID配列が不正です',
|
||||
'40015': '指定された注文が多すぎます',
|
||||
'40017': '銘柄名が不正です',
|
||||
'40020': '注文価格が不正です',
|
||||
'40021': '売買区分が不正です',
|
||||
'40022': '開始時期が不正です',
|
||||
'40024': '注文タイプが不正です',
|
||||
'40025': 'アセット名が不正です',
|
||||
'40028': 'uuidが不正です',
|
||||
'40048': '出金額が不正です',
|
||||
'40112': 'トリガー価格が不正です',
|
||||
'40113': 'post_only値が不正です',
|
||||
'40114': 'Post Onlyはご指定の注文タイプでは指定できません',
|
||||
'50003': '現在、このアカウントはご指定の操作を実行できない状態となっております。サポートにお問い合わせ下さい',
|
||||
'50004': '現在、このアカウントは仮登録の状態となっております。アカウント登録完了後、再度お試し下さい',
|
||||
'50005': '現在、このアカウントはロックされております。サポートにお問い合わせ下さい',
|
||||
'50006': '現在、このアカウントはロックされております。サポートにお問い合わせ下さい',
|
||||
'50008': 'ユーザの本人確認が完了していません',
|
||||
'50009': 'ご指定の注文は存在しません',
|
||||
'50010': 'ご指定の注文はキャンセルできません',
|
||||
'50011': 'APIが見つかりません',
|
||||
'50026': 'ご指定の注文は既にキャンセル済みです',
|
||||
'50027': 'ご指定の注文は既に約定済みです',
|
||||
'60001': '保有数量が不足しています',
|
||||
'60002': '成行買い注文の数量上限を上回っています',
|
||||
'60003': '指定した数量が制限を超えています',
|
||||
'60004': '指定した数量がしきい値を下回っています',
|
||||
'60005': '指定した価格が上限を上回っています',
|
||||
'60006': '指定した価格が下限を下回っています',
|
||||
'60011': '同時発注制限件数(30件)を上回っています',
|
||||
'60016': '指定したトリガー価格が上限を上回っています',
|
||||
'70001': 'システムエラーが発生しました。サポートにお問い合わせ下さい',
|
||||
'70002': 'システムエラーが発生しました。サポートにお問い合わせ下さい',
|
||||
'70003': 'システムエラーが発生しました。サポートにお問い合わせ下さい',
|
||||
'70004': '現在取引停止中のため、注文を承ることができません',
|
||||
'70005': '現在買い注文停止中のため、注文を承ることができません',
|
||||
'70006': '現在売り注文停止中のため、注文を承ることができません',
|
||||
'70009': 'ただいま成行注文を一時的に制限しています。指値注文をご利用ください',
|
||||
'70010': 'ただいまシステム負荷が高まっているため、最小注文数量を一時的に引き上げています',
|
||||
'70011': 'ただいまリクエストが混雑してます。しばらく時間を空けてから再度リクエストをお願いします',
|
||||
'70012': 'システムエラーが発生しました。サポートにお問い合わせ下さい',
|
||||
'70013': 'ただいまシステム負荷が高まっているため、注文および注文キャンセルを一時的に制限しています',
|
||||
'70014': 'ただいまシステム負荷が高まっているため、出金申請および出金申請キャンセルを一時的に制限しています',
|
||||
'70015': 'ただいまシステム負荷が高まっているため、貸出申請および貸出申請キャンセルを一時的に制限しています',
|
||||
'70016': '貸出申請および貸出申請キャンセル停止中のため、リクエストを承ることができません',
|
||||
'70017': '指定された銘柄は注文停止中のため、リクエストを承ることができません',
|
||||
'70018': '指定された銘柄は注文およびキャンセル停止中のため、リクエストを承ることができません',
|
||||
'70019': '注文はキャンセル中です',
|
||||
'70020': '現在成行注文停止中のため、注文を承ることができません',
|
||||
'70021': '指値注文価格が乖離率を超過しています',
|
||||
'70022': '現在逆指値指値注文停止中のため、注文を承ることができません',
|
||||
'70023': '現在逆指値成行注文停止中のため、注文を承ることができません'
|
||||
}
|
2
logic/__init__.py
Normal file
2
logic/__init__.py
Normal file
@ -0,0 +1,2 @@
|
||||
from logic.mm import MM
|
||||
from logic.hige import Hige
|
74
logic/hige.py
Normal file
74
logic/hige.py
Normal file
@ -0,0 +1,74 @@
|
||||
import asyncio
|
||||
|
||||
class Hige:
|
||||
def __init__(self, logger, pair, lot):
|
||||
self._logger = logger
|
||||
self._pair = pair
|
||||
self._lot = lot
|
||||
|
||||
self._remain = 0
|
||||
|
||||
self._sell = None
|
||||
self._buy = None
|
||||
|
||||
self._sell_price = 0
|
||||
self._buy_price = 0
|
||||
|
||||
self._total = 0
|
||||
|
||||
asyncio.create_task(self._main())
|
||||
|
||||
async def _main(self):
|
||||
self._logger.info("started")
|
||||
while True:
|
||||
pair = self._pair
|
||||
depth = pair.depth
|
||||
|
||||
if len(depth.bids) == 0 or len(depth.asks) == 0:
|
||||
await depth.wait()
|
||||
continue
|
||||
|
||||
vol_per_sec = pair.ticker.volume / 24 / 3600
|
||||
delta = 0.001 * pair.ticker.price
|
||||
|
||||
expected_sell_price = depth.asks[0][0] + delta
|
||||
expected_buy_price = depth.bids[0][0] - delta
|
||||
|
||||
if self._sell is not None:
|
||||
await asyncio.sleep(0.5)
|
||||
await self._sell.update()
|
||||
if self._sell.done:
|
||||
amount = self._sell.amount - self._sell.remain
|
||||
if amount > 0:
|
||||
income = amount*self._sell.price
|
||||
self._total += income
|
||||
self._logger.info(f"<SELL> {amount} / {income} ({self._total})")
|
||||
self._remain -= amount
|
||||
self._sell = None
|
||||
continue
|
||||
elif self._sell_price != expected_sell_price:
|
||||
await self._sell.cancel()
|
||||
continue
|
||||
elif self._remain >= self._lot*2:
|
||||
self._sell_price = expected_sell_price
|
||||
self._sell = await pair.sell_limit(self._lot, self._sell_price)
|
||||
|
||||
if self._buy is not None:
|
||||
await asyncio.sleep(0.5)
|
||||
await self._buy.update()
|
||||
if self._buy.done:
|
||||
amount = self._buy.amount - self._buy.remain
|
||||
if amount > 0:
|
||||
outgo = amount*self._buy.price
|
||||
self._total -= outgo
|
||||
self._logger.info(f"<BUY> {amount} / {outgo} ({self._total})")
|
||||
self._remain += amount
|
||||
self._buy = None
|
||||
continue
|
||||
elif self._buy_price != expected_buy_price:
|
||||
await self._buy.cancel()
|
||||
continue
|
||||
elif self._remain <= self._lot*3:
|
||||
self._buy_price = expected_buy_price
|
||||
self._buy = await pair.buy_limit(self._lot, self._buy_price)
|
||||
await asyncio.sleep(5)
|
132
logic/mm.py
Normal file
132
logic/mm.py
Normal file
@ -0,0 +1,132 @@
|
||||
import asyncio
|
||||
|
||||
|
||||
RESET_RATIO = 0
|
||||
|
||||
class MM:
|
||||
def __init__(self, logger, pair, lot, epsilon):
|
||||
self._logger = logger
|
||||
self._pair = pair
|
||||
self._lot = lot
|
||||
self._remain = 0
|
||||
self._epsilon = epsilon
|
||||
|
||||
self._buy_price = None
|
||||
self._sell_price = None
|
||||
self._buy = None
|
||||
self._sell = None
|
||||
|
||||
self._buy_amount_sum = 0
|
||||
self._sell_amount_sum = 0
|
||||
self._income_sum = 0
|
||||
self._outgo_sum = 0
|
||||
|
||||
self._total = 0
|
||||
|
||||
asyncio.create_task(self._main())
|
||||
|
||||
async def _main(self):
|
||||
self._logger.info("started")
|
||||
while True:
|
||||
pair = self._pair
|
||||
depth = pair.depth
|
||||
|
||||
await depth.wait()
|
||||
if len(depth.bids) == 0 or len(depth.asks) == 0:
|
||||
continue
|
||||
|
||||
ask = depth.asks[0][0]
|
||||
bid = depth.bids[0][0]
|
||||
enough_spread = (ask-bid) > self._epsilon*2
|
||||
|
||||
# calculate buy/sell thresh
|
||||
buy_max = 1e100
|
||||
sell_min = 0
|
||||
if self._sell_amount_sum > 0:
|
||||
buy_max = self._income_sum / self._sell_amount_sum
|
||||
if self._buy_amount_sum > 0:
|
||||
sell_min = self._outgo_sum / self._buy_amount_sum
|
||||
|
||||
loss_cut = \
|
||||
(buy_max - bid)/bid > 0.1 or \
|
||||
(ask - sell_min)/ask > 0.1
|
||||
|
||||
# reset thresh if stock is consumed or to do cut loss
|
||||
if self._remain < self._lot or loss_cut:
|
||||
self._sell_amount_sum = 0
|
||||
self._income_sum = 0
|
||||
self._buy_amount_sum = 0
|
||||
self._outgo_sum = 0
|
||||
|
||||
if self._sell is not None:
|
||||
# check current SELL order
|
||||
await asyncio.sleep(0.5)
|
||||
await self._sell.update()
|
||||
|
||||
# get highest ask
|
||||
if ask == self._sell_price and depth.asks[0][1] > self._sell.remain:
|
||||
ask = depth.asks[1][0]
|
||||
|
||||
if self._sell.done:
|
||||
amount = self._sell.amount - self._sell.remain
|
||||
if amount > 0:
|
||||
income = amount*self._sell.price
|
||||
self._sell_amount_sum += amount
|
||||
self._income_sum += income
|
||||
self._total += income
|
||||
self._logger.info(f"<SELL> {amount} / {income} ({self._total})")
|
||||
self._remain -= self._sell.amount - self._sell.remain
|
||||
self._sell = None
|
||||
elif self._sell_price != max(sell_min, ask-self._epsilon):
|
||||
try:
|
||||
await self._sell.cancel()
|
||||
except Exception:
|
||||
pass
|
||||
elif enough_spread:
|
||||
# order SELL
|
||||
self._sell_price = max(sell_min, ask-self._epsilon)
|
||||
amount = self._lot
|
||||
if self._remain > self._lot*2:
|
||||
amount = self._remain - self._lot
|
||||
elif self._remain < self._lot:
|
||||
amount = 0
|
||||
if amount > 0:
|
||||
self._sell = await self._order_sell(amount)
|
||||
|
||||
if self._buy is not None:
|
||||
# check current BUY order
|
||||
await asyncio.sleep(0.5)
|
||||
await self._buy.update()
|
||||
|
||||
# get lowest bid
|
||||
if bid == self._buy_price and depth.bids[0][1] > self._buy.remain:
|
||||
bid = depth.bids[1][0]
|
||||
|
||||
if self._buy.done:
|
||||
amount = self._buy.amount - self._buy.remain
|
||||
if amount > 0:
|
||||
outgo = amount*self._buy.price
|
||||
self._buy_amount_sum += amount
|
||||
self._outgo_sum += outgo
|
||||
self._total -= outgo
|
||||
self._logger.info(f"<BUY> {amount} / {outgo} ({self._total})")
|
||||
self._remain += self._buy.amount - self._buy.remain
|
||||
self._buy = None
|
||||
elif self._buy_price != min(buy_max, bid+self._epsilon):
|
||||
try:
|
||||
await self._buy.cancel()
|
||||
except Exception:
|
||||
pass
|
||||
elif enough_spread:
|
||||
# order BUY
|
||||
self._buy_price = min(buy_max, bid+self._epsilon)
|
||||
amount = self._lot
|
||||
if self._remain > self._lot*2:
|
||||
amount = 0
|
||||
if amount > 0:
|
||||
self._buy = await self._order_buy(amount)
|
||||
|
||||
async def _order_sell(self, amount):
|
||||
return await self._pair.sell_limit(amount, self._sell_price, True)
|
||||
async def _order_buy(self, amount):
|
||||
return await self._pair.buy_limit(amount, self._buy_price, True)
|
32
main.py
Normal file
32
main.py
Normal file
@ -0,0 +1,32 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import pybotters
|
||||
import signal
|
||||
|
||||
import bitbank
|
||||
|
||||
|
||||
async def main():
|
||||
alive = True
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
|
||||
def teardown():
|
||||
nonlocal alive
|
||||
alive = False
|
||||
for t in asyncio.all_tasks():
|
||||
t.cancel()
|
||||
|
||||
loop = asyncio.get_event_loop()
|
||||
loop.add_signal_handler(signal.SIGTERM, teardown)
|
||||
loop.add_signal_handler(signal.SIGINT, teardown)
|
||||
|
||||
async with pybotters.Client(apis="secret.json") as cli:
|
||||
await asyncio.gather(bitbank.init(cli))
|
||||
while alive: await asyncio.sleep(0.5)
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
loop = asyncio.new_event_loop()
|
||||
loop.run_until_complete(main())
|
||||
finally:
|
||||
loop.close()
|
1
requirements.txt
Normal file
1
requirements.txt
Normal file
@ -0,0 +1 @@
|
||||
pybotters
|
62
util/candlestick.py
Normal file
62
util/candlestick.py
Normal file
@ -0,0 +1,62 @@
|
||||
import asyncio
|
||||
import datetime
|
||||
|
||||
|
||||
MAX_CANDLES = 200
|
||||
|
||||
OPEN = 0
|
||||
HIGH = 0
|
||||
LOW = 0
|
||||
CLOSE = 0
|
||||
|
||||
class Candlestick:
|
||||
def __init__(self, ticker, interval):
|
||||
self.values = []
|
||||
self.latest = None
|
||||
self.interval = interval
|
||||
|
||||
self._ticker = ticker
|
||||
self._event = asyncio.Event()
|
||||
|
||||
asyncio.create_task(self._refresh_and_start())
|
||||
|
||||
async def _refresh_and_start(self):
|
||||
self.values = await self._fetch(datetime.datetime.now(tz=datetime.timezone.utc))
|
||||
asyncio.create_task(self._ticker_watcher())
|
||||
asyncio.create_task(self._main())
|
||||
|
||||
async def _fetch(self, data, depth = 0, rem = MAX_CANDLES):
|
||||
assert(False)
|
||||
|
||||
async def _ticker_watcher(self):
|
||||
while True:
|
||||
await self._ticker.wait()
|
||||
v = self._ticker.price
|
||||
if self.latest is None:
|
||||
self.latest = [v, -1e100, 1e100, None]
|
||||
self.latest[1] = max(self.latest[1], v)
|
||||
self.latest[2] = min(self.latest[2], v)
|
||||
self.latest[3] = v
|
||||
|
||||
async def _main(self):
|
||||
while True:
|
||||
await asyncio.sleep(self.interval)
|
||||
if self.latest is None:
|
||||
if len(self.values) == 0:
|
||||
continue
|
||||
self.latest = self.values[0]
|
||||
n = min(MAX_CANDLES-1, len(self.values))
|
||||
self.values = [self.latest, *self.values[0:n]]
|
||||
self.latest = None
|
||||
self._event.set()
|
||||
self._event.clear()
|
||||
|
||||
async def wait(self):
|
||||
await self._event.wait()
|
||||
|
||||
def SMA(self, period, offset=0, type = CLOSE):
|
||||
sum = 0
|
||||
end = min(period+offset, len(self.values))
|
||||
for i in range(offset, end):
|
||||
sum += self.values[i][type]
|
||||
return sum / (end - offset)
|
21
util/depth.py
Normal file
21
util/depth.py
Normal file
@ -0,0 +1,21 @@
|
||||
import asyncio
|
||||
|
||||
|
||||
MAX_ITEMS = 10
|
||||
|
||||
class Depth:
|
||||
def __init__(self):
|
||||
self.bids = []
|
||||
self.asks = []
|
||||
|
||||
self._event = asyncio.Event()
|
||||
|
||||
async def wait(self):
|
||||
await self._event.wait()
|
||||
|
||||
def askVolumeUntil(self, price):
|
||||
ret = 0
|
||||
for i in range(len(self.asks)):
|
||||
if self.asks[i][0] > price: break
|
||||
ret += self.asks[i][1]
|
||||
return ret
|
48
util/pair.py
Normal file
48
util/pair.py
Normal file
@ -0,0 +1,48 @@
|
||||
import asyncio
|
||||
|
||||
class Pair:
|
||||
def __init__(self, name):
|
||||
self.name = name
|
||||
self.ticker = None
|
||||
|
||||
self.candlestick_1s = None
|
||||
self.candlestick_1m = None
|
||||
self.candlestick_1h = None
|
||||
|
||||
def buy_market(amount):
|
||||
assert(False)
|
||||
|
||||
def sell_market(amount):
|
||||
assert(False)
|
||||
|
||||
def buy_limit(amount, price):
|
||||
assert(False)
|
||||
|
||||
def sell_limit(amount, price):
|
||||
assert(False)
|
||||
|
||||
def buy_stop(amount, price):
|
||||
assert(False)
|
||||
|
||||
def sell_stop(amount, price):
|
||||
assert(False)
|
||||
|
||||
def buy_stop_limit(amount, trigger, price):
|
||||
assert(False)
|
||||
|
||||
def sell_stop_limit(amount, trigger, price):
|
||||
assert(False)
|
||||
|
||||
|
||||
class Order:
|
||||
def __init__(self):
|
||||
self.price = None
|
||||
self.amount = None
|
||||
self.remain = None
|
||||
self.done = False
|
||||
|
||||
async def update(self):
|
||||
assert(False)
|
||||
|
||||
async def cancel(self):
|
||||
assert(False)
|
14
util/ticker.py
Normal file
14
util/ticker.py
Normal file
@ -0,0 +1,14 @@
|
||||
import asyncio
|
||||
|
||||
class Ticker:
|
||||
def __init__(self, pair):
|
||||
self.pair = pair
|
||||
self.price = None
|
||||
self.sell = None
|
||||
self.buy = None
|
||||
self.volume = None
|
||||
self.ts = None
|
||||
self._event = asyncio.Event()
|
||||
|
||||
async def wait(self):
|
||||
await self._event.wait()
|
Loading…
Reference in New Issue
Block a user