Compare commits

..

4 Commits

Author SHA1 Message Date
314d60792e fix an issue that the MM-algorithm dies after losscut 2023-08-03 02:52:23 +09:00
ccb8c2967c fix errors 2023-07-23 16:55:32 +09:00
9784f8627b fix an issue that start message is not shown 2023-07-23 09:04:06 +09:00
e376eea76b implement losscut in MM algorithm 2023-07-23 08:59:04 +09:00
3 changed files with 100 additions and 28 deletions

View File

@@ -7,58 +7,99 @@ class MM:
self._player = player self._player = player
self._pair = pair self._pair = pair
self._lastBuy = "" self._lastBuy = ""
self._lastSell = "" self._lastSell = ""
self._lastPrice = None
self._delta = float(config["delta"]) self._delta = float(config["delta"])
self._positiveCut = float(config["+cut"])
self._negativeCut = float(config["-cut"])
async def update(self): async def update(self):
sales = self._player.assets[self._pair.names[0]]
crncy = self._player.assets[self._pair.names[1]]
price = self._pair.ticker.price
lot = (sales.amount + crncy.amount / price) / 2
pos = sales.amount / lot - 1
# evaluate if cutting should be executed
negCut = False
posCut = False
if self._lastPrice is not None:
change = (price - self._lastPrice) / self._lastPrice
negCut = pos > 0.5 and change < -abs(self._negativeCut)
posCut = pos < -0.5 and change > abs(self._positiveCut)
cutting = negCut or posCut
# check if the past orders are active
lastBuyAgreed = (self._lastBuy is not None and lastBuyAgreed = (self._lastBuy is not None and
self._lastBuy not in self._player.orders) self._lastBuy not in self._player.orders)
lastSellAgreed = (self._lastSell is not None and lastSellAgreed = (self._lastSell is not None and
self._lastSell not in self._player.orders) self._lastSell not in self._player.orders)
if not lastBuyAgreed and not lastSellAgreed: if not lastBuyAgreed and not lastSellAgreed and not cutting:
return return
# cancel active orders
cancel_orders = [] cancel_orders = []
if not lastBuyAgreed and self._lastBuy is not None: if not lastBuyAgreed and self._lastBuy is not None:
logging.info(f"cancel buy")
cancel_orders.append(self._lastBuy) cancel_orders.append(self._lastBuy)
self._lastBuy = None elif lastBuyAgreed:
logging.info(f"agree buy")
if not lastSellAgreed and self._lastSell is not None: if not lastSellAgreed and self._lastSell is not None:
logging.info(f"cancel sell")
cancel_orders.append(self._lastSell) cancel_orders.append(self._lastSell)
self._lastSell = None elif lastSellAgreed:
logging.info(f"agree sell")
if len(cancel_orders) != 0: if len(cancel_orders) != 0:
await self._player.cancel(self._pair.names, cancel_orders) await self._player.cancel(self._pair.names, cancel_orders)
self._lastBuy = None
self._lastSell = None
sales = self._player.assets[self._pair.names[0]] # execute cutting
crncy = self._player.assets[self._pair.names[1]] if cutting:
price = self._pair.ticker.price if negCut:
logging.info(f"-cut (change: {change}, pos: {pos} -> 0)")
lot = (sales.amount + crncy.amount / price) / 4 if posCut:
pos = sales.amount / lot - 2 logging.info(f"+cut (change: {change}, pos: {pos} -> 0)")
self._lastBuy = ""
buy_amount = _quad( pos) * lot self._lastSell = ""
sell_amount = _quad(-pos) * lot sell_amount = pos * lot
if sell_amount > 0:
await self._player.orderMarketSell(self._pair.names, amount=sell_amount)
else:
await self._player.orderMarketBuy(self._pair.names, amount=-buy_amount)
return
# execute new cycle
self._lastPrice = None
buy_price = price * (1 - self._delta); buy_price = price * (1 - self._delta);
sell_price = price * (1 + self._delta); sell_price = price * (1 + self._delta);
order_unit = pow(10, -sales.precision) buy_amount = min(_quad( pos) * lot, crncy.amount / buy_price)
sell_amount = min(_quad(-pos) * lot, sales.amount)
order_unit = pow(10, -sales.precision)
logging.info(f"new cycle (pos: {pos}, price: {price}, buy: {buy_amount}, sell: {sell_amount})")
async def buy(): async def buy():
return (None if order_unit > buy_amount else self._lastBuy = (
None if order_unit > buy_amount else
await self._player.orderLimitBuy( await self._player.orderLimitBuy(
self._pair.names, amount = buy_amount, price = buy_price)) self._pair.names, amount = buy_amount, price = buy_price))
async def sell(): async def sell():
return (None if order_unit > sell_amount else self._lastSell = (
None if order_unit > sell_amount else
await self._player.orderLimitSell( await self._player.orderLimitSell(
self._pair.names, amount = sell_amount, price = sell_price)) self._pair.names, amount = sell_amount, price = sell_price))
orders = await asyncio.gather(buy(), sell()) await asyncio.gather(buy(), sell())
self._lastBuy = orders[0] self._lastPrice = price
self._lastSell = orders[1]
# https://kijitora-2018.hatenablog.com/entry/2018/12/23/102913 # https://kijitora-2018.hatenablog.com/entry/2018/12/23/102913
def _quad(x): def _quad(x):

View File

@@ -27,6 +27,7 @@ async def main():
loop.add_signal_handler(signal.SIGTERM, teardown) loop.add_signal_handler(signal.SIGTERM, teardown)
loop.add_signal_handler(signal.SIGINT, teardown) loop.add_signal_handler(signal.SIGINT, teardown)
logging.info("#### TMM ####")
async with pybotters.Client(apis={"bitbank":config["auth"]}) as pb: async with pybotters.Client(apis={"bitbank":config["auth"]}) as pb:
player = Player(pb) player = Player(pb)
pair = Pair(pb, config["pair"]) pair = Pair(pb, config["pair"])

View File

@@ -1,4 +1,5 @@
# No copyright # No copyright
import asyncio
import logging import logging
class Player: class Player:
@@ -12,7 +13,24 @@ class Player:
"pair": f"{pair[0]}_{pair[1]}", "pair": f"{pair[0]}_{pair[1]}",
"order_ids": orders "order_ids": orders
}) })
self._check(res)
async def orderMarketSell(self, pair, amount):
res = await self._post("user/spot/order", data={
"pair": f"{pair[0]}_{pair[1]}",
"amount": str(amount),
"side": "sell",
"type": "market",
})
return res["data"]["order_id"]
async def orderMarketBuy(self, pair, amount):
res = await self._post("user/spot/order", data={
"pair": f"{pair[0]}_{pair[1]}",
"amount": str(amount),
"side": "buy",
"type": "market",
})
return res["data"]["order_id"]
async def orderLimitSell(self, pair, amount, price): async def orderLimitSell(self, pair, amount, price):
res = await self._post("user/spot/order", data={ res = await self._post("user/spot/order", data={
@@ -22,7 +40,7 @@ class Player:
"side": "sell", "side": "sell",
"type": "limit", "type": "limit",
}) })
return self._check(res)["data"]["order_id"] return res["data"]["order_id"]
async def orderLimitBuy(self, pair, amount, price): async def orderLimitBuy(self, pair, amount, price):
res = await self._post("user/spot/order", data={ res = await self._post("user/spot/order", data={
@@ -32,7 +50,7 @@ class Player:
"side": "buy", "side": "buy",
"type": "limit", "type": "limit",
}) })
return self._check(res)["data"]["order_id"] return res["data"]["order_id"]
async def update(self): async def update(self):
self.assets = {} self.assets = {}
@@ -47,12 +65,24 @@ class Player:
self.orders[order["order_id"]] = Order(order) self.orders[order["order_id"]] = Order(order)
async def _post(self, suffix, data): async def _post(self, suffix, data):
res = await self._pb.post(f"https://api.bitbank.cc/v1/{suffix}", data=data) for i in range(10):
return self._check(await res.json()) try:
res = await self._pb.post(f"https://api.bitbank.cc/v1/{suffix}", data=data)
return self._check(await res.json())
except Exception as e:
err = e
await asyncio.sleep(1)
raise Exception(f"API error: {suffix} ({err})")
async def _get(self, suffix): async def _get(self, suffix):
res = await self._pb.get(f"https://api.bitbank.cc/v1/{suffix}") for i in range(10):
return self._check(await res.json()) try:
res = await self._pb.get(f"https://api.bitbank.cc/v1/{suffix}")
return self._check(await res.json())
except Exception as e:
err = e
await asyncio.sleep(1)
raise Exception(f"API error: {suffix} ({err})")
def _check(self, json): def _check(self, json):
if "success" not in json or 1 != json["success"]: if "success" not in json or 1 != json["success"]: