Merge pull request 'rust' (#10) from rust into master
Reviewed-on: https://giugl.io/gitea/peperunas/rustico/pulls/10
This commit is contained in:
commit
6960bb85a2
12
bfxbot.iml
12
bfxbot.iml
@ -1,12 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<module type="WEB_MODULE" version="4">
|
|
||||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
|
||||||
<exclude-output />
|
|
||||||
<content url="file://$MODULE_DIR$" />
|
|
||||||
<orderEntry type="inheritedJdk" />
|
|
||||||
<orderEntry type="sourceFolder" forTests="false" />
|
|
||||||
</component>
|
|
||||||
<component name="PackageRequirementsSettings">
|
|
||||||
<option name="removeUnused" value="true" />
|
|
||||||
</component>
|
|
||||||
</module>
|
|
@ -1 +0,0 @@
|
|||||||
from .bfxbot import BfxBot
|
|
151
bfxbot/bfxbot.py
151
bfxbot/bfxbot.py
@ -1,151 +0,0 @@
|
|||||||
import asyncio
|
|
||||||
import time
|
|
||||||
from typing import Dict, List, Optional, Tuple
|
|
||||||
|
|
||||||
from bfxapi import Order
|
|
||||||
|
|
||||||
from bfxbot.bfxwrapper import BfxWrapper
|
|
||||||
from bfxbot.currency import TradingPair, Symbol
|
|
||||||
from bfxbot.models import SymbolStatus, Ticker, EventHandler, Strategy, Event, EventKind, OFFER_PERC, PositionWrapper
|
|
||||||
|
|
||||||
|
|
||||||
class BfxBot:
|
|
||||||
def __init__(self, api_key: str, api_secret: str, symbols: List[TradingPair], quote: Symbol,
|
|
||||||
tick_duration: int = 1):
|
|
||||||
if api_key is None:
|
|
||||||
print("API_KEY is not set!")
|
|
||||||
raise ValueError
|
|
||||||
|
|
||||||
if api_secret is None:
|
|
||||||
print("API_SECRET is not set!")
|
|
||||||
raise ValueError
|
|
||||||
|
|
||||||
self.__bfx: BfxWrapper = BfxWrapper(api_key, api_secret)
|
|
||||||
self.__ticker: Ticker = Ticker(tick_duration)
|
|
||||||
self.__status: Dict[TradingPair, SymbolStatus] = {}
|
|
||||||
self.__quote: Symbol = quote
|
|
||||||
self.__account_info = None
|
|
||||||
self.__ledger = None
|
|
||||||
|
|
||||||
if isinstance(symbols, TradingPair):
|
|
||||||
symbols = [symbols]
|
|
||||||
|
|
||||||
self.symbols: List[TradingPair] = symbols
|
|
||||||
|
|
||||||
# init symbol statuses
|
|
||||||
for s in self.symbols:
|
|
||||||
self.__status[s] = SymbolStatus(s)
|
|
||||||
|
|
||||||
def __position_wrapper_from_id(self, position_id) -> Tuple[Optional[PositionWrapper], Optional[SymbolStatus]]:
|
|
||||||
for s in self.__status.values():
|
|
||||||
pw = s.active_position_wrapper_from_id(position_id)
|
|
||||||
|
|
||||||
if pw:
|
|
||||||
return pw, s
|
|
||||||
return None, None
|
|
||||||
|
|
||||||
async def __update_status__(self):
|
|
||||||
active_positions = await self.__bfx.get_active_position()
|
|
||||||
|
|
||||||
for symbol in self.__status:
|
|
||||||
# updating tick
|
|
||||||
self.__status[symbol].__init_tick__(self.__ticker.current_tick)
|
|
||||||
|
|
||||||
# updating last price
|
|
||||||
last_price = await self.__bfx.get_current_prices(symbol)
|
|
||||||
last_price = last_price[0]
|
|
||||||
|
|
||||||
self.__status[symbol].set_tick_price(self.__ticker.current_tick, last_price)
|
|
||||||
|
|
||||||
# updating positions
|
|
||||||
symbol_positions = [x for x in active_positions if x.symbol == str(symbol)]
|
|
||||||
for p in symbol_positions:
|
|
||||||
await self.__status[TradingPair.from_str(p.symbol)].add_position(p)
|
|
||||||
|
|
||||||
# updating orders
|
|
||||||
active_orders = await self.__bfx.get_active_orders(symbol)
|
|
||||||
|
|
||||||
for o in active_orders:
|
|
||||||
self.__status[symbol].add_order(o)
|
|
||||||
|
|
||||||
# emitting new tick event
|
|
||||||
# TODO: handle _on_new_tick() from Strategy
|
|
||||||
await self.__status[symbol].add_event(Event(EventKind.NEW_TICK, self.__ticker.current_tick))
|
|
||||||
|
|
||||||
async def best_position_closing_price(self, position_id: int) -> Optional[float]:
|
|
||||||
pw, _ = self.__position_wrapper_from_id(position_id)
|
|
||||||
|
|
||||||
if not pw:
|
|
||||||
return None
|
|
||||||
|
|
||||||
is_long_pos = pw.position.amount < 0
|
|
||||||
|
|
||||||
pub_tick = await self.__bfx.get_public_ticker(pw.position.symbol)
|
|
||||||
|
|
||||||
bid_price = pub_tick[0]
|
|
||||||
ask_price = pub_tick[2]
|
|
||||||
|
|
||||||
if is_long_pos:
|
|
||||||
closing_price = bid_price * (1 - OFFER_PERC / 100)
|
|
||||||
else:
|
|
||||||
closing_price = ask_price * (1 + OFFER_PERC / 100)
|
|
||||||
|
|
||||||
return closing_price
|
|
||||||
|
|
||||||
def close_order(self, symbol: TradingPair, order_id: int):
|
|
||||||
print(f"I would have closed order {order_id} for {symbol}")
|
|
||||||
|
|
||||||
async def close_position(self, position_id: int):
|
|
||||||
pw, ss = self.__position_wrapper_from_id(position_id)
|
|
||||||
|
|
||||||
if not pw:
|
|
||||||
print("Could not find open position!")
|
|
||||||
return
|
|
||||||
|
|
||||||
closing_price = await self.best_position_closing_price(pw.position.id)
|
|
||||||
|
|
||||||
amount = pw.position.amount * -1
|
|
||||||
|
|
||||||
open_orders = await self.__bfx.get_active_orders(pw.position.symbol)
|
|
||||||
|
|
||||||
if not open_orders:
|
|
||||||
await self.__bfx.submit_order(pw.position.symbol, closing_price, amount, Order.Type.LIMIT)
|
|
||||||
await ss.add_event(Event(EventKind.ORDER_SUBMITTED, ss.current_tick))
|
|
||||||
|
|
||||||
async def get_balances(self):
|
|
||||||
return await self.__bfx.get_current_balances(self.__quote)
|
|
||||||
|
|
||||||
async def get_profit_loss(self, start: int, end: int):
|
|
||||||
return await self.__bfx.profit_loss(start, end, self.__ledger, self.__quote)
|
|
||||||
|
|
||||||
def set_strategy(self, symbol, strategy: Strategy):
|
|
||||||
if symbol in self.__status:
|
|
||||||
self.__status[symbol].strategy = strategy
|
|
||||||
else:
|
|
||||||
self.__status[symbol] = SymbolStatus(symbol, strategy)
|
|
||||||
|
|
||||||
async def start(self):
|
|
||||||
self.__account_info = self.__bfx.get_account_information()
|
|
||||||
self.__ledger = await self.__bfx.ledger_history(0, time.time() * 1000)
|
|
||||||
|
|
||||||
await self.__update_status__()
|
|
||||||
|
|
||||||
def symbol_event_handler(self, symbol) -> Optional[EventHandler]:
|
|
||||||
if symbol not in self.__status:
|
|
||||||
return None
|
|
||||||
|
|
||||||
return self.__status[symbol].eh
|
|
||||||
|
|
||||||
def symbol_status(self, symbol: TradingPair) -> Optional[SymbolStatus]:
|
|
||||||
if symbol not in self.__status:
|
|
||||||
return None
|
|
||||||
|
|
||||||
return self.__status[symbol]
|
|
||||||
|
|
||||||
async def update(self):
|
|
||||||
await asyncio.sleep(self.__ticker.seconds)
|
|
||||||
self.__ticker.inc()
|
|
||||||
await self.__update_status__()
|
|
||||||
|
|
||||||
async def __update_ledger(self):
|
|
||||||
self.__ledger = await self.__bfx.ledger_history(0, time.time() * 1000)
|
|
@ -1,212 +0,0 @@
|
|||||||
from bfxapi.rest.bfx_rest import BfxRest
|
|
||||||
from retrying_async import retry
|
|
||||||
|
|
||||||
from bfxbot.currency import TradingPair, Balance, WalletKind, OrderType, Direction, Currency, BalanceGroup, Symbol
|
|
||||||
from bfxbot.utils import average
|
|
||||||
|
|
||||||
|
|
||||||
class BfxWrapper(BfxRest):
|
|
||||||
# default timeframe (in milliseconds) when retrieving old prices
|
|
||||||
DEFAULT_TIME_DELTA = 5 * 60 * 1000
|
|
||||||
|
|
||||||
def __init__(self, api_key: str, api_secret: str):
|
|
||||||
super().__init__(API_KEY=api_key, API_SECRET=api_secret)
|
|
||||||
|
|
||||||
#######################################
|
|
||||||
# OVERRIDDEN METHODS TO IMPLEMENT RETRY
|
|
||||||
#######################################
|
|
||||||
|
|
||||||
@retry()
|
|
||||||
async def get_public_ticker(self, symbol):
|
|
||||||
if isinstance(symbol, TradingPair):
|
|
||||||
symbol = str(symbol)
|
|
||||||
|
|
||||||
return await super().get_public_ticker(symbol)
|
|
||||||
|
|
||||||
@retry()
|
|
||||||
async def get_active_position(self):
|
|
||||||
return await super().get_active_position()
|
|
||||||
|
|
||||||
@retry()
|
|
||||||
async def get_active_orders(self, symbol):
|
|
||||||
if isinstance(symbol, TradingPair):
|
|
||||||
symbol = str(symbol)
|
|
||||||
|
|
||||||
return await super().get_active_orders(symbol)
|
|
||||||
|
|
||||||
@retry()
|
|
||||||
async def get_trades(self, symbol, start, end):
|
|
||||||
if isinstance(symbol, TradingPair):
|
|
||||||
symbol = str(symbol)
|
|
||||||
|
|
||||||
return await super().get_trades(symbol, start, end)
|
|
||||||
|
|
||||||
@retry()
|
|
||||||
async def post(self, endpoint: str, data=None, params=""):
|
|
||||||
if data is None:
|
|
||||||
data = {}
|
|
||||||
return await super().post(endpoint, data, params)
|
|
||||||
|
|
||||||
################################
|
|
||||||
# NEW METHODS
|
|
||||||
################################
|
|
||||||
|
|
||||||
async def account_movements_between(self, start: int, end: int, ledger, quote: Symbol) -> BalanceGroup:
|
|
||||||
movements = BalanceGroup(quote)
|
|
||||||
|
|
||||||
# TODO: Parallelize this
|
|
||||||
for entry in filter(lambda x: start <= x[3] <= end, ledger):
|
|
||||||
description: str = entry[8]
|
|
||||||
currency = entry[1]
|
|
||||||
amount = entry[5]
|
|
||||||
time = entry[3]
|
|
||||||
|
|
||||||
if not description.lower().startswith("deposit"):
|
|
||||||
continue
|
|
||||||
|
|
||||||
trading_pair = f"t{currency}{quote}"
|
|
||||||
start_time = time - self.DEFAULT_TIME_DELTA
|
|
||||||
end_time = time + self.DEFAULT_TIME_DELTA
|
|
||||||
|
|
||||||
if currency != str(quote):
|
|
||||||
trades = await self.get_public_trades(symbol=trading_pair, start=start_time, end=end_time)
|
|
||||||
currency_price = average(list(map(lambda x: x[3], trades)))
|
|
||||||
|
|
||||||
c = Currency(currency, amount, currency_price)
|
|
||||||
else:
|
|
||||||
c = Currency(currency, amount)
|
|
||||||
|
|
||||||
b = Balance(c, quote)
|
|
||||||
|
|
||||||
movements.add_balance(b)
|
|
||||||
|
|
||||||
return movements
|
|
||||||
|
|
||||||
async def balance_at(self, time: int, ledger, quote: Symbol):
|
|
||||||
bg = BalanceGroup(quote)
|
|
||||||
|
|
||||||
# TODO: Parallelize this
|
|
||||||
for entry in filter(lambda x: x[3] <= time, ledger):
|
|
||||||
currency = entry[1]
|
|
||||||
amount = entry[6]
|
|
||||||
|
|
||||||
if currency in bg.currency_names():
|
|
||||||
continue
|
|
||||||
|
|
||||||
trading_pair = f"t{currency}{quote}"
|
|
||||||
start_time = time - self.DEFAULT_TIME_DELTA
|
|
||||||
end_time = time + self.DEFAULT_TIME_DELTA
|
|
||||||
|
|
||||||
|
|
||||||
if currency != str(quote):
|
|
||||||
trades = await self.get_public_trades(symbol=trading_pair, start=start_time, end=end_time)
|
|
||||||
currency_price = average(list(map(lambda x: x[3], trades)))
|
|
||||||
|
|
||||||
c = Currency(currency, amount, currency_price)
|
|
||||||
else:
|
|
||||||
c = Currency(currency, amount)
|
|
||||||
|
|
||||||
b = Balance(c, quote)
|
|
||||||
|
|
||||||
bg.add_balance(b)
|
|
||||||
|
|
||||||
return bg
|
|
||||||
|
|
||||||
# Calculate the average execution price for Trading or rate for Margin funding.
|
|
||||||
async def calculate_execution_price(self, pair: str, amount: float):
|
|
||||||
api_path = "/calc/trade/avg"
|
|
||||||
|
|
||||||
res = await self.post(api_path, {
|
|
||||||
'symbol': pair,
|
|
||||||
'amount': amount
|
|
||||||
})
|
|
||||||
|
|
||||||
return res[0]
|
|
||||||
|
|
||||||
async def get_account_information(self):
|
|
||||||
api_path = "auth/r/info/user"
|
|
||||||
|
|
||||||
return await self.post(api_path)
|
|
||||||
|
|
||||||
async def get_current_balances(self, quote: Symbol) -> BalanceGroup:
|
|
||||||
bg: BalanceGroup = BalanceGroup(quote)
|
|
||||||
|
|
||||||
wallets = await self.get_wallets()
|
|
||||||
|
|
||||||
for w in wallets:
|
|
||||||
kind = WalletKind.from_str(w.type)
|
|
||||||
|
|
||||||
if not kind:
|
|
||||||
continue
|
|
||||||
|
|
||||||
execution_price = await self.calculate_execution_price(f"t{w.currency}{quote}", w.balance)
|
|
||||||
c = Currency(w.currency, w.balance, execution_price)
|
|
||||||
b = Balance(c, quote, kind)
|
|
||||||
|
|
||||||
bg.add_balance(b)
|
|
||||||
|
|
||||||
return bg
|
|
||||||
|
|
||||||
async def get_current_prices(self, symbol: TradingPair) -> (float, float, float):
|
|
||||||
if isinstance(symbol, TradingPair):
|
|
||||||
symbol = str(symbol)
|
|
||||||
|
|
||||||
tickers = await self.get_public_ticker(symbol)
|
|
||||||
|
|
||||||
bid_price = tickers[0]
|
|
||||||
ask_price = tickers[2]
|
|
||||||
ticker_price = tickers[6]
|
|
||||||
|
|
||||||
return bid_price, ask_price, ticker_price
|
|
||||||
|
|
||||||
async def ledger_history(self, start, end):
|
|
||||||
def chunks(lst):
|
|
||||||
for i in range(len(lst) - 1):
|
|
||||||
yield lst[i:i + 2]
|
|
||||||
|
|
||||||
def get_timeframes(start, end, increments=10):
|
|
||||||
start = int(start)
|
|
||||||
end = int(end)
|
|
||||||
|
|
||||||
delta = int((end - start) / increments)
|
|
||||||
|
|
||||||
return [x for x in range(start, end, delta)]
|
|
||||||
|
|
||||||
api_path = "auth/r/ledgers/hist"
|
|
||||||
|
|
||||||
history = []
|
|
||||||
|
|
||||||
# TODO: Parallelize this
|
|
||||||
for c in chunks(get_timeframes(start, end)):
|
|
||||||
history.extend(await self.post(api_path, {'start': c[0], 'end': c[1], 'limit': 2500}))
|
|
||||||
|
|
||||||
history.sort(key=lambda ledger_entry: ledger_entry[3], reverse=True)
|
|
||||||
|
|
||||||
return history
|
|
||||||
|
|
||||||
async def maximum_order_amount(self, symbol: TradingPair, direction: Direction,
|
|
||||||
order_type: OrderType = OrderType.EXCHANGE,
|
|
||||||
rate: int = 1):
|
|
||||||
api_path = "auth/calc/order/avail"
|
|
||||||
|
|
||||||
return await self.post(api_path,
|
|
||||||
{'symbol': str(symbol), 'type': order_type.value, "dir": direction.value, "rate": rate})
|
|
||||||
|
|
||||||
async def profit_loss(self, start: int, end: int, ledger, quote: Symbol):
|
|
||||||
if start > end:
|
|
||||||
raise ValueError
|
|
||||||
|
|
||||||
start_bg = await self.balance_at(start, ledger, quote)
|
|
||||||
end_bg = await self.balance_at(end, ledger, quote)
|
|
||||||
movements_bg = await self.account_movements_between(start, end, ledger, quote)
|
|
||||||
|
|
||||||
start_quote = start_bg.quote_equivalent()
|
|
||||||
end_quote = end_bg.quote_equivalent()
|
|
||||||
movements_quote = movements_bg.quote_equivalent()
|
|
||||||
|
|
||||||
profit_loss = end_quote - (start_quote + movements_quote)
|
|
||||||
|
|
||||||
profit_loss_percentage = profit_loss / (start_quote + movements_quote) * 100
|
|
||||||
|
|
||||||
|
|
||||||
return profit_loss, profit_loss_percentage
|
|
@ -1,161 +0,0 @@
|
|||||||
import re
|
|
||||||
from enum import Enum
|
|
||||||
from typing import Optional, List
|
|
||||||
|
|
||||||
|
|
||||||
class Symbol(Enum):
|
|
||||||
XMR = "XMR"
|
|
||||||
BTC = "BTC"
|
|
||||||
ETH = "ETH"
|
|
||||||
USD = "USD"
|
|
||||||
|
|
||||||
def __repr__(self):
|
|
||||||
return self.__str__()
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return self.value
|
|
||||||
|
|
||||||
def __eq__(self, other):
|
|
||||||
return self.value == other.value
|
|
||||||
|
|
||||||
|
|
||||||
class TradingPair(Enum):
|
|
||||||
XMR = "XMR"
|
|
||||||
BTC = "BTC"
|
|
||||||
ETH = "ETH"
|
|
||||||
|
|
||||||
def __repr__(self):
|
|
||||||
return f"t{self.value}USD"
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return self.__repr__()
|
|
||||||
|
|
||||||
def __eq__(self, other):
|
|
||||||
return self.value == other.value
|
|
||||||
|
|
||||||
def __hash__(self):
|
|
||||||
return hash(self.__repr__())
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def from_str(string: str):
|
|
||||||
match = re.compile("t([a-zA-Z]+)USD").match(string)
|
|
||||||
|
|
||||||
if not match:
|
|
||||||
raise ValueError
|
|
||||||
|
|
||||||
currency = match.group(1).lower()
|
|
||||||
|
|
||||||
if currency in ("xmr"):
|
|
||||||
return TradingPair.XMR
|
|
||||||
elif currency in ("btc"):
|
|
||||||
return TradingPair.BTC
|
|
||||||
elif currency in ("eth"):
|
|
||||||
return TradingPair.ETH
|
|
||||||
else:
|
|
||||||
return NotImplementedError
|
|
||||||
|
|
||||||
|
|
||||||
class Currency:
|
|
||||||
def __init__(self, name: str, amount: float, price: float = None):
|
|
||||||
self.__name: str = name
|
|
||||||
self.__amount: float = amount
|
|
||||||
self.__price: Optional[float] = price
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
if self.__price:
|
|
||||||
return f"{self.__name} {self.__amount} @ {self.__price}"
|
|
||||||
else:
|
|
||||||
return f"{self.__name} {self.__amount}"
|
|
||||||
|
|
||||||
def __repr__(self):
|
|
||||||
return self.__str__()
|
|
||||||
|
|
||||||
def amount(self) -> float:
|
|
||||||
return self.__amount
|
|
||||||
|
|
||||||
def name(self) -> str:
|
|
||||||
return self.__name
|
|
||||||
|
|
||||||
def price(self) -> Optional[float]:
|
|
||||||
return self.__price
|
|
||||||
|
|
||||||
|
|
||||||
class WalletKind(Enum):
|
|
||||||
EXCHANGE = "exchange",
|
|
||||||
MARGIN = "margin"
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def from_str(string: str):
|
|
||||||
string = string.lower()
|
|
||||||
|
|
||||||
if "margin" in string:
|
|
||||||
return WalletKind.MARGIN
|
|
||||||
if "exchange" in string:
|
|
||||||
return WalletKind.EXCHANGE
|
|
||||||
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
class Balance:
|
|
||||||
def __init__(self, currency: Currency, quote: Symbol, wallet: Optional[WalletKind] = None):
|
|
||||||
self.__currency: Currency = currency
|
|
||||||
self.__quote: Symbol = quote
|
|
||||||
self.__quote_equivalent: float = 0.0
|
|
||||||
self.__wallet: Optional[WalletKind] = wallet
|
|
||||||
|
|
||||||
if currency.name() == str(quote):
|
|
||||||
self.__quote_equivalent = currency.amount()
|
|
||||||
else:
|
|
||||||
self.__quote_equivalent = currency.amount() * currency.price()
|
|
||||||
|
|
||||||
def currency(self) -> Currency:
|
|
||||||
return self.__currency
|
|
||||||
|
|
||||||
def quote(self) -> Symbol:
|
|
||||||
return self.__quote
|
|
||||||
|
|
||||||
def quote_equivalent(self) -> float:
|
|
||||||
return self.__quote_equivalent
|
|
||||||
|
|
||||||
def wallet(self) -> Optional[WalletKind]:
|
|
||||||
return self.__wallet
|
|
||||||
|
|
||||||
|
|
||||||
class BalanceGroup:
|
|
||||||
def __init__(self, quote: Symbol, balances: Optional[List[Balance]] = None):
|
|
||||||
if balances is None:
|
|
||||||
balances = []
|
|
||||||
|
|
||||||
self.__quote: Symbol = quote
|
|
||||||
self.__balances: Optional[List[Balance]] = balances
|
|
||||||
self.__quote_equivalent: float = 0.0
|
|
||||||
|
|
||||||
def __iter__(self):
|
|
||||||
return self.__balances.__iter__()
|
|
||||||
|
|
||||||
def add_balance(self, balance: Balance):
|
|
||||||
self.__balances.append(balance)
|
|
||||||
|
|
||||||
self.__quote_equivalent += balance.quote_equivalent()
|
|
||||||
|
|
||||||
def balances(self) -> Optional[List[Balance]]:
|
|
||||||
return self.__balances
|
|
||||||
|
|
||||||
def currency_names(self) -> List[str]:
|
|
||||||
return list(map(lambda x: x.currency().name(), self.balances()))
|
|
||||||
|
|
||||||
def quote(self) -> Symbol:
|
|
||||||
return self.__quote
|
|
||||||
|
|
||||||
def quote_equivalent(self) -> float:
|
|
||||||
return self.__quote_equivalent
|
|
||||||
|
|
||||||
|
|
||||||
class Direction(Enum):
|
|
||||||
UP = 1,
|
|
||||||
DOWN = -1
|
|
||||||
|
|
||||||
|
|
||||||
class OrderType(Enum):
|
|
||||||
EXCHANGE = "EXCHANGE",
|
|
||||||
MARGIN = "MARGIN"
|
|
295
bfxbot/models.py
295
bfxbot/models.py
@ -1,295 +0,0 @@
|
|||||||
import inspect
|
|
||||||
import time
|
|
||||||
from enum import Enum
|
|
||||||
from typing import List, Dict, Tuple, Optional
|
|
||||||
|
|
||||||
from bfxapi import Order, Position
|
|
||||||
|
|
||||||
from bfxbot.currency import TradingPair
|
|
||||||
|
|
||||||
OFFER_PERC = 0.008
|
|
||||||
TAKER_FEE = 0.2
|
|
||||||
MAKER_FEE = 0.1
|
|
||||||
|
|
||||||
|
|
||||||
def __add_to_dict_list__(dictionary: Dict[int, List], k, v) -> Dict[int, List]:
|
|
||||||
if k not in dictionary:
|
|
||||||
dictionary[k] = [v]
|
|
||||||
else:
|
|
||||||
dictionary[k].append(v)
|
|
||||||
|
|
||||||
return dictionary
|
|
||||||
|
|
||||||
|
|
||||||
class EventKind(Enum):
|
|
||||||
NEW_MINIMUM = 1,
|
|
||||||
NEW_MAXIMUM = 2,
|
|
||||||
REACHED_LOSS = 3,
|
|
||||||
REACHED_BREAK_EVEN = 4,
|
|
||||||
REACHED_MIN_PROFIT = 5,
|
|
||||||
REACHED_GOOD_PROFIT = 6,
|
|
||||||
REACHED_MAX_LOSS = 7,
|
|
||||||
CLOSE_POSITION = 8,
|
|
||||||
TRAILING_STOP_SET = 9,
|
|
||||||
TRAILING_STOP_MOVED = 10,
|
|
||||||
ORDER_SUBMITTED = 11,
|
|
||||||
NEW_TICK = 12
|
|
||||||
|
|
||||||
|
|
||||||
class EventMetadata:
|
|
||||||
def __init__(self, position_id: int = None, order_id: int = None):
|
|
||||||
self.position_id: int = position_id
|
|
||||||
self.order_id: int = order_id
|
|
||||||
|
|
||||||
|
|
||||||
class PositionState(Enum):
|
|
||||||
CRITICAL = -1,
|
|
||||||
LOSS = 0,
|
|
||||||
BREAK_EVEN = 1,
|
|
||||||
MINIMUM_PROFIT = 2,
|
|
||||||
PROFIT = 3,
|
|
||||||
UNDEFINED = 4
|
|
||||||
|
|
||||||
def color(self) -> str:
|
|
||||||
if self == self.LOSS or self == self.CRITICAL:
|
|
||||||
return "red"
|
|
||||||
elif self == self.BREAK_EVEN:
|
|
||||||
return "yellow"
|
|
||||||
else:
|
|
||||||
return "green"
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return f"{self.name}"
|
|
||||||
|
|
||||||
def __repr__(self):
|
|
||||||
return self.__str__()
|
|
||||||
|
|
||||||
|
|
||||||
class Ticker:
|
|
||||||
def __init__(self, sec) -> None:
|
|
||||||
self.seconds: int = sec
|
|
||||||
self.start_time = time.time()
|
|
||||||
self.current_tick: int = 1
|
|
||||||
|
|
||||||
def inc(self):
|
|
||||||
self.current_tick += 1
|
|
||||||
|
|
||||||
|
|
||||||
class Event:
|
|
||||||
def __init__(self, kind: EventKind, tick: int, metadata: EventMetadata = None) -> None:
|
|
||||||
self.kind: EventKind = kind
|
|
||||||
self.tick: int = tick
|
|
||||||
self.metadata: EventMetadata = metadata
|
|
||||||
|
|
||||||
def __repr__(self) -> str:
|
|
||||||
return f"{self.kind.name} @ Tick {self.tick}"
|
|
||||||
|
|
||||||
def has_metadata(self) -> bool:
|
|
||||||
return self.metadata is not None
|
|
||||||
|
|
||||||
|
|
||||||
class PositionWrapper:
|
|
||||||
def __init__(self, position: Position, state: PositionState = PositionState.UNDEFINED,
|
|
||||||
net_profit_loss: float = None,
|
|
||||||
net_profit_loss_percentage: float = None):
|
|
||||||
self.position: Position = position
|
|
||||||
self.__net_profit_loss: float = net_profit_loss
|
|
||||||
self.__net_profit_loss_percentage: float = net_profit_loss_percentage
|
|
||||||
self.__state: PositionState = state
|
|
||||||
|
|
||||||
def net_profit_loss(self) -> float:
|
|
||||||
return self.__net_profit_loss
|
|
||||||
|
|
||||||
def net_profit_loss_percentage(self) -> float:
|
|
||||||
return self.__net_profit_loss_percentage
|
|
||||||
|
|
||||||
def set_state(self, state: PositionState):
|
|
||||||
self.__state = state
|
|
||||||
|
|
||||||
def state(self) -> PositionState:
|
|
||||||
return self.__state
|
|
||||||
|
|
||||||
|
|
||||||
class SymbolStatus:
|
|
||||||
def __init__(self, symbol: TradingPair, strategy=None):
|
|
||||||
self.symbol = symbol
|
|
||||||
self.eh = EventHandler()
|
|
||||||
self.prices: Dict[int, float] = {}
|
|
||||||
self.events: List[Event] = []
|
|
||||||
self.orders: Dict[int, List[Order]] = {}
|
|
||||||
self.positions: Dict[int, List[PositionWrapper]] = {}
|
|
||||||
self.current_tick: int = 1
|
|
||||||
self.strategy: Strategy = strategy
|
|
||||||
|
|
||||||
def __init_tick__(self, tick: int):
|
|
||||||
self.current_tick = tick
|
|
||||||
self.prices[self.current_tick] = None
|
|
||||||
self.orders[self.current_tick] = []
|
|
||||||
self.positions[self.current_tick] = []
|
|
||||||
|
|
||||||
async def add_event(self, event: Event):
|
|
||||||
self.events.append(event)
|
|
||||||
await self.eh.call_event(self, event)
|
|
||||||
|
|
||||||
def add_order(self, order: Order):
|
|
||||||
if self.strategy:
|
|
||||||
self.strategy.order_on_new_tick(order, self)
|
|
||||||
self.orders = __add_to_dict_list__(self.orders, self.current_tick, order)
|
|
||||||
|
|
||||||
# Applies strategy and adds position to list
|
|
||||||
async def add_position(self, position: Position):
|
|
||||||
events = []
|
|
||||||
|
|
||||||
# if a strategy is defined then the strategy takes care of creating a PW for us
|
|
||||||
if not self.strategy:
|
|
||||||
pw = PositionWrapper(position)
|
|
||||||
else:
|
|
||||||
pw, events = await self.__apply_strategy_to_position__(position)
|
|
||||||
self.positions = __add_to_dict_list__(self.positions, self.current_tick, pw)
|
|
||||||
|
|
||||||
# triggering state callbacks
|
|
||||||
await self.__trigger_position_state_callbacks__(pw)
|
|
||||||
|
|
||||||
# triggering events callbacks
|
|
||||||
for e in events:
|
|
||||||
if not isinstance(e, Event):
|
|
||||||
raise ValueError
|
|
||||||
await self.add_event(e)
|
|
||||||
|
|
||||||
def all_prices(self) -> List[float]:
|
|
||||||
return list(map(lambda x: self.prices[x], range(1, self.current_tick + 1)))
|
|
||||||
|
|
||||||
def all_ticks(self) -> List[int]:
|
|
||||||
return [x for x in range(1, self.current_tick + 1)]
|
|
||||||
|
|
||||||
def current_positions(self) -> List[PositionWrapper]:
|
|
||||||
return self.positions[self.current_tick]
|
|
||||||
|
|
||||||
def current_price(self):
|
|
||||||
return self.prices[self.current_tick]
|
|
||||||
|
|
||||||
def previous_pw(self, pid: int) -> Optional[PositionWrapper]:
|
|
||||||
if self.current_tick == 1:
|
|
||||||
return None
|
|
||||||
|
|
||||||
if not self.positions[self.current_tick - 1]:
|
|
||||||
return None
|
|
||||||
|
|
||||||
return next(filter(lambda x: x.position.id == pid, self.positions[self.current_tick - 1]))
|
|
||||||
|
|
||||||
def active_position_wrapper_from_id(self, position_id: int) -> Optional[PositionWrapper]:
|
|
||||||
if self.current_tick in self.positions:
|
|
||||||
for pw in self.positions[self.current_tick]:
|
|
||||||
if pw.position.id == position_id:
|
|
||||||
return pw
|
|
||||||
return None
|
|
||||||
|
|
||||||
def set_tick_price(self, tick, price):
|
|
||||||
self.prices[tick] = price
|
|
||||||
|
|
||||||
async def __apply_strategy_to_position__(self, position: Position) -> Tuple[PositionWrapper, List[Event]]:
|
|
||||||
pw, events = self.strategy.position_on_new_tick(position, self)
|
|
||||||
|
|
||||||
if not isinstance(pw, PositionWrapper):
|
|
||||||
raise ValueError
|
|
||||||
|
|
||||||
if not isinstance(events, list):
|
|
||||||
raise ValueError
|
|
||||||
|
|
||||||
return pw, events
|
|
||||||
|
|
||||||
async def __trigger_position_state_callbacks__(self, pw: PositionWrapper):
|
|
||||||
await self.eh.call_position_state(self, pw)
|
|
||||||
|
|
||||||
|
|
||||||
class Strategy:
|
|
||||||
"""
|
|
||||||
Defines new position state and events after tick.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def position_on_new_tick(self, position: Position, ss: SymbolStatus) -> Tuple[PositionWrapper, List[Event]]:
|
|
||||||
pass
|
|
||||||
|
|
||||||
"""
|
|
||||||
Defines new order state and events after tick.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def order_on_new_tick(self, order: Order, ss: SymbolStatus):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class EventHandler:
|
|
||||||
def __init__(self):
|
|
||||||
self.event_handlers = {}
|
|
||||||
self.state_handlers = {}
|
|
||||||
self.any_events = []
|
|
||||||
self.any_state = []
|
|
||||||
|
|
||||||
async def call_event(self, status: SymbolStatus, event: Event):
|
|
||||||
value = event.kind.value
|
|
||||||
|
|
||||||
# print("CALLING EVENT: {}".format(event))
|
|
||||||
if value in self.event_handlers:
|
|
||||||
for h in self.event_handlers[value]:
|
|
||||||
if inspect.iscoroutinefunction(h):
|
|
||||||
await h(event, status)
|
|
||||||
else:
|
|
||||||
h(event, status)
|
|
||||||
|
|
||||||
for h in self.any_events:
|
|
||||||
if inspect.iscoroutinefunction(h):
|
|
||||||
await h(event, status)
|
|
||||||
else:
|
|
||||||
h(event, status)
|
|
||||||
|
|
||||||
async def call_position_state(self, status: SymbolStatus, pw: PositionWrapper):
|
|
||||||
state = pw.state()
|
|
||||||
|
|
||||||
if state in self.state_handlers:
|
|
||||||
for h in self.state_handlers[state]:
|
|
||||||
if inspect.iscoroutinefunction(h):
|
|
||||||
await h(pw, status)
|
|
||||||
else:
|
|
||||||
h(pw, status)
|
|
||||||
|
|
||||||
for h in self.any_state:
|
|
||||||
if inspect.iscoroutinefunction(h):
|
|
||||||
await h(pw, status)
|
|
||||||
else:
|
|
||||||
h(pw, status)
|
|
||||||
|
|
||||||
def on_event(self, kind: EventKind):
|
|
||||||
value = kind.value
|
|
||||||
|
|
||||||
def registerhandler(handler):
|
|
||||||
if value in self.event_handlers:
|
|
||||||
self.event_handlers[value].append(handler)
|
|
||||||
else:
|
|
||||||
self.event_handlers[value] = [handler]
|
|
||||||
return handler
|
|
||||||
|
|
||||||
return registerhandler
|
|
||||||
|
|
||||||
def on_position_state(self, state: PositionState):
|
|
||||||
def registerhandler(handler):
|
|
||||||
if state in self.state_handlers:
|
|
||||||
self.state_handlers[state].append(handler)
|
|
||||||
else:
|
|
||||||
self.state_handlers[state] = [handler]
|
|
||||||
return handler
|
|
||||||
|
|
||||||
return registerhandler
|
|
||||||
|
|
||||||
def on_any_event(self):
|
|
||||||
def registerhandle(handler):
|
|
||||||
self.any_events.append(handler)
|
|
||||||
return handler
|
|
||||||
|
|
||||||
return registerhandle
|
|
||||||
|
|
||||||
def on_any_position_state(self):
|
|
||||||
def registerhandle(handler):
|
|
||||||
self.any_state.append(handler)
|
|
||||||
return handler
|
|
||||||
|
|
||||||
return registerhandle
|
|
@ -1,59 +0,0 @@
|
|||||||
import re
|
|
||||||
|
|
||||||
from bfxbot.bfxwrapper import Balance
|
|
||||||
from bfxbot.models import PositionWrapper
|
|
||||||
|
|
||||||
|
|
||||||
class CurrencyPair:
|
|
||||||
def __init__(self, base: str, quote: str):
|
|
||||||
self.base: str = base
|
|
||||||
self.quote: str = quote
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def from_str(string: str):
|
|
||||||
symbol_regex = re.compile("t(?P<base>[a-zA-Z]{3})(?P<quote>[a-zA-Z]{3})")
|
|
||||||
|
|
||||||
match = symbol_regex.match(string)
|
|
||||||
|
|
||||||
if not match:
|
|
||||||
return None
|
|
||||||
|
|
||||||
return CurrencyPair(match.group("base"), match.group("quote"))
|
|
||||||
|
|
||||||
|
|
||||||
def average(a):
|
|
||||||
return sum(a) / len(a)
|
|
||||||
|
|
||||||
|
|
||||||
def balance_to_json(balance: Balance):
|
|
||||||
return {
|
|
||||||
'currency': balance.currency().name(),
|
|
||||||
'amount': balance.currency().amount(),
|
|
||||||
'kind': balance.wallet().value,
|
|
||||||
'quote': balance.quote().value,
|
|
||||||
'quote_equivalent': balance.quote_equivalent()
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def net_pl_percentage(perc: float, reference_fee_perc: float):
|
|
||||||
return perc - reference_fee_perc
|
|
||||||
|
|
||||||
|
|
||||||
def pw_to_posprop(pw: PositionWrapper):
|
|
||||||
pair = CurrencyPair.from_str(pw.position.symbol)
|
|
||||||
|
|
||||||
if not pair:
|
|
||||||
raise ValueError
|
|
||||||
|
|
||||||
return {
|
|
||||||
"id": pw.position.id,
|
|
||||||
"amount": pw.position.amount,
|
|
||||||
"base_price": pw.position.base_price,
|
|
||||||
"state": str(pw.state()),
|
|
||||||
"pair": {
|
|
||||||
"base": pair.base,
|
|
||||||
"quote": pair.quote
|
|
||||||
},
|
|
||||||
"profit_loss": pw.net_profit_loss(),
|
|
||||||
"profit_loss_percentage": pw.net_profit_loss_percentage()
|
|
||||||
}
|
|
140
main.py
140
main.py
@ -1,140 +0,0 @@
|
|||||||
# #!/usr/bin/env python
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
import os
|
|
||||||
import threading
|
|
||||||
from time import sleep
|
|
||||||
from typing import List
|
|
||||||
|
|
||||||
import dotenv
|
|
||||||
from flask import Flask, render_template
|
|
||||||
from flask_socketio import SocketIO
|
|
||||||
|
|
||||||
from bfxbot import BfxBot
|
|
||||||
from bfxbot.bfxwrapper import Balance
|
|
||||||
from bfxbot.currency import TradingPair, Symbol
|
|
||||||
from bfxbot.models import PositionWrapper, SymbolStatus, Event, EventKind
|
|
||||||
from bfxbot.utils import pw_to_posprop, balance_to_json
|
|
||||||
from strategy import TrailingStopStrategy
|
|
||||||
|
|
||||||
|
|
||||||
async def bot_loop():
|
|
||||||
await bot.start()
|
|
||||||
|
|
||||||
while True:
|
|
||||||
await bot.update()
|
|
||||||
|
|
||||||
|
|
||||||
loop = asyncio.new_event_loop()
|
|
||||||
|
|
||||||
dotenv.load_dotenv()
|
|
||||||
|
|
||||||
API_KEY = os.getenv("API_KEY")
|
|
||||||
API_SECRET = os.getenv("API_SECRET")
|
|
||||||
|
|
||||||
app = Flask(__name__)
|
|
||||||
socketio = SocketIO(app, async_mode="threading")
|
|
||||||
bot = BfxBot(api_key=API_KEY, api_secret=API_SECRET,
|
|
||||||
symbols=[TradingPair.BTC], quote=Symbol.USD, tick_duration=20)
|
|
||||||
strategy = TrailingStopStrategy()
|
|
||||||
bot.set_strategy(TradingPair.BTC, strategy)
|
|
||||||
btc_eh = bot.symbol_event_handler(TradingPair.BTC)
|
|
||||||
|
|
||||||
# initializing and starting bot on other thread
|
|
||||||
threading.Thread(target=lambda: asyncio.run(bot_loop())).start()
|
|
||||||
|
|
||||||
|
|
||||||
###################################
|
|
||||||
# Flask callbacks
|
|
||||||
###################################
|
|
||||||
|
|
||||||
@app.route('/')
|
|
||||||
def entry():
|
|
||||||
return render_template('index.html')
|
|
||||||
|
|
||||||
|
|
||||||
###################################
|
|
||||||
# Socker.IO callbacks
|
|
||||||
###################################
|
|
||||||
|
|
||||||
@socketio.on("close_position")
|
|
||||||
def on_close_position(message: dict):
|
|
||||||
position_id = message['position_id']
|
|
||||||
|
|
||||||
loop.run_until_complete(bot.close_position(position_id))
|
|
||||||
|
|
||||||
|
|
||||||
@socketio.on('connect')
|
|
||||||
def on_connect():
|
|
||||||
# sleeping on exception to avoid race condition
|
|
||||||
ticks, prices, positions, balances = [], [], [], []
|
|
||||||
|
|
||||||
while not ticks or not prices:
|
|
||||||
try:
|
|
||||||
ticks = bot.symbol_status(TradingPair.BTC).all_ticks()
|
|
||||||
prices = bot.symbol_status(TradingPair.BTC).all_prices()
|
|
||||||
positions = bot.symbol_status(TradingPair.BTC).current_positions()
|
|
||||||
balances = loop.run_until_complete(bot.get_balances())
|
|
||||||
except KeyError:
|
|
||||||
sleep(1)
|
|
||||||
|
|
||||||
socketio.emit("first_connect",
|
|
||||||
{
|
|
||||||
"ticks": ticks,
|
|
||||||
"prices": prices,
|
|
||||||
"positions": list(map(pw_to_posprop, positions)),
|
|
||||||
"balances": list(map(balance_to_json, balances))
|
|
||||||
})
|
|
||||||
|
|
||||||
|
|
||||||
@socketio.on('get_profit_loss')
|
|
||||||
def on_get_profit_loss(message):
|
|
||||||
start = message['start']
|
|
||||||
end = message['end']
|
|
||||||
|
|
||||||
profit_loss = loop.run_until_complete(bot.get_profit_loss(start, end))
|
|
||||||
|
|
||||||
socketio.emit("put_profit_loss", {
|
|
||||||
"pl": profit_loss[0],
|
|
||||||
"pl_perc": profit_loss[1]
|
|
||||||
})
|
|
||||||
|
|
||||||
###################################
|
|
||||||
# Bot callbacks
|
|
||||||
###################################
|
|
||||||
|
|
||||||
@btc_eh.on_event(EventKind.CLOSE_POSITION)
|
|
||||||
async def on_close_position(event: Event, _):
|
|
||||||
print("CLOSING!")
|
|
||||||
await bot.close_position(event.metadata.position_id)
|
|
||||||
|
|
||||||
|
|
||||||
@btc_eh.on_any_position_state()
|
|
||||||
async def on_any_state(pw: PositionWrapper, ss: SymbolStatus):
|
|
||||||
await strategy.update_stop_percentage(pw, ss)
|
|
||||||
|
|
||||||
|
|
||||||
@btc_eh.on_event(EventKind.NEW_TICK)
|
|
||||||
async def on_new_tick(event: Event, status: SymbolStatus):
|
|
||||||
tick = event.tick
|
|
||||||
price = status.prices[event.tick]
|
|
||||||
|
|
||||||
balances: List[Balance] = await bot.get_balances()
|
|
||||||
positions: List[PositionWrapper] = status.positions[event.tick] if event.tick in status.positions else []
|
|
||||||
|
|
||||||
socketio.emit("new_tick", {"tick": tick,
|
|
||||||
"price": price,
|
|
||||||
"positions": list(map(pw_to_posprop, positions)),
|
|
||||||
"balances": list(map(balance_to_json, balances))})
|
|
||||||
|
|
||||||
|
|
||||||
@btc_eh.on_any_event()
|
|
||||||
def on_any_event(event: Event, _):
|
|
||||||
socketio.emit("new_event", {
|
|
||||||
"tick": event.tick,
|
|
||||||
"kind": event.kind.name
|
|
||||||
})
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
socketio.run(app)
|
|
@ -1,36 +0,0 @@
|
|||||||
aiohttp==3.7.3
|
|
||||||
astroid==2.4.2
|
|
||||||
async-timeout==3.0.1
|
|
||||||
asyncio==3.4.3
|
|
||||||
attrs==20.3.0
|
|
||||||
bidict==0.21.2
|
|
||||||
bitfinex-api-py==1.1.8
|
|
||||||
chardet==3.0.4
|
|
||||||
click==7.1.2
|
|
||||||
eventemitter==0.2.0
|
|
||||||
Flask==1.1.2
|
|
||||||
Flask-SocketIO==5.0.1
|
|
||||||
idna==2.10
|
|
||||||
isort==5.6.4
|
|
||||||
itsdangerous==1.1.0
|
|
||||||
Jinja2==2.11.2
|
|
||||||
lazy-object-proxy==1.4.3
|
|
||||||
MarkupSafe==1.1.1
|
|
||||||
mccabe==0.6.1
|
|
||||||
mpmath==1.1.0
|
|
||||||
multidict==5.1.0
|
|
||||||
pyee==8.1.0
|
|
||||||
pylint==2.6.0
|
|
||||||
python-dotenv==0.15.0
|
|
||||||
python-engineio==4.0.0
|
|
||||||
python-socketio==5.0.3
|
|
||||||
retrying-async==1.2.0
|
|
||||||
six==1.15.0
|
|
||||||
sympy==1.7.1
|
|
||||||
toml==0.10.2
|
|
||||||
typing-extensions==3.7.4.3
|
|
||||||
websockets==8.1
|
|
||||||
Werkzeug==1.0.1
|
|
||||||
wrapt==1.12.1
|
|
||||||
yarl==1.6.3
|
|
||||||
|
|
1717
rustybot/Cargo.lock
generated
Normal file
1717
rustybot/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
25
rustybot/Cargo.toml
Normal file
25
rustybot/Cargo.toml
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
[package]
|
||||||
|
name = "rustybot"
|
||||||
|
version = "0.1.0"
|
||||||
|
authors = ["Giulio De Pasquale <depasquale@giugl.io>"]
|
||||||
|
edition = "2018"
|
||||||
|
|
||||||
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
bitfinex = { path= "/home/giulio/dev/bitfinex-rs" }
|
||||||
|
tokio = { version = "1", features=["full"]}
|
||||||
|
futures-util = { version = "0.3", default-features = false, features = ["async-await", "sink", "std"] }
|
||||||
|
async-trait = "0.1"
|
||||||
|
regex = "1"
|
||||||
|
dyn-clone = "1"
|
||||||
|
log = "0.4"
|
||||||
|
fern = {version = "0.6", features = ["colored"]}
|
||||||
|
chrono = "0.4"
|
||||||
|
byteorder = "1"
|
||||||
|
float-cmp = "0.8"
|
||||||
|
merge = "0.1"
|
||||||
|
futures-retry = "0.6"
|
||||||
|
tungstenite = "0.12"
|
||||||
|
tokio-tungstenite = "0.13"
|
||||||
|
dotenv = "0.15"
|
73
rustybot/src/bot.rs
Normal file
73
rustybot/src/bot.rs
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
use core::time::Duration;
|
||||||
|
|
||||||
|
use log::{error, info};
|
||||||
|
use tokio::time::sleep;
|
||||||
|
|
||||||
|
use crate::connectors::ExchangeDetails;
|
||||||
|
use crate::currency::{Symbol, SymbolPair};
|
||||||
|
use crate::frontend::FrontendManagerHandle;
|
||||||
|
use crate::managers::ExchangeManager;
|
||||||
|
use crate::ticker::Ticker;
|
||||||
|
use crate::BoxError;
|
||||||
|
|
||||||
|
pub struct BfxBot {
|
||||||
|
ticker: Ticker,
|
||||||
|
exchange_managers: Vec<ExchangeManager>,
|
||||||
|
frontend_connector: FrontendManagerHandle,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BfxBot {
|
||||||
|
pub fn new(
|
||||||
|
exchanges: Vec<ExchangeDetails>,
|
||||||
|
trading_symbols: Vec<Symbol>,
|
||||||
|
quote: Symbol,
|
||||||
|
tick_duration: Duration,
|
||||||
|
) -> Self {
|
||||||
|
let pairs: Vec<_> = trading_symbols
|
||||||
|
.iter()
|
||||||
|
.map(|x| SymbolPair::new(quote.clone(), x.clone()))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let exchange_managers = exchanges
|
||||||
|
.iter()
|
||||||
|
.map(|x| ExchangeManager::new(x, &pairs))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
BfxBot {
|
||||||
|
ticker: Ticker::new(tick_duration),
|
||||||
|
exchange_managers,
|
||||||
|
frontend_connector: FrontendManagerHandle::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn start_loop(&mut self) -> Result<(), BoxError> {
|
||||||
|
self.update_exchanges().await?;
|
||||||
|
|
||||||
|
loop {
|
||||||
|
info!("Current tick: {}", self.ticker.current_tick());
|
||||||
|
|
||||||
|
if let Err(e) = self.update().await {
|
||||||
|
error!("Error in main bot loop: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn update_exchanges(&mut self) -> Result<(), BoxError> {
|
||||||
|
for e in &mut self.exchange_managers {
|
||||||
|
if let Err(err) = e.update_managers(self.ticker.current_tick()).await {
|
||||||
|
error!("Error while updating managers: {}", err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn update(&mut self) -> Result<(), BoxError> {
|
||||||
|
sleep(self.ticker.duration()).await;
|
||||||
|
self.ticker.inc();
|
||||||
|
|
||||||
|
self.update_exchanges().await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
745
rustybot/src/connectors.rs
Normal file
745
rustybot/src/connectors.rs
Normal file
@ -0,0 +1,745 @@
|
|||||||
|
use std::convert::{TryFrom, TryInto};
|
||||||
|
use std::fmt::{Debug, Formatter};
|
||||||
|
use std::str::FromStr;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use bitfinex::api::Bitfinex;
|
||||||
|
use bitfinex::book::BookPrecision;
|
||||||
|
use bitfinex::orders::{CancelOrderForm, OrderMeta};
|
||||||
|
use bitfinex::responses::{OrderResponse, TradeResponse};
|
||||||
|
use bitfinex::ticker::TradingPairTicker;
|
||||||
|
use futures_retry::RetryPolicy;
|
||||||
|
use log::trace;
|
||||||
|
use tokio::macros::support::Future;
|
||||||
|
use tokio::time::Duration;
|
||||||
|
|
||||||
|
use crate::currency::{Symbol, SymbolPair};
|
||||||
|
use crate::models::{
|
||||||
|
ActiveOrder, OrderBook, OrderBookEntry, OrderDetails, OrderFee, OrderForm, OrderKind, Position,
|
||||||
|
PositionState, PriceTicker, Trade, TradingFees, TradingPlatform, WalletKind,
|
||||||
|
};
|
||||||
|
use crate::BoxError;
|
||||||
|
|
||||||
|
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
|
||||||
|
pub enum Exchange {
|
||||||
|
Bitfinex,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Eq, PartialEq, Hash, Clone, Debug)]
|
||||||
|
pub enum ExchangeDetails {
|
||||||
|
Bitfinex { api_key: String, api_secret: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
/// You do **not** have to wrap the `Client` in an [`Rc`] or [`Arc`] to **reuse** it,
|
||||||
|
/// because it already uses an [`Arc`] internally.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Client {
|
||||||
|
exchange: Exchange,
|
||||||
|
inner: Arc<Box<dyn Connector>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Client {
|
||||||
|
pub fn new(exchange: &ExchangeDetails) -> Self {
|
||||||
|
match exchange {
|
||||||
|
ExchangeDetails::Bitfinex {
|
||||||
|
api_key,
|
||||||
|
api_secret,
|
||||||
|
} => Self {
|
||||||
|
exchange: Exchange::Bitfinex,
|
||||||
|
inner: Arc::new(Box::new(BitfinexConnector::new(api_key, api_secret))),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn active_positions(
|
||||||
|
&self,
|
||||||
|
pair: &SymbolPair,
|
||||||
|
) -> Result<Option<Vec<Position>>, BoxError> {
|
||||||
|
// retrieving open positions and order book to calculate effective profit/loss
|
||||||
|
let (positions, order_book, fees) = tokio::join!(
|
||||||
|
self.inner.active_positions(pair),
|
||||||
|
self.inner.order_book(pair),
|
||||||
|
self.inner.trading_fees()
|
||||||
|
);
|
||||||
|
|
||||||
|
let (mut positions, order_book, fees) = (positions?, order_book?, fees?);
|
||||||
|
let (best_ask, best_bid) = (order_book.lowest_ask(), order_book.highest_bid());
|
||||||
|
|
||||||
|
if positions.is_none() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
let derivative_taker = fees
|
||||||
|
.iter()
|
||||||
|
.filter_map(|x| match x {
|
||||||
|
TradingFees::Taker {
|
||||||
|
platform,
|
||||||
|
percentage,
|
||||||
|
} if platform == &TradingPlatform::Derivative => Some(percentage),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.next()
|
||||||
|
.ok_or("Could not retrieve derivative taker fee!")?;
|
||||||
|
let margin_taker = fees
|
||||||
|
.iter()
|
||||||
|
.filter_map(|x| match x {
|
||||||
|
TradingFees::Taker {
|
||||||
|
platform,
|
||||||
|
percentage,
|
||||||
|
} if platform == &TradingPlatform::Margin => Some(percentage),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.next()
|
||||||
|
.ok_or("Could not retrieve margin taker fee!")?;
|
||||||
|
|
||||||
|
// updating positions with effective profit/loss
|
||||||
|
positions.iter_mut().flatten().for_each(|x| {
|
||||||
|
let fee = match x.platform() {
|
||||||
|
TradingPlatform::Funding | TradingPlatform::Exchange => {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
TradingPlatform::Margin => margin_taker,
|
||||||
|
TradingPlatform::Derivative => derivative_taker,
|
||||||
|
};
|
||||||
|
|
||||||
|
if x.is_short() {
|
||||||
|
x.update_profit_loss(best_ask, *fee);
|
||||||
|
} else {
|
||||||
|
x.update_profit_loss(best_bid, *fee);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(positions)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn current_prices(&self, pair: &SymbolPair) -> Result<TradingPairTicker, BoxError> {
|
||||||
|
self.inner.current_prices(pair).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn active_orders(&self, pair: &SymbolPair) -> Result<Vec<ActiveOrder>, BoxError> {
|
||||||
|
Ok(self
|
||||||
|
.inner
|
||||||
|
.active_orders(pair)
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.filter(|x| &x.pair() == &pair)
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn submit_order(&self, order: &OrderForm) -> Result<ActiveOrder, BoxError> {
|
||||||
|
self.inner.submit_order(order).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn order_book(&self, pair: &SymbolPair) -> Result<OrderBook, BoxError> {
|
||||||
|
self.inner.order_book(pair).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn cancel_order(&self, order: &ActiveOrder) -> Result<ActiveOrder, BoxError> {
|
||||||
|
self.inner.cancel_order(order).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn transfer_between_wallets(
|
||||||
|
&self,
|
||||||
|
from: &WalletKind,
|
||||||
|
to: &WalletKind,
|
||||||
|
symbol: Symbol,
|
||||||
|
amount: f64,
|
||||||
|
) -> Result<(), BoxError> {
|
||||||
|
self.inner
|
||||||
|
.transfer_between_wallets(from, to, symbol, amount)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn trades_from_order(
|
||||||
|
&self,
|
||||||
|
order: &OrderDetails,
|
||||||
|
) -> Result<Option<Vec<Trade>>, BoxError> {
|
||||||
|
self.inner.trades_from_order(order).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn orders_history(
|
||||||
|
&self,
|
||||||
|
pair: &SymbolPair,
|
||||||
|
) -> Result<Option<Vec<OrderDetails>>, BoxError> {
|
||||||
|
self.inner.orders_history(pair).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
pub trait Connector: Send + Sync {
|
||||||
|
fn name(&self) -> String;
|
||||||
|
async fn active_positions(&self, pair: &SymbolPair) -> Result<Option<Vec<Position>>, BoxError>;
|
||||||
|
async fn current_prices(&self, pair: &SymbolPair) -> Result<TradingPairTicker, BoxError>;
|
||||||
|
async fn order_book(&self, pair: &SymbolPair) -> Result<OrderBook, BoxError>;
|
||||||
|
async fn active_orders(&self, pair: &SymbolPair) -> Result<Vec<ActiveOrder>, BoxError>;
|
||||||
|
async fn submit_order(&self, order: &OrderForm) -> Result<ActiveOrder, BoxError>;
|
||||||
|
async fn cancel_order(&self, order: &ActiveOrder) -> Result<ActiveOrder, BoxError>;
|
||||||
|
async fn transfer_between_wallets(
|
||||||
|
&self,
|
||||||
|
from: &WalletKind,
|
||||||
|
to: &WalletKind,
|
||||||
|
symbol: Symbol,
|
||||||
|
amount: f64,
|
||||||
|
) -> Result<(), BoxError>;
|
||||||
|
async fn trades_from_order(&self, order: &OrderDetails)
|
||||||
|
-> Result<Option<Vec<Trade>>, BoxError>;
|
||||||
|
async fn orders_history(
|
||||||
|
&self,
|
||||||
|
pair: &SymbolPair,
|
||||||
|
) -> Result<Option<Vec<OrderDetails>>, BoxError>;
|
||||||
|
async fn trading_fees(&self) -> Result<Vec<TradingFees>, BoxError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Debug for dyn Connector {
|
||||||
|
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
|
||||||
|
write!(f, "{}", self.name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**************
|
||||||
|
* BITFINEX
|
||||||
|
**************/
|
||||||
|
|
||||||
|
pub struct BitfinexConnector {
|
||||||
|
bfx: Bitfinex,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BitfinexConnector {
|
||||||
|
const AFFILIATE_CODE: &'static str = "XPebOgHxA";
|
||||||
|
|
||||||
|
fn handle_small_nonce_error(e: BoxError) -> RetryPolicy<BoxError> {
|
||||||
|
if e.to_string().contains("nonce: small") {
|
||||||
|
return RetryPolicy::WaitRetry(Duration::from_millis(1));
|
||||||
|
}
|
||||||
|
RetryPolicy::ForwardError(e)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new(api_key: &str, api_secret: &str) -> Self {
|
||||||
|
BitfinexConnector {
|
||||||
|
bfx: Bitfinex::new(Some(api_key.into()), Some(api_secret.into())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn format_trading_pair(pair: &SymbolPair) -> String {
|
||||||
|
if pair.to_string().to_lowercase().contains("test")
|
||||||
|
|| pair.to_string().to_lowercase().contains("f0")
|
||||||
|
{
|
||||||
|
format!("{}:{}", pair.base(), pair.quote())
|
||||||
|
} else {
|
||||||
|
format!("{}{}", pair.base(), pair.quote())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// retry to submit the request until it succeeds.
|
||||||
|
// the function may fail due to concurrent signed requests
|
||||||
|
// parsed in different times by the server
|
||||||
|
async fn retry_nonce<F, Fut, O>(mut func: F) -> Result<O, BoxError>
|
||||||
|
where
|
||||||
|
F: FnMut() -> Fut,
|
||||||
|
Fut: Future<Output = Result<O, BoxError>>,
|
||||||
|
{
|
||||||
|
let response = {
|
||||||
|
loop {
|
||||||
|
match func().await {
|
||||||
|
Ok(response) => break response,
|
||||||
|
Err(e) => {
|
||||||
|
if !e.to_string().contains("nonce: small") {
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_nanos(1)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(response)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl Connector for BitfinexConnector {
|
||||||
|
fn name(&self) -> String {
|
||||||
|
"Bitfinex".into()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn active_positions(&self, pair: &SymbolPair) -> Result<Option<Vec<Position>>, BoxError> {
|
||||||
|
let active_positions =
|
||||||
|
BitfinexConnector::retry_nonce(|| self.bfx.positions.active_positions()).await?;
|
||||||
|
|
||||||
|
let positions: Vec<_> = active_positions
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|x| x.try_into().ok())
|
||||||
|
.filter(|x: &Position| x.pair() == pair)
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
trace!("\t[PositionManager] Retrieved positions for {}", pair);
|
||||||
|
Ok((!positions.is_empty()).then_some(positions))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn current_prices(&self, pair: &SymbolPair) -> Result<TradingPairTicker, BoxError> {
|
||||||
|
let symbol_name = BitfinexConnector::format_trading_pair(pair);
|
||||||
|
|
||||||
|
let ticker: TradingPairTicker = self.bfx.ticker.trading_pair(symbol_name).await?;
|
||||||
|
|
||||||
|
Ok(ticker)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn order_book(&self, pair: &SymbolPair) -> Result<OrderBook, BoxError> {
|
||||||
|
let symbol_name = BitfinexConnector::format_trading_pair(pair);
|
||||||
|
|
||||||
|
let response = BitfinexConnector::retry_nonce(|| {
|
||||||
|
self.bfx.book.trading_pair(&symbol_name, BookPrecision::P0)
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let entries = response
|
||||||
|
.into_iter()
|
||||||
|
.map(|x| OrderBookEntry::Trading {
|
||||||
|
price: x.price,
|
||||||
|
count: x.count as u64,
|
||||||
|
amount: x.amount,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
Ok(OrderBook::new(pair.clone()).with_entries(entries))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn active_orders(&self, _: &SymbolPair) -> Result<Vec<ActiveOrder>, BoxError> {
|
||||||
|
let response = BitfinexConnector::retry_nonce(|| self.bfx.orders.active_orders()).await?;
|
||||||
|
|
||||||
|
Ok(response.iter().map(Into::into).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn submit_order(&self, order: &OrderForm) -> Result<ActiveOrder, BoxError> {
|
||||||
|
let symbol_name = format!("t{}", BitfinexConnector::format_trading_pair(order.pair()));
|
||||||
|
let amount = order.amount();
|
||||||
|
|
||||||
|
let order_form = {
|
||||||
|
let pre_leverage = {
|
||||||
|
match order.kind() {
|
||||||
|
OrderKind::Limit { price } => {
|
||||||
|
bitfinex::orders::OrderForm::new(symbol_name, price, amount, order.into())
|
||||||
|
}
|
||||||
|
OrderKind::Market => {
|
||||||
|
bitfinex::orders::OrderForm::new(symbol_name, 0.0, amount, order.into())
|
||||||
|
}
|
||||||
|
OrderKind::Stop { price } => {
|
||||||
|
bitfinex::orders::OrderForm::new(symbol_name, price, amount, order.into())
|
||||||
|
}
|
||||||
|
OrderKind::StopLimit { price, limit_price } => {
|
||||||
|
bitfinex::orders::OrderForm::new(symbol_name, price, amount, order.into())
|
||||||
|
.with_price_aux_limit(limit_price)?
|
||||||
|
}
|
||||||
|
OrderKind::TrailingStop { distance } => {
|
||||||
|
bitfinex::orders::OrderForm::new(symbol_name, 0.0, amount, order.into())
|
||||||
|
.with_price_trailing(distance)?
|
||||||
|
}
|
||||||
|
OrderKind::FillOrKill { price } => {
|
||||||
|
bitfinex::orders::OrderForm::new(symbol_name, price, amount, order.into())
|
||||||
|
}
|
||||||
|
OrderKind::ImmediateOrCancel { price } => {
|
||||||
|
bitfinex::orders::OrderForm::new(symbol_name, price, amount, order.into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.with_meta(OrderMeta::new(
|
||||||
|
BitfinexConnector::AFFILIATE_CODE.to_string(),
|
||||||
|
))
|
||||||
|
};
|
||||||
|
|
||||||
|
// adding leverage, if any
|
||||||
|
match order.leverage() {
|
||||||
|
// TODO: CHANGEME!!!!
|
||||||
|
Some(_leverage) => pre_leverage.with_leverage(15),
|
||||||
|
// Some(leverage) => pre_leverage.with_leverage(leverage.round() as u32),
|
||||||
|
None => pre_leverage,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let response =
|
||||||
|
BitfinexConnector::retry_nonce(|| self.bfx.orders.submit_order(&order_form)).await?;
|
||||||
|
|
||||||
|
Ok((&response).try_into()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn cancel_order(&self, order: &ActiveOrder) -> Result<ActiveOrder, BoxError> {
|
||||||
|
let cancel_form = order.into();
|
||||||
|
|
||||||
|
let response =
|
||||||
|
BitfinexConnector::retry_nonce(|| self.bfx.orders.cancel_order(&cancel_form)).await?;
|
||||||
|
|
||||||
|
Ok((&response).try_into()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn transfer_between_wallets(
|
||||||
|
&self,
|
||||||
|
from: &WalletKind,
|
||||||
|
to: &WalletKind,
|
||||||
|
symbol: Symbol,
|
||||||
|
amount: f64,
|
||||||
|
) -> Result<(), BoxError> {
|
||||||
|
BitfinexConnector::retry_nonce(|| {
|
||||||
|
self.bfx.account.transfer_between_wallets(
|
||||||
|
from.into(),
|
||||||
|
to.into(),
|
||||||
|
symbol.to_string(),
|
||||||
|
amount,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn trades_from_order(
|
||||||
|
&self,
|
||||||
|
order: &OrderDetails,
|
||||||
|
) -> Result<Option<Vec<Trade>>, BoxError> {
|
||||||
|
let response = BitfinexConnector::retry_nonce(|| {
|
||||||
|
self.bfx
|
||||||
|
.trades
|
||||||
|
.generated_by_order(order.pair().trading_repr(), order.id())
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if response.is_empty() {
|
||||||
|
Ok(None)
|
||||||
|
} else {
|
||||||
|
Ok(Some(response.iter().map(Into::into).collect()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn orders_history(
|
||||||
|
&self,
|
||||||
|
pair: &SymbolPair,
|
||||||
|
) -> Result<Option<Vec<OrderDetails>>, BoxError> {
|
||||||
|
let response =
|
||||||
|
BitfinexConnector::retry_nonce(|| self.bfx.orders.history(Some(pair.trading_repr())))
|
||||||
|
.await?;
|
||||||
|
let mapped_vec: Vec<_> = response.iter().map(Into::into).collect();
|
||||||
|
|
||||||
|
Ok((!mapped_vec.is_empty()).then_some(mapped_vec))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn trading_fees(&self) -> Result<Vec<TradingFees>, BoxError> {
|
||||||
|
let mut fees = vec![];
|
||||||
|
let accountfees =
|
||||||
|
BitfinexConnector::retry_nonce(|| self.bfx.account.account_summary()).await?;
|
||||||
|
|
||||||
|
// Derivatives
|
||||||
|
let derivative_taker = TradingFees::Taker {
|
||||||
|
platform: TradingPlatform::Derivative,
|
||||||
|
percentage: accountfees.derivative_taker() * 100.0,
|
||||||
|
};
|
||||||
|
let derivative_maker = TradingFees::Maker {
|
||||||
|
platform: TradingPlatform::Derivative,
|
||||||
|
percentage: accountfees.derivative_rebate() * 100.0,
|
||||||
|
};
|
||||||
|
fees.push(derivative_taker);
|
||||||
|
fees.push(derivative_maker);
|
||||||
|
|
||||||
|
// Exchange
|
||||||
|
let exchange_taker = TradingFees::Taker {
|
||||||
|
platform: TradingPlatform::Exchange,
|
||||||
|
percentage: accountfees.taker_to_fiat() * 100.0,
|
||||||
|
};
|
||||||
|
let exchange_maker = TradingFees::Maker {
|
||||||
|
platform: TradingPlatform::Exchange,
|
||||||
|
percentage: accountfees.maker_fee() * 100.0,
|
||||||
|
};
|
||||||
|
fees.push(exchange_taker);
|
||||||
|
fees.push(exchange_maker);
|
||||||
|
|
||||||
|
// Margin
|
||||||
|
let margin_taker = TradingFees::Taker {
|
||||||
|
platform: TradingPlatform::Margin,
|
||||||
|
percentage: accountfees.taker_to_fiat() * 100.0,
|
||||||
|
};
|
||||||
|
let margin_maker = TradingFees::Maker {
|
||||||
|
platform: TradingPlatform::Margin,
|
||||||
|
percentage: accountfees.maker_fee() * 100.0,
|
||||||
|
};
|
||||||
|
fees.push(margin_taker);
|
||||||
|
fees.push(margin_maker);
|
||||||
|
|
||||||
|
Ok(fees)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&ActiveOrder> for CancelOrderForm {
|
||||||
|
fn from(o: &ActiveOrder) -> Self {
|
||||||
|
Self::from_id(o.id())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<&bitfinex::responses::OrderResponse> for ActiveOrder {
|
||||||
|
type Error = BoxError;
|
||||||
|
|
||||||
|
fn try_from(response: &OrderResponse) -> Result<Self, Self::Error> {
|
||||||
|
let pair = SymbolPair::from_str(response.symbol())?;
|
||||||
|
|
||||||
|
Ok(ActiveOrder::new(
|
||||||
|
Exchange::Bitfinex,
|
||||||
|
response.id(),
|
||||||
|
pair.clone(),
|
||||||
|
OrderForm::new(pair, response.into(), response.into(), response.amount()),
|
||||||
|
response.mts_create(),
|
||||||
|
response.mts_update(),
|
||||||
|
)
|
||||||
|
.with_group_id(response.gid())
|
||||||
|
.with_client_id(Some(response.cid())))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryInto<Position> for bitfinex::positions::Position {
|
||||||
|
type Error = BoxError;
|
||||||
|
|
||||||
|
fn try_into(self) -> Result<Position, Self::Error> {
|
||||||
|
let state = {
|
||||||
|
if self.status().to_lowercase().contains("active") {
|
||||||
|
PositionState::Open
|
||||||
|
} else {
|
||||||
|
PositionState::Closed
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let platform = {
|
||||||
|
if self.symbol().to_ascii_lowercase().contains("f0") {
|
||||||
|
TradingPlatform::Derivative
|
||||||
|
} else {
|
||||||
|
TradingPlatform::Margin
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
println!("leverage: {}", self.leverage());
|
||||||
|
Ok(Position::new(
|
||||||
|
SymbolPair::from_str(self.symbol())?,
|
||||||
|
state,
|
||||||
|
self.amount(),
|
||||||
|
self.base_price(),
|
||||||
|
self.pl(),
|
||||||
|
self.pl_perc(),
|
||||||
|
self.price_liq(),
|
||||||
|
self.position_id(),
|
||||||
|
platform,
|
||||||
|
self.leverage(),
|
||||||
|
)
|
||||||
|
.with_creation_date(self.mts_create())
|
||||||
|
.with_creation_update(self.mts_update()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&OrderForm> for bitfinex::orders::OrderKind {
|
||||||
|
fn from(o: &OrderForm) -> Self {
|
||||||
|
match o.platform() {
|
||||||
|
TradingPlatform::Exchange => match o.kind() {
|
||||||
|
OrderKind::Limit { .. } => bitfinex::orders::OrderKind::ExchangeLimit,
|
||||||
|
OrderKind::Market { .. } => bitfinex::orders::OrderKind::ExchangeMarket,
|
||||||
|
OrderKind::Stop { .. } => bitfinex::orders::OrderKind::ExchangeStop,
|
||||||
|
OrderKind::StopLimit { .. } => bitfinex::orders::OrderKind::ExchangeStopLimit,
|
||||||
|
OrderKind::TrailingStop { .. } => bitfinex::orders::OrderKind::ExchangeTrailingStop,
|
||||||
|
OrderKind::FillOrKill { .. } => bitfinex::orders::OrderKind::ExchangeFok,
|
||||||
|
OrderKind::ImmediateOrCancel { .. } => bitfinex::orders::OrderKind::ExchangeIoc,
|
||||||
|
},
|
||||||
|
TradingPlatform::Margin | TradingPlatform::Derivative => match o.kind() {
|
||||||
|
OrderKind::Limit { .. } => bitfinex::orders::OrderKind::Limit,
|
||||||
|
OrderKind::Market { .. } => bitfinex::orders::OrderKind::Market,
|
||||||
|
OrderKind::Stop { .. } => bitfinex::orders::OrderKind::Stop,
|
||||||
|
OrderKind::StopLimit { .. } => bitfinex::orders::OrderKind::StopLimit,
|
||||||
|
OrderKind::TrailingStop { .. } => bitfinex::orders::OrderKind::TrailingStop,
|
||||||
|
OrderKind::FillOrKill { .. } => bitfinex::orders::OrderKind::Fok,
|
||||||
|
OrderKind::ImmediateOrCancel { .. } => bitfinex::orders::OrderKind::Ioc,
|
||||||
|
},
|
||||||
|
_ => unimplemented!(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&bitfinex::responses::OrderResponse> for TradingPlatform {
|
||||||
|
fn from(response: &OrderResponse) -> Self {
|
||||||
|
match response.order_type() {
|
||||||
|
bitfinex::orders::OrderKind::Limit
|
||||||
|
| bitfinex::orders::OrderKind::Market
|
||||||
|
| bitfinex::orders::OrderKind::StopLimit
|
||||||
|
| bitfinex::orders::OrderKind::Stop
|
||||||
|
| bitfinex::orders::OrderKind::TrailingStop
|
||||||
|
| bitfinex::orders::OrderKind::Fok
|
||||||
|
| bitfinex::orders::OrderKind::Ioc => Self::Margin,
|
||||||
|
_ => Self::Exchange,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&bitfinex::orders::ActiveOrder> for TradingPlatform {
|
||||||
|
fn from(response: &bitfinex::orders::ActiveOrder) -> Self {
|
||||||
|
match response.order_type() {
|
||||||
|
bitfinex::orders::OrderKind::Limit
|
||||||
|
| bitfinex::orders::OrderKind::Market
|
||||||
|
| bitfinex::orders::OrderKind::StopLimit
|
||||||
|
| bitfinex::orders::OrderKind::Stop
|
||||||
|
| bitfinex::orders::OrderKind::TrailingStop
|
||||||
|
| bitfinex::orders::OrderKind::Fok
|
||||||
|
| bitfinex::orders::OrderKind::Ioc => Self::Margin,
|
||||||
|
_ => Self::Exchange,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&bitfinex::responses::OrderResponse> for OrderKind {
|
||||||
|
fn from(response: &OrderResponse) -> Self {
|
||||||
|
match response.order_type() {
|
||||||
|
bitfinex::orders::OrderKind::Limit | bitfinex::orders::OrderKind::ExchangeLimit => {
|
||||||
|
Self::Limit {
|
||||||
|
price: response.price(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bitfinex::orders::OrderKind::Market | bitfinex::orders::OrderKind::ExchangeMarket => {
|
||||||
|
Self::Market
|
||||||
|
}
|
||||||
|
bitfinex::orders::OrderKind::Stop | bitfinex::orders::OrderKind::ExchangeStop => {
|
||||||
|
Self::Stop {
|
||||||
|
price: response.price(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bitfinex::orders::OrderKind::StopLimit
|
||||||
|
| bitfinex::orders::OrderKind::ExchangeStopLimit => Self::StopLimit {
|
||||||
|
price: response.price(),
|
||||||
|
limit_price: response.price_aux_limit().expect("Limit price not found!"),
|
||||||
|
},
|
||||||
|
bitfinex::orders::OrderKind::TrailingStop
|
||||||
|
| bitfinex::orders::OrderKind::ExchangeTrailingStop => Self::TrailingStop {
|
||||||
|
distance: response.price_trailing().expect("Distance not found!"),
|
||||||
|
},
|
||||||
|
bitfinex::orders::OrderKind::Fok | bitfinex::orders::OrderKind::ExchangeFok => {
|
||||||
|
Self::FillOrKill {
|
||||||
|
price: response.price(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bitfinex::orders::OrderKind::Ioc | bitfinex::orders::OrderKind::ExchangeIoc => {
|
||||||
|
Self::ImmediateOrCancel {
|
||||||
|
price: response.price(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&bitfinex::orders::ActiveOrder> for OrderKind {
|
||||||
|
fn from(response: &bitfinex::orders::ActiveOrder) -> Self {
|
||||||
|
match response.order_type() {
|
||||||
|
bitfinex::orders::OrderKind::Limit | bitfinex::orders::OrderKind::ExchangeLimit => {
|
||||||
|
Self::Limit {
|
||||||
|
price: response.price(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bitfinex::orders::OrderKind::Market | bitfinex::orders::OrderKind::ExchangeMarket => {
|
||||||
|
Self::Market {}
|
||||||
|
}
|
||||||
|
bitfinex::orders::OrderKind::Stop | bitfinex::orders::OrderKind::ExchangeStop => {
|
||||||
|
Self::Stop {
|
||||||
|
price: response.price(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bitfinex::orders::OrderKind::StopLimit
|
||||||
|
| bitfinex::orders::OrderKind::ExchangeStopLimit => Self::StopLimit {
|
||||||
|
price: response.price(),
|
||||||
|
limit_price: response.price_aux_limit().expect("Limit price not found!"),
|
||||||
|
},
|
||||||
|
bitfinex::orders::OrderKind::TrailingStop
|
||||||
|
| bitfinex::orders::OrderKind::ExchangeTrailingStop => Self::TrailingStop {
|
||||||
|
distance: response.price_trailing().expect("Distance not found!"),
|
||||||
|
},
|
||||||
|
bitfinex::orders::OrderKind::Fok | bitfinex::orders::OrderKind::ExchangeFok => {
|
||||||
|
Self::FillOrKill {
|
||||||
|
price: response.price(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bitfinex::orders::OrderKind::Ioc | bitfinex::orders::OrderKind::ExchangeIoc => {
|
||||||
|
Self::ImmediateOrCancel {
|
||||||
|
price: response.price(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&bitfinex::orders::ActiveOrder> for ActiveOrder {
|
||||||
|
fn from(order: &bitfinex::orders::ActiveOrder) -> Self {
|
||||||
|
let pair = SymbolPair::from_str(&order.symbol()).expect("Invalid symbol!");
|
||||||
|
|
||||||
|
ActiveOrder::new(
|
||||||
|
Exchange::Bitfinex,
|
||||||
|
order.id(),
|
||||||
|
pair.clone(),
|
||||||
|
OrderForm::new(pair, order.into(), order.into(), order.amount()),
|
||||||
|
order.creation_timestamp(),
|
||||||
|
order.update_timestamp(),
|
||||||
|
)
|
||||||
|
.with_client_id(Some(order.client_id()))
|
||||||
|
.with_group_id(order.group_id())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<TradingPairTicker> for PriceTicker {
|
||||||
|
fn from(t: TradingPairTicker) -> Self {
|
||||||
|
Self {
|
||||||
|
bid: t.bid,
|
||||||
|
bid_size: t.bid_size,
|
||||||
|
ask: t.ask,
|
||||||
|
ask_size: t.ask_size,
|
||||||
|
daily_change: t.daily_change,
|
||||||
|
daily_change_perc: t.daily_change_perc,
|
||||||
|
last_price: t.last_price,
|
||||||
|
volume: t.volume,
|
||||||
|
high: t.high,
|
||||||
|
low: t.low,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&WalletKind> for &bitfinex::account::WalletKind {
|
||||||
|
fn from(k: &WalletKind) -> Self {
|
||||||
|
match k {
|
||||||
|
WalletKind::Exchange => &bitfinex::account::WalletKind::Exchange,
|
||||||
|
WalletKind::Margin => &bitfinex::account::WalletKind::Margin,
|
||||||
|
WalletKind::Funding => &bitfinex::account::WalletKind::Funding,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&bitfinex::orders::ActiveOrder> for OrderDetails {
|
||||||
|
fn from(order: &bitfinex::orders::ActiveOrder) -> Self {
|
||||||
|
Self::new(
|
||||||
|
Exchange::Bitfinex,
|
||||||
|
order.id(),
|
||||||
|
SymbolPair::from_str(order.symbol()).unwrap(),
|
||||||
|
order.into(),
|
||||||
|
order.into(),
|
||||||
|
order.update_timestamp(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: fields are hardcoded, to fix
|
||||||
|
impl From<&bitfinex::responses::TradeResponse> for Trade {
|
||||||
|
fn from(response: &TradeResponse) -> Self {
|
||||||
|
let pair = SymbolPair::from_str(&response.symbol()).unwrap();
|
||||||
|
let fee = {
|
||||||
|
if response.is_maker() {
|
||||||
|
OrderFee::Maker(response.fee())
|
||||||
|
} else {
|
||||||
|
OrderFee::Taker(response.fee())
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
Self {
|
||||||
|
trade_id: response.trade_id(),
|
||||||
|
pair,
|
||||||
|
execution_timestamp: response.execution_timestamp(),
|
||||||
|
price: response.execution_price(),
|
||||||
|
amount: response.execution_amount(),
|
||||||
|
fee,
|
||||||
|
fee_currency: Symbol::new(response.symbol().to_owned()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
196
rustybot/src/currency.rs
Normal file
196
rustybot/src/currency.rs
Normal file
@ -0,0 +1,196 @@
|
|||||||
|
use core::fmt;
|
||||||
|
use std::borrow::Cow;
|
||||||
|
use std::fmt::{Display, Formatter};
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
use regex::Regex;
|
||||||
|
|
||||||
|
use crate::BoxError;
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq, Hash, Debug, Eq)]
|
||||||
|
pub struct Symbol {
|
||||||
|
name: Cow<'static, str>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S> From<S> for Symbol
|
||||||
|
where
|
||||||
|
S: Into<String>,
|
||||||
|
{
|
||||||
|
fn from(item: S) -> Self {
|
||||||
|
Symbol::new(item.into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Symbol {
|
||||||
|
pub const XMR: Symbol = Symbol::new_static("XMR");
|
||||||
|
pub const BTC: Symbol = Symbol::new_static("BTC");
|
||||||
|
pub const ETH: Symbol = Symbol::new_static("ETH");
|
||||||
|
pub const LTC: Symbol = Symbol::new_static("LTC");
|
||||||
|
pub const DOT: Symbol = Symbol::new_static("DOT");
|
||||||
|
|
||||||
|
pub const DERIV_BTC: Symbol = Symbol::new_static("BTCF0");
|
||||||
|
pub const DERIV_ETH: Symbol = Symbol::new_static("ETHF0");
|
||||||
|
pub const DERIV_USDT: Symbol = Symbol::new_static("USTF0");
|
||||||
|
|
||||||
|
// Paper trading
|
||||||
|
pub const TESTBTC: Symbol = Symbol::new_static("TESTBTC");
|
||||||
|
pub const TESTUSD: Symbol = Symbol::new_static("TESTUSD");
|
||||||
|
|
||||||
|
pub const DERIV_TESTBTC: Symbol = Symbol::new_static("TESTBTCF0");
|
||||||
|
pub const DERIV_TESTUSDT: Symbol = Symbol::new_static("TESTUSDTF0");
|
||||||
|
|
||||||
|
// Fiat coins
|
||||||
|
pub const USD: Symbol = Symbol::new_static("USD");
|
||||||
|
pub const GBP: Symbol = Symbol::new_static("GBP");
|
||||||
|
pub const EUR: Symbol = Symbol::new_static("EUR");
|
||||||
|
|
||||||
|
pub fn new(name: String) -> Self {
|
||||||
|
Symbol {
|
||||||
|
name: Cow::from(name),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const fn new_static(name: &'static str) -> Self {
|
||||||
|
Symbol {
|
||||||
|
name: Cow::Borrowed(name),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn name(&self) -> &str {
|
||||||
|
&self.name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for Symbol {
|
||||||
|
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(f, "{}", self.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||||
|
pub struct SymbolPair {
|
||||||
|
quote: Symbol,
|
||||||
|
base: Symbol,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SymbolPair {
|
||||||
|
pub fn new(quote: Symbol, base: Symbol) -> Self {
|
||||||
|
SymbolPair { quote, base }
|
||||||
|
}
|
||||||
|
pub fn trading_repr(&self) -> String {
|
||||||
|
format!("t{}{}", self.base, self.quote)
|
||||||
|
}
|
||||||
|
pub fn funding_repr(&self) -> String {
|
||||||
|
format!("f{}{}", self.base, self.quote)
|
||||||
|
}
|
||||||
|
pub fn quote(&self) -> &Symbol {
|
||||||
|
&self.quote
|
||||||
|
}
|
||||||
|
pub fn base(&self) -> &Symbol {
|
||||||
|
&self.base
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Into<String> for SymbolPair {
|
||||||
|
fn into(self) -> String {
|
||||||
|
format!("{}/{}", self.base, self.quote)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromStr for SymbolPair {
|
||||||
|
type Err = BoxError;
|
||||||
|
|
||||||
|
fn from_str(value: &str) -> Result<Self, Self::Err> {
|
||||||
|
const REGEX: &str = r"^[t|f](?P<base>\w{3,7}):?(?P<quote>\w{3,7})";
|
||||||
|
|
||||||
|
let captures = Regex::new(REGEX)?.captures(&value).ok_or("Invalid input")?;
|
||||||
|
let quote = captures.name("quote").ok_or("Quote not found")?.as_str();
|
||||||
|
let base = captures.name("base").ok_or("Base not found")?.as_str();
|
||||||
|
|
||||||
|
Ok(SymbolPair {
|
||||||
|
quote: quote.into(),
|
||||||
|
base: base.into(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for SymbolPair {
|
||||||
|
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(f, "{}/{}", self.base, self.quote)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
enum WalletKind {
|
||||||
|
Margin,
|
||||||
|
Exchange,
|
||||||
|
Funding,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct Balance {
|
||||||
|
pair: SymbolPair,
|
||||||
|
base_price: f64,
|
||||||
|
base_amount: f64,
|
||||||
|
quote_equivalent: f64,
|
||||||
|
wallet: WalletKind,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Balance {
|
||||||
|
pub fn new(pair: SymbolPair, base_price: f64, base_amount: f64, wallet: WalletKind) -> Self {
|
||||||
|
Balance {
|
||||||
|
pair,
|
||||||
|
base_price,
|
||||||
|
base_amount,
|
||||||
|
quote_equivalent: base_amount * base_price,
|
||||||
|
wallet,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn pair(&self) -> &SymbolPair {
|
||||||
|
&self.pair
|
||||||
|
}
|
||||||
|
pub fn base_price(&self) -> f64 {
|
||||||
|
self.base_price
|
||||||
|
}
|
||||||
|
pub fn base_amount(&self) -> f64 {
|
||||||
|
self.base_amount
|
||||||
|
}
|
||||||
|
pub fn quote_equivalent(&self) -> f64 {
|
||||||
|
self.quote_equivalent
|
||||||
|
}
|
||||||
|
pub fn wallet(&self) -> &WalletKind {
|
||||||
|
&self.wallet
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct BalanceGroup {
|
||||||
|
quote_equivalent: f64,
|
||||||
|
balances: Vec<Balance>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BalanceGroup {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
BalanceGroup {
|
||||||
|
balances: Vec::new(),
|
||||||
|
quote_equivalent: 0f64,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_balance(&mut self, balance: &Balance) {
|
||||||
|
self.balances.push(balance.clone());
|
||||||
|
|
||||||
|
self.quote_equivalent += balance.quote_equivalent()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn currency_names(&self) -> Vec<String> {
|
||||||
|
self.balances
|
||||||
|
.iter()
|
||||||
|
.map(|x| x.pair().base().name().into())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn balances(&self) -> &Vec<Balance> {
|
||||||
|
&self.balances
|
||||||
|
}
|
||||||
|
}
|
70
rustybot/src/events.rs
Normal file
70
rustybot/src/events.rs
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
use tokio::sync::oneshot;
|
||||||
|
|
||||||
|
use crate::managers::OptionUpdate;
|
||||||
|
use crate::models::OrderForm;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct ActorMessage {
|
||||||
|
pub(crate) message: ActionMessage,
|
||||||
|
pub(crate) respond_to: oneshot::Sender<OptionUpdate>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum ActionMessage {
|
||||||
|
Update { tick: u64 },
|
||||||
|
ClosePosition { position_id: u64 },
|
||||||
|
SubmitOrder { order: OrderForm },
|
||||||
|
ClosePositionOrders { position_id: u64 },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
|
||||||
|
pub struct EventMetadata {
|
||||||
|
position_id: Option<u64>,
|
||||||
|
order_id: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventMetadata {
|
||||||
|
pub fn new(position_id: Option<u64>, order_id: Option<u64>) -> Self {
|
||||||
|
EventMetadata {
|
||||||
|
position_id,
|
||||||
|
order_id,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
|
||||||
|
pub enum EventKind {
|
||||||
|
NewMinimum,
|
||||||
|
NewMaximum,
|
||||||
|
ReachedLoss,
|
||||||
|
ReachedBreakEven,
|
||||||
|
ReachedMinProfit,
|
||||||
|
ReachedGoodProfit,
|
||||||
|
ReachedMaxLoss,
|
||||||
|
TrailingStopSet,
|
||||||
|
TrailingStopMoved,
|
||||||
|
OrderSubmitted,
|
||||||
|
NewTick,
|
||||||
|
PositionClosed { position_id: u64 },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
|
||||||
|
pub struct Event {
|
||||||
|
kind: EventKind,
|
||||||
|
tick: u64,
|
||||||
|
metadata: Option<EventMetadata>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Event {
|
||||||
|
pub fn new(kind: EventKind, tick: u64, metadata: Option<EventMetadata>) -> Self {
|
||||||
|
Event {
|
||||||
|
kind,
|
||||||
|
tick,
|
||||||
|
metadata,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_metadata(&self) -> bool {
|
||||||
|
self.metadata.is_some()
|
||||||
|
}
|
||||||
|
}
|
90
rustybot/src/frontend.rs
Normal file
90
rustybot/src/frontend.rs
Normal file
@ -0,0 +1,90 @@
|
|||||||
|
use log::info;
|
||||||
|
use tokio::sync::mpsc::{channel, Receiver, Sender};
|
||||||
|
|
||||||
|
use crate::events::{ActorMessage};
|
||||||
|
use crate::BoxError;
|
||||||
|
use futures_util::stream::TryStreamExt;
|
||||||
|
use futures_util::StreamExt;
|
||||||
|
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
|
||||||
|
use tokio::net::{TcpListener, TcpStream};
|
||||||
|
use tokio_tungstenite::accept_async;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct FrontendManager {
|
||||||
|
receiver: Receiver<ActorMessage>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FrontendManager {
|
||||||
|
pub fn new(receiver: Receiver<ActorMessage>) -> Self {
|
||||||
|
Self { receiver }
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_ws_connection(stream: TcpStream, addr: SocketAddr) -> Result<(), BoxError> {
|
||||||
|
let websocket = accept_async(stream).await?;
|
||||||
|
info!("Received WebSocket connection <{:?}>", addr);
|
||||||
|
|
||||||
|
let (_, ws_in) = websocket.split();
|
||||||
|
|
||||||
|
let on_received = ws_in.try_for_each(move |msg| {
|
||||||
|
info!(
|
||||||
|
"Received a message from {:?}: {}",
|
||||||
|
addr,
|
||||||
|
msg.to_text().unwrap()
|
||||||
|
);
|
||||||
|
|
||||||
|
futures_util::future::ok(())
|
||||||
|
});
|
||||||
|
|
||||||
|
tokio::spawn(on_received);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn websocket() -> Result<(), BoxError> {
|
||||||
|
let server = TcpListener::bind("127.0.0.1:3012").await?;
|
||||||
|
|
||||||
|
while let Ok((stream, addr)) = server.accept().await {
|
||||||
|
tokio::spawn(FrontendManager::handle_ws_connection(stream, addr));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn handle_message(&mut self, message: ActorMessage) -> Result<(), BoxError> {
|
||||||
|
match message.message {
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(message
|
||||||
|
.respond_to
|
||||||
|
.send((None, None))
|
||||||
|
.map_err(|_| BoxError::from("Could not send message."))?)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct FrontendManagerHandle {
|
||||||
|
sender: Sender<ActorMessage>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FrontendManagerHandle {
|
||||||
|
// async fn run_frontend_manager(mut manager: FrontendManager) {
|
||||||
|
// info!("Frontend handler ready");
|
||||||
|
//
|
||||||
|
// while let Some(msg) = manager.receiver.recv().await {
|
||||||
|
// manager.handle_message(msg).await.unwrap();
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
pub fn new() -> Self {
|
||||||
|
let (sender, receiver) = channel(1);
|
||||||
|
|
||||||
|
let _frontend = FrontendManager::new(receiver);
|
||||||
|
|
||||||
|
tokio::spawn(FrontendManager::websocket());
|
||||||
|
// tokio::spawn(FrontendManagerHandle::run_frontend_manager(frontend));
|
||||||
|
|
||||||
|
Self { sender }
|
||||||
|
}
|
||||||
|
}
|
79
rustybot/src/main.rs
Normal file
79
rustybot/src/main.rs
Normal file
@ -0,0 +1,79 @@
|
|||||||
|
#![feature(drain_filter)]
|
||||||
|
#![feature(bool_to_option)]
|
||||||
|
|
||||||
|
use std::env;
|
||||||
|
|
||||||
|
use fern::colors::{Color, ColoredLevelConfig};
|
||||||
|
use log::LevelFilter::{Trace};
|
||||||
|
use tokio::time::Duration;
|
||||||
|
|
||||||
|
use crate::bot::BfxBot;
|
||||||
|
use crate::connectors::ExchangeDetails;
|
||||||
|
use crate::currency::Symbol;
|
||||||
|
|
||||||
|
mod bot;
|
||||||
|
mod connectors;
|
||||||
|
mod currency;
|
||||||
|
mod events;
|
||||||
|
mod frontend;
|
||||||
|
mod managers;
|
||||||
|
mod models;
|
||||||
|
mod strategy;
|
||||||
|
mod ticker;
|
||||||
|
|
||||||
|
pub type BoxError = Box<dyn std::error::Error + Send + Sync>;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<(), BoxError> {
|
||||||
|
setup_logger()?;
|
||||||
|
dotenv::dotenv()?;
|
||||||
|
|
||||||
|
let api_key = env::vars()
|
||||||
|
.find(|(k, _v)| k == "API_KEY")
|
||||||
|
.map(|(_k, v)| v)
|
||||||
|
.ok_or("API_KEY not set!")?;
|
||||||
|
let api_secret = env::vars()
|
||||||
|
.find(|(k, _v)| k == "API_SECRET")
|
||||||
|
.map(|(_k, v)| v)
|
||||||
|
.ok_or("API_SECRET not set!")?;
|
||||||
|
|
||||||
|
let bitfinex = ExchangeDetails::Bitfinex {
|
||||||
|
api_key: api_key.into(),
|
||||||
|
api_secret: api_secret.into(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut bot = BfxBot::new(
|
||||||
|
vec![bitfinex],
|
||||||
|
vec![Symbol::DERIV_ETH, Symbol::DERIV_BTC],
|
||||||
|
Symbol::DERIV_USDT,
|
||||||
|
Duration::new(10, 0),
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(bot.start_loop().await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn setup_logger() -> Result<(), fern::InitError> {
|
||||||
|
let colors = ColoredLevelConfig::new()
|
||||||
|
.info(Color::Green)
|
||||||
|
.error(Color::Red)
|
||||||
|
.trace(Color::Blue)
|
||||||
|
.debug(Color::Cyan)
|
||||||
|
.warn(Color::Yellow);
|
||||||
|
|
||||||
|
fern::Dispatch::new()
|
||||||
|
.format(move |out, message, record| {
|
||||||
|
out.finish(format_args!(
|
||||||
|
"[{}][{}] {}",
|
||||||
|
record.target(),
|
||||||
|
colors.color(record.level()),
|
||||||
|
message
|
||||||
|
))
|
||||||
|
})
|
||||||
|
.level(Trace)
|
||||||
|
.filter(|metadata| metadata.target().contains("rustybot"))
|
||||||
|
.chain(std::io::stdout())
|
||||||
|
// .chain(fern::log_file("rustico.log")?)
|
||||||
|
.apply()?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
743
rustybot/src/managers.rs
Normal file
743
rustybot/src/managers.rs
Normal file
@ -0,0 +1,743 @@
|
|||||||
|
use std::collections::HashMap;
|
||||||
|
use std::ops::Neg;
|
||||||
|
|
||||||
|
use futures_util::stream::FuturesUnordered;
|
||||||
|
use futures_util::StreamExt;
|
||||||
|
use log::{debug, error, info, trace};
|
||||||
|
use merge::Merge;
|
||||||
|
use tokio::sync::mpsc::channel;
|
||||||
|
use tokio::sync::mpsc::{Receiver, Sender};
|
||||||
|
use tokio::sync::oneshot;
|
||||||
|
use tokio::time::Duration;
|
||||||
|
|
||||||
|
use crate::connectors::{Client, ExchangeDetails};
|
||||||
|
use crate::currency::SymbolPair;
|
||||||
|
use crate::events::{ActionMessage, ActorMessage, Event};
|
||||||
|
use crate::models::{
|
||||||
|
ActiveOrder, OrderBook, OrderForm, OrderKind, Position, PriceTicker,
|
||||||
|
};
|
||||||
|
use crate::strategy::{HiddenTrailingStop, MarketEnforce, OrderStrategy, PositionStrategy};
|
||||||
|
use crate::BoxError;
|
||||||
|
|
||||||
|
pub type OptionUpdate = (Option<Vec<Event>>, Option<Vec<ActionMessage>>);
|
||||||
|
|
||||||
|
/******************
|
||||||
|
* PRICES
|
||||||
|
******************/
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct PriceManager {
|
||||||
|
receiver: Receiver<ActorMessage>,
|
||||||
|
pair: SymbolPair,
|
||||||
|
prices: Vec<PriceEntry>,
|
||||||
|
client: Client,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PriceManager {
|
||||||
|
pub fn new(receiver: Receiver<ActorMessage>, pair: SymbolPair, client: Client) -> Self {
|
||||||
|
PriceManager {
|
||||||
|
receiver,
|
||||||
|
pair,
|
||||||
|
prices: Vec::new(),
|
||||||
|
client,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn handle_message(&mut self, message: ActorMessage) -> Result<(), BoxError> {
|
||||||
|
if let ActionMessage::Update { tick } = message.message {
|
||||||
|
let a = self.update(tick).await?;
|
||||||
|
self.add_entry(a);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(message
|
||||||
|
.respond_to
|
||||||
|
.send((None, None))
|
||||||
|
.map_err(|_| BoxError::from("Could not send message."))?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_entry(&mut self, entry: PriceEntry) {
|
||||||
|
self.prices.push(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn update(&mut self, tick: u64) -> Result<PriceEntry, BoxError> {
|
||||||
|
let current_prices = self.client.current_prices(&self.pair).await?.into();
|
||||||
|
|
||||||
|
Ok(PriceEntry::new(
|
||||||
|
tick,
|
||||||
|
current_prices,
|
||||||
|
self.pair.clone(),
|
||||||
|
None,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn pair(&self) -> &SymbolPair {
|
||||||
|
&self.pair
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct PriceManagerHandle {
|
||||||
|
sender: Sender<ActorMessage>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PriceManagerHandle {
|
||||||
|
async fn run_price_manager(mut manager: PriceManager) {
|
||||||
|
while let Some(msg) = manager.receiver.recv().await {
|
||||||
|
manager.handle_message(msg).await.unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new(pair: SymbolPair, client: Client) -> Self {
|
||||||
|
let (sender, receiver) = channel(1);
|
||||||
|
|
||||||
|
let price_manager = PriceManager::new(receiver, pair, client);
|
||||||
|
tokio::spawn(PriceManagerHandle::run_price_manager(price_manager));
|
||||||
|
|
||||||
|
Self { sender }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn update(&mut self, tick: u64) -> Result<OptionUpdate, BoxError> {
|
||||||
|
let (send, recv) = oneshot::channel();
|
||||||
|
|
||||||
|
self.sender
|
||||||
|
.send(ActorMessage {
|
||||||
|
message: ActionMessage::Update { tick },
|
||||||
|
respond_to: send,
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(recv.await?)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct PriceEntry {
|
||||||
|
tick: u64,
|
||||||
|
pair: SymbolPair,
|
||||||
|
price: PriceTicker,
|
||||||
|
events: Option<Vec<Event>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PriceEntry {
|
||||||
|
pub fn new(
|
||||||
|
tick: u64,
|
||||||
|
price: PriceTicker,
|
||||||
|
pair: SymbolPair,
|
||||||
|
events: Option<Vec<Event>>,
|
||||||
|
) -> Self {
|
||||||
|
PriceEntry {
|
||||||
|
tick,
|
||||||
|
pair,
|
||||||
|
price,
|
||||||
|
events,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn tick(&self) -> u64 {
|
||||||
|
self.tick
|
||||||
|
}
|
||||||
|
pub fn pair(&self) -> &SymbolPair {
|
||||||
|
&self.pair
|
||||||
|
}
|
||||||
|
pub fn price(&self) -> PriceTicker {
|
||||||
|
self.price
|
||||||
|
}
|
||||||
|
pub fn events(&self) -> &Option<Vec<Event>> {
|
||||||
|
&self.events
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/******************
|
||||||
|
* POSITIONS
|
||||||
|
******************/
|
||||||
|
|
||||||
|
pub struct PositionManagerHandle {
|
||||||
|
sender: Sender<ActorMessage>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PositionManagerHandle {
|
||||||
|
async fn run_position_manager(mut manager: PositionManager) {
|
||||||
|
while let Some(msg) = manager.receiver.recv().await {
|
||||||
|
manager.handle_message(msg).await.unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new(pair: SymbolPair, client: Client, strategy: Box<dyn PositionStrategy>) -> Self {
|
||||||
|
let (sender, receiver) = channel(1);
|
||||||
|
|
||||||
|
let manager = PositionManager::new(receiver, pair, client, strategy);
|
||||||
|
|
||||||
|
tokio::spawn(PositionManagerHandle::run_position_manager(manager));
|
||||||
|
|
||||||
|
Self { sender }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn update(&mut self, tick: u64) -> Result<OptionUpdate, BoxError> {
|
||||||
|
let (send, recv) = oneshot::channel();
|
||||||
|
|
||||||
|
self.sender
|
||||||
|
.send(ActorMessage {
|
||||||
|
message: ActionMessage::Update { tick },
|
||||||
|
respond_to: send,
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let response = recv.await?;
|
||||||
|
Ok(response)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct PositionManager {
|
||||||
|
receiver: Receiver<ActorMessage>,
|
||||||
|
current_tick: u64,
|
||||||
|
pair: SymbolPair,
|
||||||
|
positions_history: HashMap<u64, Position>,
|
||||||
|
active_position: Option<Position>,
|
||||||
|
client: Client,
|
||||||
|
strategy: Box<dyn PositionStrategy>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PositionManager {
|
||||||
|
pub fn new(
|
||||||
|
receiver: Receiver<ActorMessage>,
|
||||||
|
pair: SymbolPair,
|
||||||
|
client: Client,
|
||||||
|
strategy: Box<dyn PositionStrategy>,
|
||||||
|
) -> Self {
|
||||||
|
PositionManager {
|
||||||
|
receiver,
|
||||||
|
current_tick: 0,
|
||||||
|
pair,
|
||||||
|
positions_history: HashMap::new(),
|
||||||
|
active_position: None,
|
||||||
|
client,
|
||||||
|
strategy,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn current_tick(&self) -> u64 {
|
||||||
|
self.current_tick
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn handle_message(&mut self, msg: ActorMessage) -> Result<(), BoxError> {
|
||||||
|
let (events, messages) = match msg.message {
|
||||||
|
ActionMessage::Update { tick } => self.update(tick).await?,
|
||||||
|
_ => (None, None),
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(msg
|
||||||
|
.respond_to
|
||||||
|
.send((events, messages))
|
||||||
|
.map_err(|_| BoxError::from("Could not send message."))?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn update(&mut self, tick: u64) -> Result<OptionUpdate, BoxError> {
|
||||||
|
trace!("\t[PositionManager] Updating {}", self.pair);
|
||||||
|
|
||||||
|
let opt_active_positions = self.client.active_positions(&self.pair).await?;
|
||||||
|
self.current_tick = tick;
|
||||||
|
|
||||||
|
// we assume there is only ONE active position per pair
|
||||||
|
match opt_active_positions {
|
||||||
|
// no open positions, no events and no messages returned
|
||||||
|
None => return Ok((None, None)),
|
||||||
|
|
||||||
|
Some(positions) => {
|
||||||
|
// checking if there are positions open for our pair
|
||||||
|
match positions.into_iter().find(|x| x.pair() == &self.pair) {
|
||||||
|
// no open positions for our pair, setting active position to none
|
||||||
|
None => {
|
||||||
|
self.active_position = None;
|
||||||
|
return Ok((None, None));
|
||||||
|
}
|
||||||
|
|
||||||
|
// applying strategy to open position and saving into struct
|
||||||
|
Some(position) => {
|
||||||
|
let mut events = None;
|
||||||
|
let mut messages = None;
|
||||||
|
|
||||||
|
let (pos_on_tick, events_on_tick, messages_on_tick) = self
|
||||||
|
.strategy
|
||||||
|
.on_tick(position, self.current_tick(), &self.positions_history);
|
||||||
|
|
||||||
|
let (pos_post_tick, events_post_tick, messages_post_tick) = self
|
||||||
|
.strategy
|
||||||
|
.post_tick(pos_on_tick, self.current_tick(), &self.positions_history);
|
||||||
|
|
||||||
|
events.merge(events_on_tick);
|
||||||
|
events.merge(events_post_tick);
|
||||||
|
|
||||||
|
messages.merge(messages_on_tick);
|
||||||
|
messages.merge(messages_post_tick);
|
||||||
|
|
||||||
|
self.positions_history
|
||||||
|
.insert(self.current_tick(), pos_post_tick.clone());
|
||||||
|
self.active_position = Some(pos_post_tick);
|
||||||
|
|
||||||
|
return Ok((events, messages));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn position_previous_tick(&self, id: u64, tick: Option<u64>) -> Option<&Position> {
|
||||||
|
let tick = match tick {
|
||||||
|
Some(tick) => {
|
||||||
|
if tick < 1 {
|
||||||
|
1
|
||||||
|
} else {
|
||||||
|
tick
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => self.current_tick() - 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
self.positions_history.get(&tick).filter(|x| x.id() == id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/******************
|
||||||
|
* ORDERS
|
||||||
|
******************/
|
||||||
|
|
||||||
|
// Position ID: Order ID
|
||||||
|
pub type TrackedPositionsMap = HashMap<u64, Vec<u64>>;
|
||||||
|
|
||||||
|
pub struct OrderManagerHandle {
|
||||||
|
sender: Sender<ActorMessage>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OrderManagerHandle {
|
||||||
|
const SLEEP_DURATION: u64 = 5;
|
||||||
|
|
||||||
|
async fn run_order_manager(mut manager: OrderManager) {
|
||||||
|
let mut sleep =
|
||||||
|
tokio::time::interval(Duration::from_secs(OrderManagerHandle::SLEEP_DURATION));
|
||||||
|
|
||||||
|
loop {
|
||||||
|
tokio::select! {
|
||||||
|
opt_msg = manager.receiver.recv() => {
|
||||||
|
if let Some(msg) = opt_msg {
|
||||||
|
manager.handle_message(msg).await.unwrap()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
_ = sleep.tick() => {
|
||||||
|
manager.update().await.unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new(pair: SymbolPair, client: Client, strategy: Box<dyn OrderStrategy>) -> Self {
|
||||||
|
let (sender, receiver) = channel(1);
|
||||||
|
|
||||||
|
let manager = OrderManager::new(receiver, pair, client, strategy);
|
||||||
|
|
||||||
|
tokio::spawn(OrderManagerHandle::run_order_manager(manager));
|
||||||
|
|
||||||
|
Self { sender }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn close_position(&mut self, position_id: u64) -> Result<OptionUpdate, BoxError> {
|
||||||
|
let (send, recv) = oneshot::channel();
|
||||||
|
|
||||||
|
self.sender
|
||||||
|
.send(ActorMessage {
|
||||||
|
message: ActionMessage::ClosePosition { position_id },
|
||||||
|
respond_to: send,
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(recv.await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn close_position_orders(
|
||||||
|
&mut self,
|
||||||
|
position_id: u64,
|
||||||
|
) -> Result<OptionUpdate, BoxError> {
|
||||||
|
let (send, recv) = oneshot::channel();
|
||||||
|
|
||||||
|
self.sender
|
||||||
|
.send(ActorMessage {
|
||||||
|
message: ActionMessage::ClosePositionOrders { position_id },
|
||||||
|
respond_to: send,
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(recv.await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn submit_order(&mut self, order_form: OrderForm) -> Result<OptionUpdate, BoxError> {
|
||||||
|
let (send, recv) = oneshot::channel();
|
||||||
|
|
||||||
|
self.sender
|
||||||
|
.send(ActorMessage {
|
||||||
|
message: ActionMessage::SubmitOrder { order: order_form },
|
||||||
|
respond_to: send,
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(recv.await?)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct OrderManager {
|
||||||
|
receiver: Receiver<ActorMessage>,
|
||||||
|
tracked_positions: TrackedPositionsMap,
|
||||||
|
pair: SymbolPair,
|
||||||
|
open_orders: Vec<ActiveOrder>,
|
||||||
|
client: Client,
|
||||||
|
strategy: Box<dyn OrderStrategy>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OrderManager {
|
||||||
|
pub fn new(
|
||||||
|
receiver: Receiver<ActorMessage>,
|
||||||
|
pair: SymbolPair,
|
||||||
|
client: Client,
|
||||||
|
strategy: Box<dyn OrderStrategy>,
|
||||||
|
) -> Self {
|
||||||
|
OrderManager {
|
||||||
|
receiver,
|
||||||
|
pair,
|
||||||
|
open_orders: Vec::new(),
|
||||||
|
client,
|
||||||
|
strategy,
|
||||||
|
tracked_positions: HashMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn handle_message(&mut self, msg: ActorMessage) -> Result<(), BoxError> {
|
||||||
|
let (events, messages) = match msg.message {
|
||||||
|
ActionMessage::Update { .. } => self.update().await?,
|
||||||
|
ActionMessage::ClosePosition { position_id } => {
|
||||||
|
self.close_position(position_id).await?
|
||||||
|
}
|
||||||
|
ActionMessage::ClosePositionOrders { position_id } => {
|
||||||
|
self.close_position_orders(position_id).await?
|
||||||
|
}
|
||||||
|
ActionMessage::SubmitOrder { order } => self.submit_order(&order).await?,
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(msg
|
||||||
|
.respond_to
|
||||||
|
.send((events, messages))
|
||||||
|
.map_err(|_| BoxError::from("Could not send message."))?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn close_position_orders(&self, position_id: u64) -> Result<OptionUpdate, BoxError> {
|
||||||
|
info!("Closing outstanding orders for position #{}", position_id);
|
||||||
|
|
||||||
|
if let Some(position_orders) = self.tracked_positions.get(&position_id) {
|
||||||
|
// retrieving open orders
|
||||||
|
let open_orders = self.client.active_orders(&self.pair).await?;
|
||||||
|
let position_orders: Vec<_> = position_orders
|
||||||
|
.iter()
|
||||||
|
.filter_map(|&x| open_orders.iter().find(|y| y.id() == x))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
for order in position_orders {
|
||||||
|
match self.client.cancel_order(order).await {
|
||||||
|
Ok(_) => info!("Order #{} closed successfully.", order.id()),
|
||||||
|
Err(e) => error!("Could not close order #{}: {}", order.id(), e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: return valid messages and events!
|
||||||
|
Ok((None, None))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn submit_order(&mut self, order_form: &OrderForm) -> Result<OptionUpdate, BoxError> {
|
||||||
|
info!("Submiting {}", order_form.kind());
|
||||||
|
|
||||||
|
let active_order = self.client.submit_order(order_form).await?;
|
||||||
|
|
||||||
|
debug!("Adding order to tracked orders.");
|
||||||
|
if let Some(metadata) = order_form.metadata() {
|
||||||
|
if let Some(position_id) = metadata.position_id() {
|
||||||
|
match self.tracked_positions.get_mut(&position_id) {
|
||||||
|
None => {
|
||||||
|
self.tracked_positions
|
||||||
|
.insert(position_id, vec![active_order.id()]);
|
||||||
|
}
|
||||||
|
Some(position_orders) => {
|
||||||
|
position_orders.push(active_order.id());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// TODO: return valid messages and events!111!!!1!
|
||||||
|
Ok((None, None))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn close_position(&mut self, position_id: u64) -> Result<OptionUpdate, BoxError> {
|
||||||
|
info!("Closing position #{}", position_id);
|
||||||
|
|
||||||
|
debug!("Retrieving open orders, positions and current prices...");
|
||||||
|
let (res_open_orders, res_order_book, res_open_positions) = tokio::join!(
|
||||||
|
self.client.active_orders(&self.pair),
|
||||||
|
self.client.order_book(&self.pair),
|
||||||
|
self.client.active_positions(&self.pair)
|
||||||
|
);
|
||||||
|
|
||||||
|
let (open_orders, order_book, open_positions) =
|
||||||
|
(res_open_orders?, res_order_book?, res_open_positions?);
|
||||||
|
|
||||||
|
// if there are open positions
|
||||||
|
if let Some(open_positions) = open_positions {
|
||||||
|
// if we find an open position with the ID we are looking for
|
||||||
|
if let Some(position) = open_positions.into_iter().find(|x| x.id() == position_id) {
|
||||||
|
let opt_position_order = open_orders
|
||||||
|
.iter()
|
||||||
|
// avoid using direct equality, using error margin instead
|
||||||
|
.find(|x| {
|
||||||
|
(x.order_form().amount().neg() - position.amount()).abs() < 0.0000001
|
||||||
|
});
|
||||||
|
|
||||||
|
// checking if the position has an open order.
|
||||||
|
// If so, don't do anything since the order is taken care of
|
||||||
|
// in the update phase.
|
||||||
|
// If no order is open, send an undercut limit order at the best current price.
|
||||||
|
if opt_position_order.is_none() {
|
||||||
|
// No open order, undercutting best price with limit order
|
||||||
|
let closing_price = self.best_closing_price(&position, &order_book);
|
||||||
|
|
||||||
|
let order_form = OrderForm::new(
|
||||||
|
self.pair.clone(),
|
||||||
|
OrderKind::Limit {
|
||||||
|
price: closing_price,
|
||||||
|
},
|
||||||
|
position.platform(),
|
||||||
|
position.amount().neg(),
|
||||||
|
)
|
||||||
|
.with_leverage(Some(position.leverage()));
|
||||||
|
|
||||||
|
info!("Submitting {} order", order_form.kind());
|
||||||
|
if let Err(e) = self.client.submit_order(&order_form).await {
|
||||||
|
error!(
|
||||||
|
"Could not submit {} to close position #{}: {}",
|
||||||
|
order_form.kind(),
|
||||||
|
position.id(),
|
||||||
|
e
|
||||||
|
);
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok((None, None))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn update(&mut self) -> Result<OptionUpdate, BoxError> {
|
||||||
|
debug!("\t[OrderManager] Updating {}", self.pair);
|
||||||
|
|
||||||
|
let (res_open_orders, res_order_book) = tokio::join!(
|
||||||
|
self.client.active_orders(&self.pair),
|
||||||
|
self.client.order_book(&self.pair)
|
||||||
|
);
|
||||||
|
|
||||||
|
let (open_orders, order_book) = (res_open_orders?, res_order_book?);
|
||||||
|
|
||||||
|
// retrieving open positions to check whether the positions have open orders.
|
||||||
|
// we need to update our internal mapping in that case.
|
||||||
|
if !open_orders.is_empty() {
|
||||||
|
let open_positions = self.client.active_positions(&self.pair).await?;
|
||||||
|
|
||||||
|
if let Some(positions) = open_positions {
|
||||||
|
// currently, we are only trying to match orders with an amount equal to
|
||||||
|
// a position amount.
|
||||||
|
for position in positions {
|
||||||
|
let matching_order = open_orders
|
||||||
|
.iter()
|
||||||
|
.find(|x| x.order_form().amount().abs() == position.amount().abs());
|
||||||
|
|
||||||
|
// if an order is found, we insert the order to our internal mapping, if not already present
|
||||||
|
if let Some(matching_order) = matching_order {
|
||||||
|
match self.tracked_positions.get_mut(&position.id()) {
|
||||||
|
Some(position_orders) => {
|
||||||
|
if !position_orders.contains(&matching_order.id()) {
|
||||||
|
trace!(
|
||||||
|
"Mapped order #{} to position #{}",
|
||||||
|
position.id(),
|
||||||
|
matching_order.id()
|
||||||
|
);
|
||||||
|
position_orders.push(matching_order.id());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
trace!(
|
||||||
|
"Mapped order #{} to position #{}",
|
||||||
|
position.id(),
|
||||||
|
matching_order.id()
|
||||||
|
);
|
||||||
|
self.tracked_positions
|
||||||
|
.insert(position.id(), vec![matching_order.id()]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for active_order in open_orders {
|
||||||
|
trace!(
|
||||||
|
"Found open order, calling \"{}\" strategy.",
|
||||||
|
self.strategy.name()
|
||||||
|
);
|
||||||
|
|
||||||
|
let (_, strat_messages) = self.strategy.on_open_order(&active_order, &order_book)?;
|
||||||
|
|
||||||
|
if let Some(messages) = strat_messages {
|
||||||
|
for m in messages {
|
||||||
|
match m {
|
||||||
|
ActionMessage::SubmitOrder { order: order_form } => {
|
||||||
|
info!("Closing open order...");
|
||||||
|
info!("\tCancelling open order #{}", &active_order.id());
|
||||||
|
self.client.cancel_order(&active_order).await?;
|
||||||
|
|
||||||
|
info!("\tSubmitting {}...", order_form.kind());
|
||||||
|
self.client.submit_order(&order_form).await?;
|
||||||
|
info!("Done!");
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
debug!(
|
||||||
|
"Received unsupported message from order strategy. Unimplemented."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok((None, None))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn best_closing_price(&self, position: &Position, order_book: &OrderBook) -> f64 {
|
||||||
|
let ask = order_book.lowest_ask();
|
||||||
|
let bid = order_book.highest_bid();
|
||||||
|
let avg = (bid + ask) / 2.0;
|
||||||
|
let delta = (ask - bid) / 10.0;
|
||||||
|
|
||||||
|
let closing_price = {
|
||||||
|
if position.is_short() {
|
||||||
|
bid - delta
|
||||||
|
} else {
|
||||||
|
ask + delta
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if avg > 9999.0 {
|
||||||
|
if position.is_short() {
|
||||||
|
closing_price.ceil()
|
||||||
|
} else {
|
||||||
|
closing_price.floor()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
closing_price
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct PairManager {
|
||||||
|
pair: SymbolPair,
|
||||||
|
price_manager: PriceManagerHandle,
|
||||||
|
order_manager: OrderManagerHandle,
|
||||||
|
position_manager: PositionManagerHandle,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PairManager {
|
||||||
|
pub fn new(pair: SymbolPair, client: Client) -> Self {
|
||||||
|
Self {
|
||||||
|
pair: pair.clone(),
|
||||||
|
price_manager: PriceManagerHandle::new(pair.clone(), client.clone()),
|
||||||
|
order_manager: OrderManagerHandle::new(
|
||||||
|
pair.clone(),
|
||||||
|
client.clone(),
|
||||||
|
Box::new(MarketEnforce::default()),
|
||||||
|
),
|
||||||
|
position_manager: PositionManagerHandle::new(
|
||||||
|
pair,
|
||||||
|
client,
|
||||||
|
Box::new(HiddenTrailingStop::default()),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn update_managers(&mut self, tick: u64) -> Result<(), BoxError> {
|
||||||
|
let mut events = None;
|
||||||
|
let mut messages = None;
|
||||||
|
|
||||||
|
let (price_results, pos_results) = tokio::join!(
|
||||||
|
self.price_manager.update(tick),
|
||||||
|
self.position_manager.update(tick),
|
||||||
|
);
|
||||||
|
|
||||||
|
let (opt_price_events, opt_price_messages) = price_results?;
|
||||||
|
let (opt_pos_events, opt_pos_messages) = pos_results?;
|
||||||
|
|
||||||
|
events.merge(opt_price_events);
|
||||||
|
events.merge(opt_pos_events);
|
||||||
|
|
||||||
|
messages.merge(opt_price_messages);
|
||||||
|
messages.merge(opt_pos_messages);
|
||||||
|
|
||||||
|
// TODO: to move into Handler?
|
||||||
|
if let Some(messages) = messages {
|
||||||
|
for m in messages {
|
||||||
|
match m {
|
||||||
|
ActionMessage::Update { .. } => {}
|
||||||
|
ActionMessage::ClosePosition { position_id } => {
|
||||||
|
self.order_manager.close_position(position_id).await?;
|
||||||
|
}
|
||||||
|
ActionMessage::SubmitOrder { order } => {
|
||||||
|
self.order_manager.submit_order(order).await?;
|
||||||
|
}
|
||||||
|
ActionMessage::ClosePositionOrders { position_id } => {
|
||||||
|
self.order_manager
|
||||||
|
.close_position_orders(position_id)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ExchangeManager {
|
||||||
|
kind: ExchangeDetails,
|
||||||
|
pair_managers: Vec<PairManager>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ExchangeManager {
|
||||||
|
pub fn new(kind: &ExchangeDetails, pairs: &[SymbolPair]) -> Self {
|
||||||
|
let client = Client::new(kind);
|
||||||
|
let pair_managers = pairs
|
||||||
|
.iter()
|
||||||
|
.map(|x| PairManager::new(x.clone(), client.clone()))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
Self {
|
||||||
|
kind: kind.clone(),
|
||||||
|
pair_managers,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn update_managers(&mut self, tick: u64) -> Result<(), BoxError> {
|
||||||
|
let mut futures: FuturesUnordered<_> = self
|
||||||
|
.pair_managers
|
||||||
|
.iter_mut()
|
||||||
|
.map(|x| x.update_managers(tick))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
// execute the futures
|
||||||
|
while futures.next().await.is_some() {}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
605
rustybot/src/models.rs
Normal file
605
rustybot/src/models.rs
Normal file
@ -0,0 +1,605 @@
|
|||||||
|
use std::fmt;
|
||||||
|
use std::fmt::{Display, Formatter};
|
||||||
|
use std::hash::{Hash, Hasher};
|
||||||
|
|
||||||
|
use crate::connectors::Exchange;
|
||||||
|
use crate::currency::{Symbol, SymbolPair};
|
||||||
|
|
||||||
|
/***************
|
||||||
|
* Prices
|
||||||
|
***************/
|
||||||
|
|
||||||
|
#[derive(Copy, Clone, Debug)]
|
||||||
|
pub struct PriceTicker {
|
||||||
|
pub bid: f64,
|
||||||
|
pub bid_size: f64,
|
||||||
|
pub ask: f64,
|
||||||
|
pub ask_size: f64,
|
||||||
|
pub daily_change: f64,
|
||||||
|
pub daily_change_perc: f64,
|
||||||
|
pub last_price: f64,
|
||||||
|
pub volume: f64,
|
||||||
|
pub high: f64,
|
||||||
|
pub low: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/***************
|
||||||
|
* Orders
|
||||||
|
***************/
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum OrderBookEntry {
|
||||||
|
Trading {
|
||||||
|
price: f64,
|
||||||
|
count: u64,
|
||||||
|
amount: f64,
|
||||||
|
},
|
||||||
|
Funding {
|
||||||
|
rate: f64,
|
||||||
|
period: u64,
|
||||||
|
count: u64,
|
||||||
|
amount: f64,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct OrderBook {
|
||||||
|
pair: SymbolPair,
|
||||||
|
entries: Vec<OrderBookEntry>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OrderBook {
|
||||||
|
pub fn new(pair: SymbolPair) -> Self {
|
||||||
|
OrderBook {
|
||||||
|
pair,
|
||||||
|
entries: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_entries(mut self, entries: Vec<OrderBookEntry>) -> Self {
|
||||||
|
self.entries = entries;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: distinguish between trading and funding
|
||||||
|
pub fn bids(&self) -> Vec<&OrderBookEntry> {
|
||||||
|
self.entries
|
||||||
|
.iter()
|
||||||
|
.filter(|x| match x {
|
||||||
|
OrderBookEntry::Trading { amount, .. } => amount > &0.0,
|
||||||
|
OrderBookEntry::Funding { amount, .. } => amount < &0.0,
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: distinguish between trading and funding
|
||||||
|
pub fn asks(&self) -> Vec<&OrderBookEntry> {
|
||||||
|
self.entries
|
||||||
|
.iter()
|
||||||
|
.filter(|x| match x {
|
||||||
|
OrderBookEntry::Trading { amount, .. } => amount < &0.0,
|
||||||
|
OrderBookEntry::Funding { amount, .. } => amount > &0.0,
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn highest_bid(&self) -> f64 {
|
||||||
|
self.bids()
|
||||||
|
.iter()
|
||||||
|
.map(|x| match x {
|
||||||
|
OrderBookEntry::Trading { price, .. } => price,
|
||||||
|
OrderBookEntry::Funding { rate, .. } => rate,
|
||||||
|
})
|
||||||
|
.fold(f64::NEG_INFINITY, |a, &b| a.max(b))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn lowest_ask(&self) -> f64 {
|
||||||
|
self.asks()
|
||||||
|
.iter()
|
||||||
|
.map(|x| match x {
|
||||||
|
OrderBookEntry::Trading { price, .. } => price,
|
||||||
|
OrderBookEntry::Funding { rate, .. } => rate,
|
||||||
|
})
|
||||||
|
.fold(f64::INFINITY, |a, &b| a.min(b))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum OrderFee {
|
||||||
|
Maker(f64),
|
||||||
|
Taker(f64),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct OrderDetails {
|
||||||
|
exchange: Exchange,
|
||||||
|
pair: SymbolPair,
|
||||||
|
platform: TradingPlatform,
|
||||||
|
kind: OrderKind,
|
||||||
|
execution_timestamp: u64,
|
||||||
|
id: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OrderDetails {
|
||||||
|
pub fn new(
|
||||||
|
exchange: Exchange,
|
||||||
|
id: u64,
|
||||||
|
pair: SymbolPair,
|
||||||
|
platform: TradingPlatform,
|
||||||
|
kind: OrderKind,
|
||||||
|
execution_timestamp: u64,
|
||||||
|
) -> Self {
|
||||||
|
OrderDetails {
|
||||||
|
exchange,
|
||||||
|
pair,
|
||||||
|
platform,
|
||||||
|
kind,
|
||||||
|
execution_timestamp,
|
||||||
|
id,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn id(&self) -> u64 {
|
||||||
|
self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn pair(&self) -> &SymbolPair {
|
||||||
|
&self.pair
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct ActiveOrder {
|
||||||
|
exchange: Exchange,
|
||||||
|
id: u64,
|
||||||
|
group_id: Option<u64>,
|
||||||
|
client_id: Option<u64>,
|
||||||
|
pair: SymbolPair,
|
||||||
|
order_form: OrderForm,
|
||||||
|
creation_timestamp: u64,
|
||||||
|
update_timestamp: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActiveOrder {
|
||||||
|
pub fn new(
|
||||||
|
exchange: Exchange,
|
||||||
|
id: u64,
|
||||||
|
pair: SymbolPair,
|
||||||
|
order_form: OrderForm,
|
||||||
|
creation_timestamp: u64,
|
||||||
|
update_timestamp: u64,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
exchange,
|
||||||
|
id,
|
||||||
|
group_id: None,
|
||||||
|
client_id: None,
|
||||||
|
pair,
|
||||||
|
order_form,
|
||||||
|
creation_timestamp,
|
||||||
|
update_timestamp,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_group_id(mut self, group_id: Option<u64>) -> Self {
|
||||||
|
self.group_id = group_id;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_client_id(mut self, client_id: Option<u64>) -> Self {
|
||||||
|
self.client_id = client_id;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn exchange(&self) -> Exchange {
|
||||||
|
self.exchange
|
||||||
|
}
|
||||||
|
pub fn id(&self) -> u64 {
|
||||||
|
self.id
|
||||||
|
}
|
||||||
|
pub fn group_id(&self) -> Option<u64> {
|
||||||
|
self.group_id
|
||||||
|
}
|
||||||
|
pub fn client_id(&self) -> Option<u64> {
|
||||||
|
self.client_id
|
||||||
|
}
|
||||||
|
pub fn pair(&self) -> &SymbolPair {
|
||||||
|
&self.pair
|
||||||
|
}
|
||||||
|
pub fn order_form(&self) -> &OrderForm {
|
||||||
|
&self.order_form
|
||||||
|
}
|
||||||
|
pub fn creation_timestamp(&self) -> u64 {
|
||||||
|
self.creation_timestamp
|
||||||
|
}
|
||||||
|
pub fn update_timestamp(&self) -> u64 {
|
||||||
|
self.update_timestamp
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Hash for ActiveOrder {
|
||||||
|
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||||
|
state.write(&self.id.to_le_bytes());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialEq for ActiveOrder {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
self.id == other.id && self.client_id == other.client_id && self.group_id == other.group_id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Eq for ActiveOrder {}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
|
||||||
|
pub enum TradingPlatform {
|
||||||
|
Exchange,
|
||||||
|
Derivative,
|
||||||
|
Funding,
|
||||||
|
Margin,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TradingPlatform {
|
||||||
|
pub fn as_str(&self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
TradingPlatform::Exchange => "Exchange",
|
||||||
|
TradingPlatform::Derivative => "Derivative",
|
||||||
|
TradingPlatform::Funding => "Funding",
|
||||||
|
TradingPlatform::Margin => "Margin",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for TradingPlatform {
|
||||||
|
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(f, "{}", self.as_str())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Copy, Clone, Debug)]
|
||||||
|
pub enum OrderKind {
|
||||||
|
Limit { price: f64 },
|
||||||
|
Market,
|
||||||
|
Stop { price: f64 },
|
||||||
|
StopLimit { price: f64, limit_price: f64 },
|
||||||
|
TrailingStop { distance: f64 },
|
||||||
|
FillOrKill { price: f64 },
|
||||||
|
ImmediateOrCancel { price: f64 },
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OrderKind {
|
||||||
|
pub fn as_str(&self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
OrderKind::Limit { .. } => "Limit",
|
||||||
|
OrderKind::Market { .. } => "Market",
|
||||||
|
OrderKind::Stop { .. } => "Stop",
|
||||||
|
OrderKind::StopLimit { .. } => "Stop Limit",
|
||||||
|
OrderKind::TrailingStop { .. } => "Trailing Stop",
|
||||||
|
OrderKind::FillOrKill { .. } => "Fill or Kill",
|
||||||
|
OrderKind::ImmediateOrCancel { .. } => "Immediate or Cancel",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for OrderKind {
|
||||||
|
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
OrderKind::Limit { price } => {
|
||||||
|
write!(f, "[{} | Price: {:0.5}]", self.as_str(), price,)
|
||||||
|
}
|
||||||
|
OrderKind::Market => {
|
||||||
|
write!(f, "[{}]", self.as_str())
|
||||||
|
}
|
||||||
|
OrderKind::Stop { price } => {
|
||||||
|
write!(f, "[{} | Price: {:0.5}", self.as_str(), price,)
|
||||||
|
}
|
||||||
|
OrderKind::StopLimit { price, limit_price } => {
|
||||||
|
write!(
|
||||||
|
f,
|
||||||
|
"[{} | Price: {:0.5}, Limit Price: {:0.5}]",
|
||||||
|
self.as_str(),
|
||||||
|
price,
|
||||||
|
limit_price
|
||||||
|
)
|
||||||
|
}
|
||||||
|
OrderKind::TrailingStop { distance } => {
|
||||||
|
write!(f, "[{} | Distance: {:0.5}]", self.as_str(), distance,)
|
||||||
|
}
|
||||||
|
OrderKind::FillOrKill { price } => {
|
||||||
|
write!(f, "[{} | Price: {:0.5}]", self.as_str(), price,)
|
||||||
|
}
|
||||||
|
OrderKind::ImmediateOrCancel { price } => {
|
||||||
|
write!(f, "[{} | Price: {:0.5}]", self.as_str(), price,)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct OrderForm {
|
||||||
|
pair: SymbolPair,
|
||||||
|
kind: OrderKind,
|
||||||
|
platform: TradingPlatform,
|
||||||
|
amount: f64,
|
||||||
|
leverage: Option<f64>,
|
||||||
|
metadata: Option<OrderMetadata>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OrderForm {
|
||||||
|
pub fn new(
|
||||||
|
pair: SymbolPair,
|
||||||
|
order_kind: OrderKind,
|
||||||
|
platform: TradingPlatform,
|
||||||
|
amount: f64,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
pair,
|
||||||
|
kind: order_kind,
|
||||||
|
platform,
|
||||||
|
amount,
|
||||||
|
leverage: None,
|
||||||
|
metadata: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_leverage(mut self, leverage: Option<f64>) -> Self {
|
||||||
|
self.leverage = leverage;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_metadata(mut self, metadata: Option<OrderMetadata>) -> Self {
|
||||||
|
self.metadata = metadata;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn pair(&self) -> &SymbolPair {
|
||||||
|
&self.pair
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn kind(&self) -> OrderKind {
|
||||||
|
self.kind
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn platform(&self) -> &TradingPlatform {
|
||||||
|
&self.platform
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn amount(&self) -> f64 {
|
||||||
|
self.amount
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn price(&self) -> Option<f64> {
|
||||||
|
match self.kind {
|
||||||
|
OrderKind::Limit { price, .. } => Some(price),
|
||||||
|
OrderKind::Market { .. } => None,
|
||||||
|
OrderKind::Stop { price, .. } => Some(price),
|
||||||
|
OrderKind::StopLimit { price, .. } => Some(price),
|
||||||
|
OrderKind::TrailingStop { .. } => None,
|
||||||
|
OrderKind::FillOrKill { price, .. } => Some(price),
|
||||||
|
OrderKind::ImmediateOrCancel { price, .. } => Some(price),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn leverage(&self) -> Option<f64> {
|
||||||
|
self.leverage
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn metadata(&self) -> &Option<OrderMetadata> {
|
||||||
|
&self.metadata
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct OrderMetadata {
|
||||||
|
position_id: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OrderMetadata {
|
||||||
|
pub fn with_position_id(position_id: u64) -> Self {
|
||||||
|
OrderMetadata {
|
||||||
|
position_id: Some(position_id),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn position_id(&self) -> Option<u64> {
|
||||||
|
self.position_id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/***************
|
||||||
|
* Positions
|
||||||
|
***************/
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Position {
|
||||||
|
pair: SymbolPair,
|
||||||
|
state: PositionState,
|
||||||
|
profit_state: Option<PositionProfitState>,
|
||||||
|
amount: f64,
|
||||||
|
base_price: f64,
|
||||||
|
pl: f64,
|
||||||
|
pl_perc: f64,
|
||||||
|
price_liq: f64,
|
||||||
|
position_id: u64,
|
||||||
|
creation_date: Option<u64>,
|
||||||
|
creation_update: Option<u64>,
|
||||||
|
platform: TradingPlatform,
|
||||||
|
leverage: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Position {
|
||||||
|
pub fn new(
|
||||||
|
pair: SymbolPair,
|
||||||
|
state: PositionState,
|
||||||
|
amount: f64,
|
||||||
|
base_price: f64,
|
||||||
|
pl: f64,
|
||||||
|
pl_perc: f64,
|
||||||
|
price_liq: f64,
|
||||||
|
position_id: u64,
|
||||||
|
platform: TradingPlatform,
|
||||||
|
leverage: f64,
|
||||||
|
) -> Self {
|
||||||
|
Position {
|
||||||
|
pair,
|
||||||
|
state,
|
||||||
|
amount,
|
||||||
|
base_price,
|
||||||
|
pl,
|
||||||
|
pl_perc,
|
||||||
|
price_liq,
|
||||||
|
position_id,
|
||||||
|
creation_date: None,
|
||||||
|
creation_update: None,
|
||||||
|
profit_state: None,
|
||||||
|
platform,
|
||||||
|
leverage,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_creation_date(mut self, creation_date: Option<u64>) -> Self {
|
||||||
|
self.creation_date = creation_date;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_creation_update(mut self, creation_update: Option<u64>) -> Self {
|
||||||
|
self.creation_update = creation_update;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_profit_state(mut self, profit_state: Option<PositionProfitState>) -> Self {
|
||||||
|
self.profit_state = profit_state;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update_profit_loss(&mut self, best_offer: f64, fee_perc: f64) {
|
||||||
|
let (base_price, delta) = {
|
||||||
|
if self.is_short() {
|
||||||
|
let base_price = self.base_price * (1.0 - fee_perc / 100.0);
|
||||||
|
let delta = base_price - best_offer;
|
||||||
|
|
||||||
|
(base_price, delta)
|
||||||
|
} else {
|
||||||
|
let base_price = self.base_price * (1.0 + fee_perc / 100.0);
|
||||||
|
let delta = best_offer - base_price;
|
||||||
|
|
||||||
|
(base_price, delta)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let profit_loss = delta * self.amount.abs();
|
||||||
|
let profit_loss_percentage = delta / base_price * 100.0;
|
||||||
|
|
||||||
|
self.pl = profit_loss;
|
||||||
|
self.pl_perc = profit_loss_percentage;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_profit_loss(mut self, profit_loss: f64) -> Self {
|
||||||
|
self.pl = profit_loss;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn pair(&self) -> &SymbolPair {
|
||||||
|
&self.pair
|
||||||
|
}
|
||||||
|
pub fn state(&self) -> PositionState {
|
||||||
|
self.state
|
||||||
|
}
|
||||||
|
pub fn amount(&self) -> f64 {
|
||||||
|
self.amount
|
||||||
|
}
|
||||||
|
pub fn base_price(&self) -> f64 {
|
||||||
|
self.base_price
|
||||||
|
}
|
||||||
|
pub fn pl(&self) -> f64 {
|
||||||
|
self.pl
|
||||||
|
}
|
||||||
|
pub fn pl_perc(&self) -> f64 {
|
||||||
|
self.pl_perc
|
||||||
|
}
|
||||||
|
pub fn price_liq(&self) -> f64 {
|
||||||
|
self.price_liq
|
||||||
|
}
|
||||||
|
pub fn id(&self) -> u64 {
|
||||||
|
self.position_id
|
||||||
|
}
|
||||||
|
pub fn profit_state(&self) -> Option<PositionProfitState> {
|
||||||
|
self.profit_state
|
||||||
|
}
|
||||||
|
pub fn creation_date(&self) -> Option<u64> {
|
||||||
|
self.creation_date
|
||||||
|
}
|
||||||
|
pub fn creation_update(&self) -> Option<u64> {
|
||||||
|
self.creation_update
|
||||||
|
}
|
||||||
|
pub fn is_short(&self) -> bool {
|
||||||
|
self.amount.is_sign_negative()
|
||||||
|
}
|
||||||
|
pub fn is_long(&self) -> bool {
|
||||||
|
self.amount.is_sign_positive()
|
||||||
|
}
|
||||||
|
pub fn platform(&self) -> TradingPlatform {
|
||||||
|
self.platform
|
||||||
|
}
|
||||||
|
pub fn leverage(&self) -> f64 {
|
||||||
|
self.leverage
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Hash for Position {
|
||||||
|
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||||
|
state.write(&self.id().to_le_bytes())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialEq for Position {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
self.id() == other.id()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Eq for Position {}
|
||||||
|
|
||||||
|
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
|
||||||
|
pub enum PositionProfitState {
|
||||||
|
Critical,
|
||||||
|
Loss,
|
||||||
|
BreakEven,
|
||||||
|
MinimumProfit,
|
||||||
|
Profit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
|
||||||
|
pub enum PositionState {
|
||||||
|
Closed,
|
||||||
|
Open,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub enum WalletKind {
|
||||||
|
Exchange,
|
||||||
|
Margin,
|
||||||
|
Funding,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Trade {
|
||||||
|
pub trade_id: u64,
|
||||||
|
pub pair: SymbolPair,
|
||||||
|
pub execution_timestamp: u64,
|
||||||
|
pub price: f64,
|
||||||
|
pub amount: f64,
|
||||||
|
pub fee: OrderFee,
|
||||||
|
pub fee_currency: Symbol,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum TradingFees {
|
||||||
|
Maker {
|
||||||
|
platform: TradingPlatform,
|
||||||
|
percentage: f64,
|
||||||
|
},
|
||||||
|
Taker {
|
||||||
|
platform: TradingPlatform,
|
||||||
|
percentage: f64,
|
||||||
|
},
|
||||||
|
}
|
587
rustybot/src/strategy.rs
Normal file
587
rustybot/src/strategy.rs
Normal file
@ -0,0 +1,587 @@
|
|||||||
|
use std::collections::HashMap;
|
||||||
|
use std::fmt::{Debug, Formatter};
|
||||||
|
|
||||||
|
use dyn_clone::DynClone;
|
||||||
|
use log::info;
|
||||||
|
|
||||||
|
use crate::connectors::Connector;
|
||||||
|
use crate::events::{ActionMessage, Event, EventKind, EventMetadata};
|
||||||
|
use crate::managers::OptionUpdate;
|
||||||
|
use crate::models::{ActiveOrder, OrderBook, OrderForm, OrderKind, Position, PositionProfitState};
|
||||||
|
use crate::BoxError;
|
||||||
|
|
||||||
|
/***************
|
||||||
|
* DEFINITIONS
|
||||||
|
***************/
|
||||||
|
|
||||||
|
pub trait PositionStrategy: DynClone + Send + Sync {
|
||||||
|
fn name(&self) -> String;
|
||||||
|
fn on_tick(
|
||||||
|
&mut self,
|
||||||
|
position: Position,
|
||||||
|
current_tick: u64,
|
||||||
|
positions_history: &HashMap<u64, Position>,
|
||||||
|
) -> (Position, Option<Vec<Event>>, Option<Vec<ActionMessage>>);
|
||||||
|
fn post_tick(
|
||||||
|
&mut self,
|
||||||
|
position: Position,
|
||||||
|
current_tick: u64,
|
||||||
|
positions_history: &HashMap<u64, Position>,
|
||||||
|
) -> (Position, Option<Vec<Event>>, Option<Vec<ActionMessage>>);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Debug for dyn PositionStrategy {
|
||||||
|
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
|
||||||
|
write!(f, "{}", self.name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait OrderStrategy: DynClone + Send + Sync {
|
||||||
|
/// The name of the strategy, used for debugging purposes
|
||||||
|
fn name(&self) -> String;
|
||||||
|
/// This method is called when the OrderManager checks the open orders on a new tick.
|
||||||
|
/// It should manage if some orders have to be closed or keep open.
|
||||||
|
fn on_open_order(
|
||||||
|
&self,
|
||||||
|
order: &ActiveOrder,
|
||||||
|
order_book: &OrderBook,
|
||||||
|
) -> Result<OptionUpdate, BoxError>;
|
||||||
|
// /// This method is called when the OrderManager is requested to close
|
||||||
|
// /// a position that has an open order associated to it.
|
||||||
|
// fn on_position_order(
|
||||||
|
// &self,
|
||||||
|
// order: &ActiveOrder,
|
||||||
|
// open_position: &Position,
|
||||||
|
// order_book: &OrderBook,
|
||||||
|
// ) -> Result<OptionUpdate, BoxError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Debug for dyn OrderStrategy {
|
||||||
|
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
|
||||||
|
write!(f, "{}", self.name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/***************
|
||||||
|
* IMPLEMENTATIONS
|
||||||
|
***************/
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct HiddenTrailingStop {
|
||||||
|
stop_percentages: HashMap<u64, f64>,
|
||||||
|
capital_max_loss: f64,
|
||||||
|
capital_min_profit: f64,
|
||||||
|
capital_good_profit: f64,
|
||||||
|
min_profit_trailing_delta: f64,
|
||||||
|
good_profit_trailing_delta: f64,
|
||||||
|
leverage: f64,
|
||||||
|
min_profit_percentage: f64,
|
||||||
|
good_profit_percentage: f64,
|
||||||
|
max_loss_percentage: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HiddenTrailingStop {
|
||||||
|
fn update_stop_percentage(&mut self, position: &Position) {
|
||||||
|
if let Some(profit_state) = position.profit_state() {
|
||||||
|
let profit_state_delta = match profit_state {
|
||||||
|
PositionProfitState::MinimumProfit => Some(self.min_profit_trailing_delta),
|
||||||
|
PositionProfitState::Profit => Some(self.good_profit_trailing_delta),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(profit_state_delta) = profit_state_delta {
|
||||||
|
let current_stop_percentage = position.pl_perc() - profit_state_delta;
|
||||||
|
|
||||||
|
if let PositionProfitState::MinimumProfit | PositionProfitState::Profit =
|
||||||
|
profit_state
|
||||||
|
{
|
||||||
|
match self.stop_percentages.get(&position.id()) {
|
||||||
|
None => {
|
||||||
|
self.stop_percentages
|
||||||
|
.insert(position.id(), current_stop_percentage);
|
||||||
|
}
|
||||||
|
Some(existing_threshold) => {
|
||||||
|
if existing_threshold < ¤t_stop_percentage {
|
||||||
|
self.stop_percentages
|
||||||
|
.insert(position.id(), current_stop_percentage);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
info!(
|
||||||
|
"\tState: {:?} | PL: {:0.2}{} ({:0.2}%) | Stop: {:0.2}",
|
||||||
|
position.profit_state().unwrap(),
|
||||||
|
position.pl(),
|
||||||
|
position.pair().quote(),
|
||||||
|
position.pl_perc(),
|
||||||
|
self.stop_percentages.get(&position.id()).unwrap_or(&0.0)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for HiddenTrailingStop {
|
||||||
|
fn default() -> Self {
|
||||||
|
let leverage = 5.0;
|
||||||
|
|
||||||
|
// in percentage
|
||||||
|
let capital_max_loss = 15.0;
|
||||||
|
let capital_min_profit = 9.0;
|
||||||
|
let capital_good_profit = capital_min_profit * 2.0;
|
||||||
|
|
||||||
|
let weighted_min_profit = capital_min_profit / leverage;
|
||||||
|
let weighted_good_profit = capital_good_profit / leverage;
|
||||||
|
let weighted_max_loss = capital_max_loss / leverage;
|
||||||
|
|
||||||
|
let min_profit_trailing_delta = weighted_min_profit * 0.17;
|
||||||
|
let good_profit_trailing_delta = weighted_good_profit * 0.08;
|
||||||
|
|
||||||
|
let min_profit_percentage = weighted_min_profit + min_profit_trailing_delta;
|
||||||
|
let good_profit_percentage = weighted_good_profit + good_profit_trailing_delta;
|
||||||
|
let max_loss_percentage = -weighted_max_loss;
|
||||||
|
|
||||||
|
HiddenTrailingStop {
|
||||||
|
stop_percentages: Default::default(),
|
||||||
|
capital_max_loss,
|
||||||
|
capital_min_profit,
|
||||||
|
capital_good_profit,
|
||||||
|
min_profit_trailing_delta,
|
||||||
|
good_profit_trailing_delta,
|
||||||
|
leverage,
|
||||||
|
min_profit_percentage,
|
||||||
|
good_profit_percentage,
|
||||||
|
max_loss_percentage,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl PositionStrategy for HiddenTrailingStop {
|
||||||
|
fn name(&self) -> String {
|
||||||
|
"Hidden Trailing Stop".into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets the profit state of an open position
|
||||||
|
fn on_tick(
|
||||||
|
&mut self,
|
||||||
|
position: Position,
|
||||||
|
current_tick: u64,
|
||||||
|
positions_history: &HashMap<u64, Position>,
|
||||||
|
) -> (Position, Option<Vec<Event>>, Option<Vec<ActionMessage>>) {
|
||||||
|
let pl_perc = position.pl_perc();
|
||||||
|
|
||||||
|
let state = {
|
||||||
|
if pl_perc > self.good_profit_percentage {
|
||||||
|
PositionProfitState::Profit
|
||||||
|
} else if (self.min_profit_percentage..self.good_profit_percentage).contains(&pl_perc) {
|
||||||
|
PositionProfitState::MinimumProfit
|
||||||
|
} else if (0.0..self.min_profit_percentage).contains(&pl_perc) {
|
||||||
|
PositionProfitState::BreakEven
|
||||||
|
} else if (self.max_loss_percentage..0.0).contains(&pl_perc) {
|
||||||
|
PositionProfitState::Loss
|
||||||
|
} else {
|
||||||
|
PositionProfitState::Critical
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let opt_prev_position = positions_history.get(&(current_tick - 1));
|
||||||
|
let event_metadata = EventMetadata::new(Some(position.id()), None);
|
||||||
|
let new_position = position.with_profit_state(Some(state));
|
||||||
|
|
||||||
|
match opt_prev_position {
|
||||||
|
Some(prev) => {
|
||||||
|
if prev.profit_state() == Some(state) {
|
||||||
|
return (new_position, None, None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => return (new_position, None, None),
|
||||||
|
};
|
||||||
|
|
||||||
|
let events = {
|
||||||
|
let mut events = vec![];
|
||||||
|
|
||||||
|
if state == PositionProfitState::Profit {
|
||||||
|
events.push(Event::new(
|
||||||
|
EventKind::ReachedGoodProfit,
|
||||||
|
current_tick,
|
||||||
|
Some(event_metadata),
|
||||||
|
));
|
||||||
|
} else if state == PositionProfitState::MinimumProfit {
|
||||||
|
events.push(Event::new(
|
||||||
|
EventKind::ReachedMinProfit,
|
||||||
|
current_tick,
|
||||||
|
Some(event_metadata),
|
||||||
|
));
|
||||||
|
} else if state == PositionProfitState::BreakEven {
|
||||||
|
events.push(Event::new(
|
||||||
|
EventKind::ReachedBreakEven,
|
||||||
|
current_tick,
|
||||||
|
Some(event_metadata),
|
||||||
|
));
|
||||||
|
} else if state == PositionProfitState::Loss {
|
||||||
|
events.push(Event::new(
|
||||||
|
EventKind::ReachedLoss,
|
||||||
|
current_tick,
|
||||||
|
Some(event_metadata),
|
||||||
|
));
|
||||||
|
} else {
|
||||||
|
events.push(Event::new(
|
||||||
|
EventKind::ReachedMaxLoss,
|
||||||
|
current_tick,
|
||||||
|
Some(event_metadata),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
events
|
||||||
|
};
|
||||||
|
|
||||||
|
(new_position, Some(events), None)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn post_tick(
|
||||||
|
&mut self,
|
||||||
|
position: Position,
|
||||||
|
_: u64,
|
||||||
|
_: &HashMap<u64, Position>,
|
||||||
|
) -> (Position, Option<Vec<Event>>, Option<Vec<ActionMessage>>) {
|
||||||
|
let close_message = ActionMessage::ClosePosition {
|
||||||
|
position_id: position.id(),
|
||||||
|
};
|
||||||
|
|
||||||
|
// if critical, early return with close position
|
||||||
|
if let Some(PositionProfitState::Critical) = position.profit_state() {
|
||||||
|
info!("Maximum loss reached. Closing position.");
|
||||||
|
return (position, None, Some(vec![close_message]));
|
||||||
|
};
|
||||||
|
|
||||||
|
// let's check if we surpassed an existing stop percentage
|
||||||
|
if let Some(existing_stop_percentage) = self.stop_percentages.get(&position.id()) {
|
||||||
|
if &position.pl_perc() <= existing_stop_percentage {
|
||||||
|
info!("Stop percentage surpassed. Closing position.");
|
||||||
|
return (position, None, Some(vec![close_message]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self.update_stop_percentage(&position);
|
||||||
|
|
||||||
|
(position, None, None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// #[derive(Clone, Debug)]
|
||||||
|
// pub struct TrailingStop {
|
||||||
|
// stop_percentages: HashMap<u64, f64>,
|
||||||
|
// capital_max_loss: f64,
|
||||||
|
// capital_min_profit: f64,
|
||||||
|
// capital_good_profit: f64,
|
||||||
|
// min_profit_trailing_delta: f64,
|
||||||
|
// good_profit_trailing_delta: f64,
|
||||||
|
// leverage: f64,
|
||||||
|
// min_profit_percentage: f64,
|
||||||
|
// good_profit_percentage: f64,
|
||||||
|
// max_loss_percentage: f64,
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// impl TrailingStop {
|
||||||
|
// fn update_stop_percentage(&mut self, position: &Position) -> Option<OrderForm> {
|
||||||
|
// let mut order_form = None;
|
||||||
|
//
|
||||||
|
// if let Some(profit_state) = position.profit_state() {
|
||||||
|
// let profit_state_delta = match profit_state {
|
||||||
|
// PositionProfitState::MinimumProfit => Some(self.min_profit_trailing_delta),
|
||||||
|
// PositionProfitState::Profit => Some(self.good_profit_trailing_delta),
|
||||||
|
// _ => None,
|
||||||
|
// };
|
||||||
|
//
|
||||||
|
// if let Some(profit_state_delta) = profit_state_delta {
|
||||||
|
// let current_stop_percentage = position.pl_perc() - profit_state_delta;
|
||||||
|
// let price_percentage_delta = {
|
||||||
|
// if position.is_short() {
|
||||||
|
// // 1.0 is the base price
|
||||||
|
// 1.0 - current_stop_percentage / 100.0
|
||||||
|
// } else {
|
||||||
|
// 1.0 + current_stop_percentage / 100.0
|
||||||
|
// }
|
||||||
|
// };
|
||||||
|
//
|
||||||
|
// println!("Delta: {}", price_percentage_delta);
|
||||||
|
//
|
||||||
|
// if let PositionProfitState::MinimumProfit | PositionProfitState::Profit =
|
||||||
|
// profit_state
|
||||||
|
// {
|
||||||
|
// match self.stop_percentages.get(&position.id()) {
|
||||||
|
// None => {
|
||||||
|
// self.stop_percentages
|
||||||
|
// .insert(position.id(), current_stop_percentage);
|
||||||
|
//
|
||||||
|
// trace!("Setting trailing stop, asking order manager to cancel previous orders.");
|
||||||
|
// order_form = Some(
|
||||||
|
// OrderForm::new(
|
||||||
|
// position.pair().clone(),
|
||||||
|
// OrderKind::Limit {
|
||||||
|
// price: position.base_price() * price_percentage_delta,
|
||||||
|
// },
|
||||||
|
// position.platform(),
|
||||||
|
// position.amount().neg(),
|
||||||
|
// )
|
||||||
|
// .with_metadata(OrderMetadata::with_position_id(position.id())),
|
||||||
|
// );
|
||||||
|
// }
|
||||||
|
// Some(existing_threshold) => {
|
||||||
|
// // follow and update trailing stop
|
||||||
|
// if existing_threshold < ¤t_stop_percentage {
|
||||||
|
// self.stop_percentages
|
||||||
|
// .insert(position.id(), current_stop_percentage);
|
||||||
|
//
|
||||||
|
// trace!("Updating threshold, asking order manager to cancel previous orders.");
|
||||||
|
// order_form = Some(
|
||||||
|
// OrderForm::new(
|
||||||
|
// position.pair().clone(),
|
||||||
|
// OrderKind::Limit {
|
||||||
|
// price: position.base_price() * price_percentage_delta,
|
||||||
|
// },
|
||||||
|
// position.platform(),
|
||||||
|
// position.amount().neg(),
|
||||||
|
// )
|
||||||
|
// .with_metadata(OrderMetadata::with_position_id(position.id())),
|
||||||
|
// );
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// info!(
|
||||||
|
// "\tState: {:?} | PL: {:0.2}{} ({:0.2}%) | Stop: {:0.2}",
|
||||||
|
// position.profit_state().unwrap(),
|
||||||
|
// position.pl(),
|
||||||
|
// position.pair().quote(),
|
||||||
|
// position.pl_perc(),
|
||||||
|
// self.stop_percentages.get(&position.id()).unwrap_or(&0.0)
|
||||||
|
// );
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// order_form
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// impl Default for TrailingStop {
|
||||||
|
// fn default() -> Self {
|
||||||
|
// let leverage = 5.0;
|
||||||
|
//
|
||||||
|
// // in percentage
|
||||||
|
// let capital_max_loss = 15.0;
|
||||||
|
// let capital_min_profit = 1.0;
|
||||||
|
// let capital_good_profit = 6.0;
|
||||||
|
//
|
||||||
|
// let weighted_min_profit = capital_min_profit / leverage;
|
||||||
|
// let weighted_good_profit = capital_good_profit / leverage;
|
||||||
|
// let weighted_max_loss = capital_max_loss / leverage;
|
||||||
|
//
|
||||||
|
// let min_profit_trailing_delta = weighted_min_profit * 0.2;
|
||||||
|
// let good_profit_trailing_delta = weighted_good_profit * 0.08;
|
||||||
|
//
|
||||||
|
// let min_profit_percentage = weighted_min_profit + min_profit_trailing_delta;
|
||||||
|
// let good_profit_percentage = weighted_good_profit + good_profit_trailing_delta;
|
||||||
|
// let max_loss_percentage = -weighted_max_loss;
|
||||||
|
//
|
||||||
|
// TrailingStop {
|
||||||
|
// stop_percentages: Default::default(),
|
||||||
|
// capital_max_loss,
|
||||||
|
// capital_min_profit,
|
||||||
|
// capital_good_profit,
|
||||||
|
// min_profit_trailing_delta,
|
||||||
|
// good_profit_trailing_delta,
|
||||||
|
// leverage,
|
||||||
|
// min_profit_percentage,
|
||||||
|
// good_profit_percentage,
|
||||||
|
// max_loss_percentage,
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// impl PositionStrategy for TrailingStop {
|
||||||
|
// fn name(&self) -> String {
|
||||||
|
// "Trailing Stop".into()
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// /// Sets the profit state of an open position
|
||||||
|
// fn on_tick(
|
||||||
|
// &mut self,
|
||||||
|
// position: Position,
|
||||||
|
// current_tick: u64,
|
||||||
|
// positions_history: &HashMap<u64, Position>,
|
||||||
|
// ) -> (Position, Option<Vec<Event>>, Option<Vec<ActionMessage>>) {
|
||||||
|
// let pl_perc = position.pl_perc();
|
||||||
|
//
|
||||||
|
// let state = {
|
||||||
|
// if pl_perc > self.good_profit_percentage {
|
||||||
|
// PositionProfitState::Profit
|
||||||
|
// } else if (self.min_profit_percentage..self.good_profit_percentage).contains(&pl_perc) {
|
||||||
|
// PositionProfitState::MinimumProfit
|
||||||
|
// } else if (0.0..self.min_profit_percentage).contains(&pl_perc) {
|
||||||
|
// PositionProfitState::BreakEven
|
||||||
|
// } else if (self.max_loss_percentage..0.0).contains(&pl_perc) {
|
||||||
|
// PositionProfitState::Loss
|
||||||
|
// } else {
|
||||||
|
// PositionProfitState::Critical
|
||||||
|
// }
|
||||||
|
// };
|
||||||
|
//
|
||||||
|
// let opt_prev_position = positions_history.get(&(current_tick - 1));
|
||||||
|
// let event_metadata = EventMetadata::new(Some(position.id()), None);
|
||||||
|
// let new_position = position.with_profit_state(Some(state));
|
||||||
|
//
|
||||||
|
// match opt_prev_position {
|
||||||
|
// Some(prev) => {
|
||||||
|
// if prev.profit_state() == Some(state) {
|
||||||
|
// return (new_position, None, None);
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// None => return (new_position, None, None),
|
||||||
|
// };
|
||||||
|
//
|
||||||
|
// let events = {
|
||||||
|
// let mut events = vec![];
|
||||||
|
//
|
||||||
|
// if state == PositionProfitState::Profit {
|
||||||
|
// events.push(Event::new(
|
||||||
|
// EventKind::ReachedGoodProfit,
|
||||||
|
// current_tick,
|
||||||
|
// Some(event_metadata),
|
||||||
|
// ));
|
||||||
|
// } else if state == PositionProfitState::MinimumProfit {
|
||||||
|
// events.push(Event::new(
|
||||||
|
// EventKind::ReachedMinProfit,
|
||||||
|
// current_tick,
|
||||||
|
// Some(event_metadata),
|
||||||
|
// ));
|
||||||
|
// } else if state == PositionProfitState::BreakEven {
|
||||||
|
// events.push(Event::new(
|
||||||
|
// EventKind::ReachedBreakEven,
|
||||||
|
// current_tick,
|
||||||
|
// Some(event_metadata),
|
||||||
|
// ));
|
||||||
|
// } else if state == PositionProfitState::Loss {
|
||||||
|
// events.push(Event::new(
|
||||||
|
// EventKind::ReachedLoss,
|
||||||
|
// current_tick,
|
||||||
|
// Some(event_metadata),
|
||||||
|
// ));
|
||||||
|
// } else {
|
||||||
|
// events.push(Event::new(
|
||||||
|
// EventKind::ReachedMaxLoss,
|
||||||
|
// current_tick,
|
||||||
|
// Some(event_metadata),
|
||||||
|
// ));
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// events
|
||||||
|
// };
|
||||||
|
//
|
||||||
|
// (new_position, Some(events), None)
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// fn post_tick(
|
||||||
|
// &mut self,
|
||||||
|
// position: Position,
|
||||||
|
// _: u64,
|
||||||
|
// _: &HashMap<u64, Position>,
|
||||||
|
// ) -> (Position, Option<Vec<Event>>, Option<Vec<ActionMessage>>) {
|
||||||
|
// let close_message = ActionMessage::ClosePosition {
|
||||||
|
// position_id: position.id(),
|
||||||
|
// };
|
||||||
|
//
|
||||||
|
// // if critical, early return with close position
|
||||||
|
// if let Some(PositionProfitState::Critical) = position.profit_state() {
|
||||||
|
// info!("Maximum loss reached. Closing position.");
|
||||||
|
// return (position, None, Some(vec![close_message]));
|
||||||
|
// };
|
||||||
|
//
|
||||||
|
// // let's check if we surpassed an existing stop percentage
|
||||||
|
// if let Some(existing_stop_percentage) = self.stop_percentages.get(&position.id()) {
|
||||||
|
// if &position.pl_perc() <= existing_stop_percentage {
|
||||||
|
// info!("Stop percentage surpassed. Closing position.");
|
||||||
|
// return (position, None, Some(vec![close_message]));
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// // updated or new trailing stop. should cancel orders and submit new one
|
||||||
|
// if let Some(order_form) = self.update_stop_percentage(&position) {
|
||||||
|
// let mut messages = vec![];
|
||||||
|
//
|
||||||
|
// messages.push(ActionMessage::ClosePositionOrders {
|
||||||
|
// position_id: position.id(),
|
||||||
|
// });
|
||||||
|
// messages.push(ActionMessage::SubmitOrder { order: order_form });
|
||||||
|
//
|
||||||
|
// return (position, None, Some(messages));
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// (position, None, None)
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
/*
|
||||||
|
* ORDER STRATEGIES
|
||||||
|
*/
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct MarketEnforce {
|
||||||
|
// threshold (%) for which we trigger a market order
|
||||||
|
// to close an open position
|
||||||
|
threshold: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for MarketEnforce {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
threshold: 1.0 / 15.0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OrderStrategy for MarketEnforce {
|
||||||
|
fn name(&self) -> String {
|
||||||
|
"Market Enforce".into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn on_open_order(
|
||||||
|
&self,
|
||||||
|
order: &ActiveOrder,
|
||||||
|
order_book: &OrderBook,
|
||||||
|
) -> Result<OptionUpdate, BoxError> {
|
||||||
|
let mut messages = vec![];
|
||||||
|
|
||||||
|
// long
|
||||||
|
let offer_comparison = {
|
||||||
|
if order.order_form().amount() > 0.0 {
|
||||||
|
order_book.highest_bid()
|
||||||
|
} else {
|
||||||
|
order_book.lowest_ask()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// if the best offer is higher than our threshold,
|
||||||
|
// ask the manager to close the position with a market order
|
||||||
|
let order_price = order
|
||||||
|
.order_form()
|
||||||
|
.price()
|
||||||
|
.ok_or("The active order does not have a price!")?;
|
||||||
|
let delta = (1.0 - (offer_comparison / order_price)).abs() * 100.0;
|
||||||
|
|
||||||
|
if delta > self.threshold {
|
||||||
|
messages.push(ActionMessage::SubmitOrder {
|
||||||
|
order: OrderForm::new(
|
||||||
|
order.pair().clone(),
|
||||||
|
OrderKind::Market,
|
||||||
|
*order.order_form().platform(),
|
||||||
|
order.order_form().amount(),
|
||||||
|
)
|
||||||
|
.with_leverage(order.order_form().leverage())
|
||||||
|
.with_metadata(order.order_form().metadata().clone()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok((None, (!messages.is_empty()).then_some(messages)))
|
||||||
|
}
|
||||||
|
}
|
25
rustybot/src/ticker.rs
Normal file
25
rustybot/src/ticker.rs
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
use tokio::time::Duration;
|
||||||
|
|
||||||
|
pub struct Ticker {
|
||||||
|
duration: Duration,
|
||||||
|
current_tick: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Ticker {
|
||||||
|
pub fn new(duration: Duration) -> Self {
|
||||||
|
Ticker {
|
||||||
|
duration,
|
||||||
|
current_tick: 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn inc(&mut self) {
|
||||||
|
self.current_tick += 1
|
||||||
|
}
|
||||||
|
pub fn duration(&self) -> Duration {
|
||||||
|
self.duration
|
||||||
|
}
|
||||||
|
pub fn current_tick(&self) -> u64 {
|
||||||
|
self.current_tick
|
||||||
|
}
|
||||||
|
}
|
BIN
sounds/1up.mp3
BIN
sounds/1up.mp3
Binary file not shown.
BIN
sounds/coin.mp3
BIN
sounds/coin.mp3
Binary file not shown.
Binary file not shown.
BIN
sounds/goal.wav
BIN
sounds/goal.wav
Binary file not shown.
3
static/.gitignore
vendored
3
static/.gitignore
vendored
@ -1,3 +0,0 @@
|
|||||||
*
|
|
||||||
!.gitignore
|
|
||||||
|
|
123
strategy.py
123
strategy.py
@ -1,123 +0,0 @@
|
|||||||
from typing import List, Dict
|
|
||||||
|
|
||||||
import sympy.abc
|
|
||||||
from bfxapi import Position
|
|
||||||
from sympy import Point, solve
|
|
||||||
|
|
||||||
from bfxbot.models import Strategy, PositionState, SymbolStatus, Event, EventKind, EventMetadata, PositionWrapper, \
|
|
||||||
TAKER_FEE
|
|
||||||
from bfxbot.utils import net_pl_percentage
|
|
||||||
|
|
||||||
|
|
||||||
class SquaredTrailingStop:
|
|
||||||
def __init__(self, p_min: Point, p_max: Point):
|
|
||||||
a = sympy.abc.a
|
|
||||||
b = sympy.abc.b
|
|
||||||
c = sympy.abc.c
|
|
||||||
|
|
||||||
self.p_min = p_min
|
|
||||||
self.p_max = p_max
|
|
||||||
|
|
||||||
e1 = 2 * a * (p_max.x + b)
|
|
||||||
e2 = a * (p_min.x + b) ** 2 + c - p_min.y
|
|
||||||
e3 = a * (p_max.x + b) ** 2 + c - p_max.y
|
|
||||||
|
|
||||||
s = solve([e1, e2, e3])[0]
|
|
||||||
|
|
||||||
self.a, self.b, self.c = s[a], s[b], s[c]
|
|
||||||
|
|
||||||
def y(self, x):
|
|
||||||
def inter_y(x):
|
|
||||||
return self.a * (x + self.b) ** 2 + self.c
|
|
||||||
|
|
||||||
if x < self.p_min.x:
|
|
||||||
return self.p_min.y
|
|
||||||
elif x > self.p_max.x:
|
|
||||||
return self.p_max.y
|
|
||||||
else:
|
|
||||||
return inter_y(x)
|
|
||||||
|
|
||||||
def profit(self, x):
|
|
||||||
if x < self.p_min.x:
|
|
||||||
return 0
|
|
||||||
return x - self.y(x)
|
|
||||||
|
|
||||||
|
|
||||||
class TrailingStopStrategy(Strategy):
|
|
||||||
BREAK_EVEN_PERC = TAKER_FEE
|
|
||||||
MIN_PROFIT_PERC = BREAK_EVEN_PERC + 0.3
|
|
||||||
GOOD_PROFIT_PERC = MIN_PROFIT_PERC * 2.5
|
|
||||||
MAX_LOSS_PERC = -4.0
|
|
||||||
|
|
||||||
TRAILING_STOP = SquaredTrailingStop(Point(MIN_PROFIT_PERC, MIN_PROFIT_PERC / 3 * 2), Point(GOOD_PROFIT_PERC, 0.1))
|
|
||||||
|
|
||||||
def __init__(self):
|
|
||||||
# position_id : stop percentage
|
|
||||||
self.stop_percentage: Dict[int, float] = {}
|
|
||||||
|
|
||||||
def position_on_new_tick(self, current_position: Position, ss: SymbolStatus) -> (PositionState, List[Event]):
|
|
||||||
events = []
|
|
||||||
|
|
||||||
pl_perc = net_pl_percentage(current_position.profit_loss_percentage, TAKER_FEE)
|
|
||||||
prev = ss.previous_pw(current_position.id)
|
|
||||||
event_metadata = EventMetadata(position_id=current_position.id)
|
|
||||||
|
|
||||||
if pl_perc > self.GOOD_PROFIT_PERC:
|
|
||||||
state = PositionState.PROFIT
|
|
||||||
elif self.MIN_PROFIT_PERC <= pl_perc < self.GOOD_PROFIT_PERC:
|
|
||||||
state = PositionState.MINIMUM_PROFIT
|
|
||||||
elif 0.0 <= pl_perc < self.MIN_PROFIT_PERC:
|
|
||||||
state = PositionState.BREAK_EVEN
|
|
||||||
elif self.MAX_LOSS_PERC < pl_perc < 0.0:
|
|
||||||
state = PositionState.LOSS
|
|
||||||
else:
|
|
||||||
events.append(Event(EventKind.CLOSE_POSITION, ss.current_tick, event_metadata))
|
|
||||||
state = PositionState.CRITICAL
|
|
||||||
|
|
||||||
pw = PositionWrapper(current_position, state=state, net_profit_loss=current_position.profit_loss,
|
|
||||||
net_profit_loss_percentage=pl_perc)
|
|
||||||
|
|
||||||
if not prev or prev.state() == state:
|
|
||||||
return pw, events
|
|
||||||
|
|
||||||
if state == PositionState.PROFIT:
|
|
||||||
events.append(Event(EventKind.REACHED_GOOD_PROFIT, ss.current_tick, event_metadata))
|
|
||||||
elif state == PositionState.MINIMUM_PROFIT:
|
|
||||||
events.append(Event(EventKind.REACHED_MIN_PROFIT, ss.current_tick, event_metadata))
|
|
||||||
elif state == PositionState.BREAK_EVEN:
|
|
||||||
events.append(Event(EventKind.REACHED_BREAK_EVEN, ss.current_tick, event_metadata))
|
|
||||||
elif state == PositionState.LOSS:
|
|
||||||
events.append(Event(EventKind.REACHED_LOSS, ss.current_tick, event_metadata))
|
|
||||||
else:
|
|
||||||
events.append(Event(EventKind.REACHED_MAX_LOSS, ss.current_tick, event_metadata))
|
|
||||||
events.append(Event(EventKind.CLOSE_POSITION, ss.current_tick, event_metadata))
|
|
||||||
|
|
||||||
return pw, events
|
|
||||||
|
|
||||||
async def update_stop_percentage(self, pw: PositionWrapper, ss: SymbolStatus):
|
|
||||||
current_pl_perc = pw.net_profit_loss_percentage()
|
|
||||||
pid = pw.position.id
|
|
||||||
event_metadata = EventMetadata(position_id=pw.position.id)
|
|
||||||
|
|
||||||
# if trailing stop not set for this position and state is not profit (we should not set it)
|
|
||||||
if pid not in self.stop_percentage and pw.state() not in [PositionState.MINIMUM_PROFIT,
|
|
||||||
PositionState.PROFIT]:
|
|
||||||
return
|
|
||||||
|
|
||||||
# set stop percentage for first time only if in profit
|
|
||||||
if pid not in self.stop_percentage:
|
|
||||||
await ss.add_event(Event(EventKind.TRAILING_STOP_SET, ss.current_tick, event_metadata))
|
|
||||||
|
|
||||||
self.stop_percentage[pid] = current_pl_perc - self.TRAILING_STOP.y(current_pl_perc)
|
|
||||||
return
|
|
||||||
|
|
||||||
# moving trailing stop
|
|
||||||
if current_pl_perc - self.TRAILING_STOP.y(current_pl_perc) > self.stop_percentage[pid]:
|
|
||||||
await ss.add_event(Event(EventKind.TRAILING_STOP_MOVED, ss.current_tick, event_metadata))
|
|
||||||
self.stop_percentage[pid] = current_pl_perc - self.TRAILING_STOP.y(current_pl_perc)
|
|
||||||
|
|
||||||
# close position if current P/L below stop percentage
|
|
||||||
if current_pl_perc < self.stop_percentage[pid]:
|
|
||||||
await ss.add_event(Event(EventKind.CLOSE_POSITION, ss.current_tick, event_metadata))
|
|
||||||
|
|
||||||
return
|
|
@ -1,16 +0,0 @@
|
|||||||
<!doctype html>
|
|
||||||
<html>
|
|
||||||
|
|
||||||
<head>
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
||||||
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='index.css') }}">
|
|
||||||
</head>
|
|
||||||
|
|
||||||
<title>Rustico</title>
|
|
||||||
|
|
||||||
<body>
|
|
||||||
<div id="root"></div>
|
|
||||||
<script src="{{ url_for('static', filename='index.js') }}"></script>
|
|
||||||
</body>
|
|
||||||
|
|
||||||
</html>
|
|
1
websrc/.eslintcache
Normal file
1
websrc/.eslintcache
Normal file
File diff suppressed because one or more lines are too long
24
websrc/.gitignore
vendored
24
websrc/.gitignore
vendored
@ -1 +1,23 @@
|
|||||||
*.js
|
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||||
|
|
||||||
|
# dependencies
|
||||||
|
/node_modules
|
||||||
|
/.pnp
|
||||||
|
.pnp.js
|
||||||
|
|
||||||
|
# testing
|
||||||
|
/coverage
|
||||||
|
|
||||||
|
# production
|
||||||
|
/build
|
||||||
|
|
||||||
|
# misc
|
||||||
|
.DS_Store
|
||||||
|
.env.local
|
||||||
|
.env.development.local
|
||||||
|
.env.test.local
|
||||||
|
.env.production.local
|
||||||
|
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
70
websrc/README.md
Normal file
70
websrc/README.md
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
# Getting Started with Create React App
|
||||||
|
|
||||||
|
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
|
||||||
|
|
||||||
|
## Available Scripts
|
||||||
|
|
||||||
|
In the project directory, you can run:
|
||||||
|
|
||||||
|
### `yarn start`
|
||||||
|
|
||||||
|
Runs the app in the development mode.\
|
||||||
|
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
|
||||||
|
|
||||||
|
The page will reload if you make edits.\
|
||||||
|
You will also see any lint errors in the console.
|
||||||
|
|
||||||
|
### `yarn test`
|
||||||
|
|
||||||
|
Launches the test runner in the interactive watch mode.\
|
||||||
|
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
|
||||||
|
|
||||||
|
### `yarn build`
|
||||||
|
|
||||||
|
Builds the app for production to the `build` folder.\
|
||||||
|
It correctly bundles React in production mode and optimizes the build for the best performance.
|
||||||
|
|
||||||
|
The build is minified and the filenames include the hashes.\
|
||||||
|
Your app is ready to be deployed!
|
||||||
|
|
||||||
|
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
|
||||||
|
|
||||||
|
### `yarn eject`
|
||||||
|
|
||||||
|
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
|
||||||
|
|
||||||
|
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
|
||||||
|
|
||||||
|
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
|
||||||
|
|
||||||
|
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
|
||||||
|
|
||||||
|
## Learn More
|
||||||
|
|
||||||
|
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
|
||||||
|
|
||||||
|
To learn React, check out the [React documentation](https://reactjs.org/).
|
||||||
|
|
||||||
|
### Code Splitting
|
||||||
|
|
||||||
|
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
|
||||||
|
|
||||||
|
### Analyzing the Bundle Size
|
||||||
|
|
||||||
|
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
|
||||||
|
|
||||||
|
### Making a Progressive Web App
|
||||||
|
|
||||||
|
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
|
||||||
|
|
||||||
|
### Advanced Configuration
|
||||||
|
|
||||||
|
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
|
||||||
|
|
||||||
|
### Deployment
|
||||||
|
|
||||||
|
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
|
||||||
|
|
||||||
|
### `yarn build` fails to minify
|
||||||
|
|
||||||
|
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
|
@ -28,7 +28,7 @@ class CoinBalance extends Component<CoinBalanceProps> {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex-grow flex px-6 py-3 text-gray-800 items-center border-b -mx-4 align-middle">
|
<div className="flex-grow flex px-6 py-3 text-gray-800 items-center border-b -mx-4 align-middle">
|
||||||
<div className={"w-1/8"}>
|
<div className={"w-1/8 bg-te"}>
|
||||||
{/*{icon}*/}
|
{/*{icon}*/}
|
||||||
</div>
|
</div>
|
||||||
<div className="w-2/5 xl:w-1/4 px-4 flex items-center">
|
<div className="w-2/5 xl:w-1/4 px-4 flex items-center">
|
||||||
|
@ -1,45 +0,0 @@
|
|||||||
import {Button, ButtonGroup, Dropdown} from "react-bootstrap";
|
|
||||||
import React, {Component} from "react";
|
|
||||||
import DropdownItem from "react-bootstrap/DropdownItem";
|
|
||||||
import {CurrencyPair} from "../types";
|
|
||||||
|
|
||||||
|
|
||||||
export type CurrencyPairProps = {
|
|
||||||
active_pair: CurrencyPair,
|
|
||||||
pairs: Array<CurrencyPair>
|
|
||||||
}
|
|
||||||
|
|
||||||
export class CurrencyDropdown extends Component<CurrencyPairProps> {
|
|
||||||
constructor(props) {
|
|
||||||
super(props);
|
|
||||||
}
|
|
||||||
|
|
||||||
dropdownItems() {
|
|
||||||
return this.props.pairs.map((pair) => {
|
|
||||||
return (
|
|
||||||
<DropdownItem key={String(pair.base) + String(pair.quote)}> {pair.base} / {pair.quote} </DropdownItem>)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
render() {
|
|
||||||
return (
|
|
||||||
<Dropdown as={ButtonGroup} className={"mr-3"}>
|
|
||||||
<Button variant="outline-primary"><b>{this.props.active_pair.base} / {this.props.active_pair.quote}</b></Button>
|
|
||||||
|
|
||||||
{this.props.pairs.length > 0 &&
|
|
||||||
|
|
||||||
<>
|
|
||||||
<Dropdown.Toggle split variant="primary" id="dropdown-split-basic"/>
|
|
||||||
|
|
||||||
<Dropdown.Menu className={"mr-3"}>
|
|
||||||
{this.dropdownItems()}
|
|
||||||
</Dropdown.Menu>
|
|
||||||
</>
|
|
||||||
}
|
|
||||||
|
|
||||||
</Dropdown>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
@ -1,42 +0,0 @@
|
|||||||
import React, {Component} from "react";
|
|
||||||
import {Container, ListGroup} from "react-bootstrap";
|
|
||||||
|
|
||||||
|
|
||||||
export type EventProp = {
|
|
||||||
id: number,
|
|
||||||
name: string,
|
|
||||||
tick: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export class Events extends Component<{ events: Array<EventProp> }> {
|
|
||||||
constructor(props) {
|
|
||||||
super(props);
|
|
||||||
}
|
|
||||||
|
|
||||||
state = {
|
|
||||||
events: this.props.events
|
|
||||||
}
|
|
||||||
|
|
||||||
mapEvents() {
|
|
||||||
return this.state.events.map((event: EventProp) => {
|
|
||||||
return (
|
|
||||||
<ListGroup.Item action key={event.id}>
|
|
||||||
{event.name} @ Tick {event.tick}
|
|
||||||
</ListGroup.Item>
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
render() {
|
|
||||||
return (
|
|
||||||
<Container>
|
|
||||||
<div className={"border-bottom mb-2"}>
|
|
||||||
<h2>Events</h2>
|
|
||||||
</div>
|
|
||||||
<ListGroup>
|
|
||||||
{this.mapEvents()}
|
|
||||||
</ListGroup>
|
|
||||||
</Container>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,48 +0,0 @@
|
|||||||
import React, {Component} from 'react';
|
|
||||||
import {Toast} from 'react-bootstrap';
|
|
||||||
import {socket} from "../";
|
|
||||||
|
|
||||||
type ToastProps = {
|
|
||||||
title: string,
|
|
||||||
content?: string,
|
|
||||||
bg?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
type ToastState = {
|
|
||||||
lastUpdated: Date,
|
|
||||||
show: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
export class RToast extends Component<ToastProps, ToastState> {
|
|
||||||
state = {
|
|
||||||
lastUpdated: new Date(),
|
|
||||||
show: false
|
|
||||||
}
|
|
||||||
|
|
||||||
constructor(props: ToastProps) {
|
|
||||||
super(props)
|
|
||||||
}
|
|
||||||
|
|
||||||
componentDidMount() {
|
|
||||||
socket.on("connect", () => {
|
|
||||||
this.setState({show: true})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
tick() {
|
|
||||||
this.setState({lastUpdated: new Date()})
|
|
||||||
}
|
|
||||||
|
|
||||||
render() {
|
|
||||||
return (
|
|
||||||
<Toast show={this.state.show} delay={5000} autohide>
|
|
||||||
<Toast.Header>
|
|
||||||
<strong className="mr-auto">{this.props.title}</strong>
|
|
||||||
<small>{this.state.lastUpdated.toLocaleTimeString('en-GB')}</small>
|
|
||||||
</Toast.Header>
|
|
||||||
{this.props.content ? <Toast.Body> {this.props.content}</Toast.Body> : null}
|
|
||||||
</Toast>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,40 +1,55 @@
|
|||||||
{
|
{
|
||||||
"name": "rustico",
|
"name": "bfxbot",
|
||||||
"version": "1.0.0",
|
"version": "0.1.0",
|
||||||
"main": "index.tsx",
|
"private": true,
|
||||||
"license": "MIT",
|
"dependencies": {
|
||||||
"devDependencies": {
|
"@testing-library/jest-dom": "^5.11.4",
|
||||||
"@types/luxon": "^1.25.0",
|
"@testing-library/react": "^11.1.0",
|
||||||
|
"@testing-library/user-event": "^12.1.10",
|
||||||
|
"@types/jest": "^26.0.19",
|
||||||
|
"@types/node": "^14.14.16",
|
||||||
"@types/react": "^17.0.0",
|
"@types/react": "^17.0.0",
|
||||||
"@types/react-dom": "^17.0.0",
|
"@types/react-dom": "^17.0.0",
|
||||||
"@types/react-helmet": "^6.1.0",
|
"plotly.js": "^1.58.4",
|
||||||
"@types/react-plotly.js": "^2.2.4",
|
|
||||||
"@types/socket.io-client": "^1.4.34",
|
|
||||||
"parcel-bundler": "^1.12.4",
|
|
||||||
"react-plotly.js": "^2.5.1",
|
|
||||||
"typescript": "^4.1.2"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@types/classnames": "^2.2.11",
|
|
||||||
"autoprefixer": "^10.1.0",
|
|
||||||
"classnames": "^2.2.6",
|
|
||||||
"css": "^3.0.0",
|
|
||||||
"luxon": "^1.25.0",
|
|
||||||
"plotly.js": "^1.58.2",
|
|
||||||
"postcss": "^8.2.1",
|
|
||||||
"postcss-cli": "^8.3.1",
|
|
||||||
"react": "^17.0.1",
|
"react": "^17.0.1",
|
||||||
"react-cryptocoins": "^1.0.11",
|
|
||||||
"react-dom": "^17.0.1",
|
"react-dom": "^17.0.1",
|
||||||
"react-helmet": "^6.1.0",
|
"react-plotly.js": "^2.5.1",
|
||||||
"socket.io-client": "~3",
|
"react-scripts": "4.0.1",
|
||||||
"tailwindcss": "^2.0.2"
|
"socket.io-client": "^3.0.4",
|
||||||
|
"typescript": "^4.1.3",
|
||||||
|
"web-vitals": "^0.2.4"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build:tailwind": "tailwindcss build css/index.css -o css/tailwind.css",
|
"start": "react-scripts start",
|
||||||
"watch": "parcel watch index.tsx -d ../static",
|
"build": "react-scripts build",
|
||||||
"prestart": "yarn run build:tailwind",
|
"test": "react-scripts test",
|
||||||
"prebuild": "yarn run build:tailwind",
|
"eject": "react-scripts eject"
|
||||||
"start": "python ../main.py & yarn run watch"
|
},
|
||||||
|
"eslintConfig": {
|
||||||
|
"extends": [
|
||||||
|
"react-app",
|
||||||
|
"react-app/jest"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"browserslist": {
|
||||||
|
"production": [
|
||||||
|
">0.2%",
|
||||||
|
"not dead",
|
||||||
|
"not op_mini all"
|
||||||
|
],
|
||||||
|
"development": [
|
||||||
|
"last 1 chrome version",
|
||||||
|
"last 1 firefox version",
|
||||||
|
"last 1 safari version"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/luxon": "^1.25.0",
|
||||||
|
"@types/react-helmet": "^6.1.0",
|
||||||
|
"@types/react-plotly.js": "^2.2.4",
|
||||||
|
"luxon": "^1.25.0",
|
||||||
|
"react-cryptocoins": "^1.0.11",
|
||||||
|
"react-helmet": "^6.1.0",
|
||||||
|
"react-plotly": "^1.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
BIN
websrc/public/favicon.ico
Normal file
BIN
websrc/public/favicon.ico
Normal file
Binary file not shown.
After Width: | Height: | Size: 3.8 KiB |
43
websrc/public/index.html
Normal file
43
websrc/public/index.html
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<meta name="theme-color" content="#000000" />
|
||||||
|
<meta
|
||||||
|
name="description"
|
||||||
|
content="Web site created using create-react-app"
|
||||||
|
/>
|
||||||
|
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
|
||||||
|
<!--
|
||||||
|
manifest.json provides metadata used when your web app is installed on a
|
||||||
|
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
|
||||||
|
-->
|
||||||
|
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
|
||||||
|
<!--
|
||||||
|
Notice the use of %PUBLIC_URL% in the tags above.
|
||||||
|
It will be replaced with the URL of the `public` folder during the build.
|
||||||
|
Only files inside the `public` folder can be referenced from the HTML.
|
||||||
|
|
||||||
|
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
|
||||||
|
work correctly both with client-side routing and a non-root public URL.
|
||||||
|
Learn how to configure a non-root public URL by running `npm run build`.
|
||||||
|
-->
|
||||||
|
<title>React App</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||||
|
<div id="root"></div>
|
||||||
|
<!--
|
||||||
|
This HTML file is a template.
|
||||||
|
If you open it directly in the browser, you will see an empty page.
|
||||||
|
|
||||||
|
You can add webfonts, meta tags, or analytics to this file.
|
||||||
|
The build step will place the bundled scripts into the <body> tag.
|
||||||
|
|
||||||
|
To begin the development, run `npm start` or `yarn start`.
|
||||||
|
To create a production bundle, use `npm run build` or `yarn build`.
|
||||||
|
-->
|
||||||
|
</body>
|
||||||
|
</html>
|
BIN
websrc/public/logo192.png
Normal file
BIN
websrc/public/logo192.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 5.2 KiB |
BIN
websrc/public/logo512.png
Normal file
BIN
websrc/public/logo512.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 9.4 KiB |
25
websrc/public/manifest.json
Normal file
25
websrc/public/manifest.json
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"short_name": "React App",
|
||||||
|
"name": "Create React App Sample",
|
||||||
|
"icons": [
|
||||||
|
{
|
||||||
|
"src": "favicon.ico",
|
||||||
|
"sizes": "64x64 32x32 24x24 16x16",
|
||||||
|
"type": "image/x-icon"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "logo192.png",
|
||||||
|
"type": "image/png",
|
||||||
|
"sizes": "192x192"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "logo512.png",
|
||||||
|
"type": "image/png",
|
||||||
|
"sizes": "512x512"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"start_url": ".",
|
||||||
|
"display": "standalone",
|
||||||
|
"theme_color": "#000000",
|
||||||
|
"background_color": "#ffffff"
|
||||||
|
}
|
3
websrc/public/robots.txt
Normal file
3
websrc/public/robots.txt
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
# https://www.robotstxt.org/robotstxt.html
|
||||||
|
User-agent: *
|
||||||
|
Disallow:
|
131
websrc/src/components/App.tsx
Normal file
131
websrc/src/components/App.tsx
Normal file
@ -0,0 +1,131 @@
|
|||||||
|
import React, { Component } from "react";
|
||||||
|
import {
|
||||||
|
Balance,
|
||||||
|
CurrencyPair,
|
||||||
|
EventName,
|
||||||
|
EventProp,
|
||||||
|
FirstConnectMessage,
|
||||||
|
NewEventMessage,
|
||||||
|
NewTickMessage,
|
||||||
|
PositionProp
|
||||||
|
} from "../types";
|
||||||
|
import { socket } from "../index";
|
||||||
|
import { symbolToPair } from "../utils";
|
||||||
|
import { Helmet } from "react-helmet";
|
||||||
|
import { Navbar, Sidebar } from "./Navbars";
|
||||||
|
import { Statusbar } from "./Statusbar";
|
||||||
|
import { PositionsTable } from "./Tables";
|
||||||
|
import RPlot from "./RPlot";
|
||||||
|
|
||||||
|
type AppState = {
|
||||||
|
current_price: number,
|
||||||
|
current_tick: number,
|
||||||
|
last_update: Date,
|
||||||
|
positions: Array<PositionProp>,
|
||||||
|
events: Array<EventProp>,
|
||||||
|
active_pair: CurrencyPair,
|
||||||
|
available_pairs: Array<CurrencyPair>,
|
||||||
|
balances: Array<Balance>
|
||||||
|
}
|
||||||
|
|
||||||
|
class App extends Component<{}, AppState> {
|
||||||
|
event_id = 0;
|
||||||
|
|
||||||
|
state = {
|
||||||
|
current_price: 0,
|
||||||
|
current_tick: 0,
|
||||||
|
last_update: new Date(),
|
||||||
|
positions: [],
|
||||||
|
events: [],
|
||||||
|
balances: [],
|
||||||
|
active_pair: symbolToPair("tBTCUSD"),
|
||||||
|
available_pairs: []
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(props: {}) {
|
||||||
|
super(props)
|
||||||
|
}
|
||||||
|
|
||||||
|
componentDidMount() {
|
||||||
|
socket.on(EventName.FirstConnect, (data: FirstConnectMessage) => {
|
||||||
|
this.setState({
|
||||||
|
current_price: data.prices[data.prices.length - 1],
|
||||||
|
current_tick: data.ticks[data.ticks.length - 1],
|
||||||
|
last_update: new Date(),
|
||||||
|
positions: data.positions,
|
||||||
|
balances: data.balances
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
socket.on(EventName.NewTick, (data: NewTickMessage) => {
|
||||||
|
this.setState({
|
||||||
|
current_price: data.price,
|
||||||
|
current_tick: data.tick,
|
||||||
|
last_update: new Date(),
|
||||||
|
positions: data.positions,
|
||||||
|
balances: data.balances
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
socket.on(EventName.NewEvent, (data: NewEventMessage) => {
|
||||||
|
// ignore new tick
|
||||||
|
if (!data.kind.toLowerCase().includes("new_tick")) {
|
||||||
|
const new_event: EventProp = {
|
||||||
|
id: this.event_id,
|
||||||
|
name: data.kind,
|
||||||
|
tick: data.tick
|
||||||
|
}
|
||||||
|
|
||||||
|
this.event_id += 1
|
||||||
|
|
||||||
|
this.setState((state) => ({
|
||||||
|
events: [...state.events, new_event]
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
render() {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Helmet>
|
||||||
|
<title> Rustico
|
||||||
|
- {String(this.state.current_price.toLocaleString())} {String(this.state.active_pair.base) + "/" + String(this.state.active_pair.quote)} </title>
|
||||||
|
</Helmet>
|
||||||
|
<div className="bg-gray-800">
|
||||||
|
<div className="h-screen max-w-screen flex mx-auto">
|
||||||
|
<Navbar />
|
||||||
|
|
||||||
|
<main
|
||||||
|
className="my-1 py-2 px-10 flex-1 bg-gray-200 dark:bg-black rounded-l-lg*
|
||||||
|
transition duration-500 ease-in-out overflow-y-auto flex flex-col">
|
||||||
|
<div className="flex justify-center text-2xl my-2">
|
||||||
|
<Statusbar balances={this.state.balances} positions={this.state.positions}
|
||||||
|
price={this.state.current_price}
|
||||||
|
tick={this.state.current_tick} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col flex-grow my-8 shadow-md hover:shadow-lg">
|
||||||
|
<div
|
||||||
|
className="py-2 flex-grow bg-white min-width dark:bg-gray-600 rounded-lg overflow-hidden">
|
||||||
|
<RPlot />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{this.state.positions.length > 0 ?
|
||||||
|
<PositionsTable positions={this.state.positions} /> : null}
|
||||||
|
|
||||||
|
<footer className="flex rounded-lg justify-center bg-gray-600 mt-4 border-t text-gray-300">
|
||||||
|
<span className="my-1 mx-1">Made with ❤️ by the Peperone in a scantinato</span>
|
||||||
|
</footer>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<Sidebar />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default App;
|
154
websrc/src/components/Cards.tsx
Normal file
154
websrc/src/components/Cards.tsx
Normal file
@ -0,0 +1,154 @@
|
|||||||
|
import React, { Component } from 'react';
|
||||||
|
import { Balance, EventName, FirstConnectMessage, NewTickMessage } from "../types";
|
||||||
|
import { socket } from "../index";
|
||||||
|
|
||||||
|
export type CoinBalanceProps = {
|
||||||
|
name: string,
|
||||||
|
amount: number,
|
||||||
|
percentage: number,
|
||||||
|
quote_equivalent: number,
|
||||||
|
quote_symbol: string,
|
||||||
|
}
|
||||||
|
|
||||||
|
class CoinBalance extends Component<CoinBalanceProps> {
|
||||||
|
constructor(props: CoinBalanceProps) {
|
||||||
|
super(props);
|
||||||
|
}
|
||||||
|
|
||||||
|
render() {
|
||||||
|
// do not print equivalent if this element is the quote itself
|
||||||
|
const quoteBlock = this.props.name != this.props.quote_symbol ? this.props.quote_symbol.concat(" ").concat(this.props.quote_equivalent.toLocaleString()) : null
|
||||||
|
|
||||||
|
// const accessory = SymbolAccessories.filter((accessory) => {
|
||||||
|
// return accessory.name == this.props.name
|
||||||
|
// })
|
||||||
|
//
|
||||||
|
// const icon = accessory.length > 0 ? accessory.pop().icon : null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex-grow flex px-6 py-3 text-gray-800 items-center border-b -mx-4 align-middle">
|
||||||
|
<div className={"w-1/8"}>
|
||||||
|
{/*{icon}*/}
|
||||||
|
</div>
|
||||||
|
<div className="w-2/5 xl:w-1/4 px-4 flex items-center">
|
||||||
|
<span className="text-lg">{this.props.name}</span>
|
||||||
|
</div>
|
||||||
|
<div className="hidden md:flex lg:hidden xl:flex w-1/4 px-1 flex-col">
|
||||||
|
<div className={"italic w-full text-center"}>
|
||||||
|
{Math.trunc(this.props.percentage)}%
|
||||||
|
</div>
|
||||||
|
<div className="w-full bg-transparent mt-2">
|
||||||
|
<div className={"bg-blue-400 rounded-lg text-xs leading-none py-1 text-center text-white"}
|
||||||
|
style={{ width: this.props.percentage.toString().concat("%") }} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex w-3/5 md:w/12">
|
||||||
|
<div className="w-1/2 px-4">
|
||||||
|
<div className="text-right">
|
||||||
|
{this.props.amount.toFixed(5)} {this.props.name}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="w-1/2 px-4 my-auto">
|
||||||
|
<div
|
||||||
|
className={"px-2 inline-flex text-center text-xs leading-5 font-semibold rounded-full bg-gray-200 text-gray-800"}>
|
||||||
|
{quoteBlock}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
export type WalletCardProps = {
|
||||||
|
quote: string,
|
||||||
|
}
|
||||||
|
|
||||||
|
export class WalletCard extends Component
|
||||||
|
<{}, { balances: Array<Balance> }> {
|
||||||
|
// constructor(props) {
|
||||||
|
// super(props);
|
||||||
|
// }
|
||||||
|
|
||||||
|
state =
|
||||||
|
{
|
||||||
|
balances: []
|
||||||
|
}
|
||||||
|
|
||||||
|
totalQuoteBalance() {
|
||||||
|
let total = 0
|
||||||
|
|
||||||
|
this.state.balances.forEach((balance: Balance) => {
|
||||||
|
if (balance.currency == balance.quote) {
|
||||||
|
total += balance.amount
|
||||||
|
} else {
|
||||||
|
total += balance.quote_equivalent
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return total
|
||||||
|
}
|
||||||
|
|
||||||
|
renderCoinBalances() {
|
||||||
|
return (
|
||||||
|
this.state.balances.map((balance: Balance) => {
|
||||||
|
const percentage_amount = balance.quote == balance.currency ? balance.amount : balance.quote_equivalent;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<CoinBalance key={balance.currency.concat(balance.kind)} name={balance.currency}
|
||||||
|
amount={balance.amount} quote_equivalent={balance.quote_equivalent}
|
||||||
|
percentage={percentage_amount / this.totalQuoteBalance() * 100}
|
||||||
|
quote_symbol={balance.quote} />
|
||||||
|
)
|
||||||
|
})
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
componentDidMount() {
|
||||||
|
socket.on(EventName.NewTick, (data: NewTickMessage) => {
|
||||||
|
this.setState({
|
||||||
|
balances: data.balances
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
socket.on(EventName.FirstConnect, (data: FirstConnectMessage) => {
|
||||||
|
this.setState({
|
||||||
|
balances: data.balances
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
render() {
|
||||||
|
return (
|
||||||
|
<div className="w-full mb-6 lg:mb-0 px-4 flex flex-col">
|
||||||
|
<div
|
||||||
|
className="flex-grow flex bg-white flex-col border-t border-b sm:rounded-lg sm:border shadow overflow-hidden">
|
||||||
|
<div className="border-b bg-gray-50">
|
||||||
|
<div className="flex justify-between px-6 -mb-px">
|
||||||
|
<h3 className="text-blue-700 py-4 font-normal text-lg">Your Wallets</h3>
|
||||||
|
<div className="flex">
|
||||||
|
<button type="button"
|
||||||
|
className="appearance-none py-4 text-blue-700 border-b border-blue-dark mr-3">
|
||||||
|
Margin
|
||||||
|
</button>
|
||||||
|
<button type="button"
|
||||||
|
className="appearance-none py-4 text-gray-600 border-b border-transparent hover:border-grey-dark">
|
||||||
|
Chart
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{this.renderCoinBalances()}
|
||||||
|
|
||||||
|
<div className="px-6 py-4">
|
||||||
|
<div className="text-center text-gray-400">
|
||||||
|
Total Balance ≈ USD {this.totalQuoteBalance().toLocaleString()}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
9
websrc/src/components/Currency.tsx
Normal file
9
websrc/src/components/Currency.tsx
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
import React, { Component } from "react";
|
||||||
|
import { CurrencyPair } from "../types";
|
||||||
|
|
||||||
|
|
||||||
|
export type CurrencyPairProps = {
|
||||||
|
active_pair: CurrencyPair,
|
||||||
|
pairs: Array<CurrencyPair>
|
||||||
|
}
|
||||||
|
|
@ -9,7 +9,7 @@ class Icon extends Component <IconProps> {
|
|||||||
private readonly width: string;
|
private readonly width: string;
|
||||||
private readonly height: string;
|
private readonly height: string;
|
||||||
|
|
||||||
constructor(props) {
|
constructor(props: IconProps) {
|
||||||
super(props);
|
super(props);
|
||||||
|
|
||||||
this.width = "w-" + this.props.width.toString();
|
this.width = "w-" + this.props.width.toString();
|
@ -1,8 +1,8 @@
|
|||||||
import React, {Component} from "react";
|
import React, { Component } from "react";
|
||||||
import {WalletCard} from "./Cards";
|
import { WalletCard } from "./Cards";
|
||||||
|
|
||||||
export class Navbar extends Component<any, any> {
|
export class Navbar extends Component {
|
||||||
constructor(props) {
|
constructor(props: {}) {
|
||||||
super(props);
|
super(props);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -27,9 +27,9 @@ export class Navbar extends Component<any, any> {
|
|||||||
<li className="mt-3 p-2 text-gray-400 dark:text-blue-300 rounded-lg">
|
<li className="mt-3 p-2 text-gray-400 dark:text-blue-300 rounded-lg">
|
||||||
<a href="#" className=" flex flex-col items-center">
|
<a href="#" className=" flex flex-col items-center">
|
||||||
<svg className="w-5 h-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
|
<svg className="w-5 h-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
|
||||||
stroke="currentColor">
|
stroke="currentColor">
|
||||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
|
||||||
d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"/>
|
d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" />
|
||||||
</svg>
|
</svg>
|
||||||
<span className="text-xs mt-2 text-gray-300">Reports</span>
|
<span className="text-xs mt-2 text-gray-300">Reports</span>
|
||||||
</a>
|
</a>
|
||||||
@ -39,11 +39,11 @@ export class Navbar extends Component<any, any> {
|
|||||||
<li className="mt-auto p-2 text-gray-400 dark:text-blue-300 rounded-lg">
|
<li className="mt-auto p-2 text-gray-400 dark:text-blue-300 rounded-lg">
|
||||||
<a href="#" className=" flex flex-col items-center">
|
<a href="#" className=" flex flex-col items-center">
|
||||||
<svg className="w-5 h-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
|
<svg className="w-5 h-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
|
||||||
stroke="currentColor">
|
stroke="currentColor">
|
||||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
|
||||||
d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"/>
|
d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
|
||||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
|
||||||
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
|
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||||
</svg>
|
</svg>
|
||||||
<span className="text-xs mt-2 text-gray-300">Settings</span>
|
<span className="text-xs mt-2 text-gray-300">Settings</span>
|
||||||
</a>
|
</a>
|
||||||
@ -55,7 +55,7 @@ export class Navbar extends Component<any, any> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class Sidebar extends Component {
|
export class Sidebar extends Component {
|
||||||
constructor(props) {
|
constructor(props: {}) {
|
||||||
super(props);
|
super(props);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -64,7 +64,7 @@ export class Sidebar extends Component {
|
|||||||
<aside
|
<aside
|
||||||
className="w-1/4 my-1 mr-1 pr-2 py-4 flex flex-col bg-gray-200 dark:bg-black
|
className="w-1/4 my-1 mr-1 pr-2 py-4 flex flex-col bg-gray-200 dark:bg-black
|
||||||
dark:text-gray-400 rounded-r-lg overflow-y-auto">
|
dark:text-gray-400 rounded-r-lg overflow-y-auto">
|
||||||
<WalletCard/>
|
<WalletCard />
|
||||||
</aside>
|
</aside>
|
||||||
)
|
)
|
||||||
}
|
}
|
@ -9,7 +9,7 @@ export type ModalProps = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class ClosePositionModal extends Component<ModalProps, any> {
|
export class ClosePositionModal extends Component<ModalProps, any> {
|
||||||
constructor(props) {
|
constructor(props: ModalProps) {
|
||||||
super(props);
|
super(props);
|
||||||
}
|
}
|
||||||
|
|
@ -1,8 +1,8 @@
|
|||||||
import React, {Component} from "react"
|
import React, { Component } from "react"
|
||||||
import Plot from "react-plotly.js"
|
import Plot from "react-plotly.js"
|
||||||
|
|
||||||
import {socket} from '../';
|
import { socket } from '../';
|
||||||
import {EventName, NewTickMessage} from "../types";
|
import { EventName, NewTickMessage } from "../types";
|
||||||
|
|
||||||
|
|
||||||
type FirstConnectData = {
|
type FirstConnectData = {
|
||||||
@ -29,11 +29,11 @@ class RPlot extends Component<{}, PlotState> {
|
|||||||
state = {
|
state = {
|
||||||
x: [],
|
x: [],
|
||||||
y: [],
|
y: [],
|
||||||
current_price_line: {x0: 0, x1: 0, y0: 0, y1: 0},
|
current_price_line: { x0: 0, x1: 0, y0: 0, y1: 0 },
|
||||||
positions_price_lines: []
|
positions_price_lines: []
|
||||||
}
|
}
|
||||||
|
|
||||||
constructor(props) {
|
constructor(props: {}) {
|
||||||
super(props)
|
super(props)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -79,24 +79,24 @@ class RPlot extends Component<{}, PlotState> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
let additional_shapes = []
|
// let additional_shapes: ConcatArray<{ type: string; x0: number; y0: number; x1: number; y1: number; line: { color: string; width: number; dash: string; }; }> = []
|
||||||
|
|
||||||
if (this.state.positions_price_lines.length > 0) {
|
// if (this.state.positions_price_lines.length > 0) {
|
||||||
additional_shapes = this.state.positions_price_lines.map((priceline: PriceLine) => {
|
// additional_shapes = this.state.positions_price_lines.map((priceline: PriceLine) => {
|
||||||
return {
|
// return {
|
||||||
type: 'line',
|
// type: 'line',
|
||||||
x0: priceline.x0,
|
// x0: priceline.x0,
|
||||||
y0: priceline.y0,
|
// y0: priceline.y0,
|
||||||
x1: priceline.x1,
|
// x1: priceline.x1,
|
||||||
y1: priceline.y1,
|
// y1: priceline.y1,
|
||||||
line: {
|
// line: {
|
||||||
color: 'rgb(1, 1, 1)',
|
// color: 'rgb(1, 1, 1)',
|
||||||
width: 1,
|
// width: 1,
|
||||||
dash: 'solid'
|
// dash: 'solid'
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
})
|
// })
|
||||||
}
|
// }
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Plot
|
<Plot
|
||||||
@ -117,20 +117,20 @@ class RPlot extends Component<{}, PlotState> {
|
|||||||
pad: 4
|
pad: 4
|
||||||
},
|
},
|
||||||
dragmode: "pan",
|
dragmode: "pan",
|
||||||
shapes: [
|
// shapes: [
|
||||||
{
|
// {
|
||||||
type: 'line',
|
// type: 'line',
|
||||||
x0: this.state.current_price_line.x0,
|
// x0: this.state.current_price_line.x0,
|
||||||
y0: this.state.current_price_line.y0,
|
// y0: this.state.current_price_line.y0,
|
||||||
x1: this.state.current_price_line.x1,
|
// x1: this.state.current_price_line.x1,
|
||||||
y1: this.state.current_price_line.y1,
|
// y1: this.state.current_price_line.y1,
|
||||||
line: {
|
// line: {
|
||||||
color: 'rgb(50, 171, 96)',
|
// color: 'rgb(50, 171, 96)',
|
||||||
width: 2,
|
// width: 2,
|
||||||
dash: 'dashdot'
|
// dash: 'dashdot'
|
||||||
}
|
// }
|
||||||
},
|
// },
|
||||||
].concat(additional_shapes),
|
// ].concat(additional_shapes),
|
||||||
xaxis: {
|
xaxis: {
|
||||||
title: {
|
title: {
|
||||||
text: 'Tick',
|
text: 'Tick',
|
||||||
@ -158,7 +158,7 @@ class RPlot extends Component<{}, PlotState> {
|
|||||||
displayModeBar: false,
|
displayModeBar: false,
|
||||||
responsive: true,
|
responsive: true,
|
||||||
}}
|
}}
|
||||||
style={{width: '100%', height: '100%'}}
|
style={{ width: '100%', height: '100%' }}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
}
|
}
|
@ -1,7 +1,7 @@
|
|||||||
import React, {Component} from "react";
|
import React, { Component } from "react";
|
||||||
import {EventName, GetProfitLossMessage, NewTickMessage, PutProfitLossMessage} from "../types";
|
import { EventName, GetProfitLossMessage, NewTickMessage, PutProfitLossMessage } from "../types";
|
||||||
import {socket} from "../index";
|
import { socket } from "../index";
|
||||||
import {DateTime} from "luxon";
|
import { DateTime } from "luxon";
|
||||||
|
|
||||||
type QuoteStatusProps = {
|
type QuoteStatusProps = {
|
||||||
percentage?: boolean,
|
percentage?: boolean,
|
||||||
@ -17,9 +17,14 @@ export class QuoteStatus extends Component<QuoteStatusProps> {
|
|||||||
private sign: string;
|
private sign: string;
|
||||||
private signClass: string;
|
private signClass: string;
|
||||||
|
|
||||||
constructor(props) {
|
constructor(props: QuoteStatusProps) {
|
||||||
super(props);
|
super(props);
|
||||||
|
|
||||||
|
this.whole = 0;
|
||||||
|
this.decimal = 0;
|
||||||
|
this.sign = "";
|
||||||
|
this.signClass = "";
|
||||||
|
|
||||||
this.deriveProps()
|
this.deriveProps()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -45,8 +50,8 @@ export class QuoteStatus extends Component<QuoteStatusProps> {
|
|||||||
if (this.props.percentage) {
|
if (this.props.percentage) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<span className="text-4xl text-bold align-top">
|
<span className="text-4xl text-bold align-top">
|
||||||
{this.renderSign()}</span>
|
{this.renderSign()}</span>
|
||||||
<span className="text-5xl">{Math.abs(this.props.amount).toFixed(2)}</span>
|
<span className="text-5xl">{Math.abs(this.props.amount).toFixed(2)}</span>
|
||||||
<span className="text-3xl align-top">%</span>
|
<span className="text-3xl align-top">%</span>
|
||||||
</>
|
</>
|
||||||
@ -89,20 +94,26 @@ type DateButtonState = {
|
|||||||
class DateButton extends Component<DateButtonProps, DateButtonState> {
|
class DateButton extends Component<DateButtonProps, DateButtonState> {
|
||||||
private classSelected: string = "appearance-none py-4 text-blue-600 border-b border-blue-600 mr-3";
|
private classSelected: string = "appearance-none py-4 text-blue-600 border-b border-blue-600 mr-3";
|
||||||
private classNotSelected: string = "appearance-none py-4 text-gray-600 border-b border-transparent hover:border-gray-800 mr-3";
|
private classNotSelected: string = "appearance-none py-4 text-gray-600 border-b border-transparent hover:border-gray-800 mr-3";
|
||||||
private currentClass: string;
|
private currentClass: string = "";
|
||||||
|
|
||||||
state = {
|
state = {
|
||||||
selected: this.props.selected_default
|
selected: false
|
||||||
}
|
}
|
||||||
|
|
||||||
constructor(props) {
|
constructor(props: DateButtonProps) {
|
||||||
super(props);
|
super(props);
|
||||||
|
|
||||||
|
if (this.props.selected_default) {
|
||||||
|
this.state = {
|
||||||
|
selected: this.props.selected_default
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
this.updateClass()
|
this.updateClass()
|
||||||
}
|
}
|
||||||
|
|
||||||
onClick() {
|
onClick() {
|
||||||
this.setState({selected: !this.state.selected}, this.updateClass)
|
this.setState({ selected: !this.state.selected }, this.updateClass)
|
||||||
|
|
||||||
this.props.onClick()
|
this.props.onClick()
|
||||||
}
|
}
|
||||||
@ -114,7 +125,7 @@ class DateButton extends Component<DateButtonProps, DateButtonState> {
|
|||||||
render() {
|
render() {
|
||||||
return (
|
return (
|
||||||
<button key={this.props.label} type="button"
|
<button key={this.props.label} type="button"
|
||||||
className={this.currentClass} onClick={this.onClick.bind(this)}>
|
className={this.currentClass} onClick={this.onClick.bind(this)}>
|
||||||
{this.props.label}
|
{this.props.label}
|
||||||
</button>
|
</button>
|
||||||
)
|
)
|
||||||
@ -140,7 +151,7 @@ type StatusBarState = {
|
|||||||
|
|
||||||
export class Statusbar extends Component<NewTickMessage, StatusBarState> {
|
export class Statusbar extends Component<NewTickMessage, StatusBarState> {
|
||||||
|
|
||||||
constructor(props) {
|
constructor(props: NewTickMessage) {
|
||||||
super(props);
|
super(props);
|
||||||
|
|
||||||
this.state = {
|
this.state = {
|
||||||
@ -223,21 +234,21 @@ export class Statusbar extends Component<NewTickMessage, StatusBarState> {
|
|||||||
</div>
|
</div>
|
||||||
<div className="hidden lg:flex">
|
<div className="hidden lg:flex">
|
||||||
<button type="button"
|
<button type="button"
|
||||||
className="appearance-none py-4 text-blue-600 border-b border-blue-dark mr-6">
|
className="appearance-none py-4 text-blue-600 border-b border-blue-dark mr-6">
|
||||||
Bitcoin
|
Bitcoin
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex text-sm">
|
<div className="flex text-sm">
|
||||||
<DateButton key={PeriodUnit.MINUTE} label={"1m"}
|
<DateButton key={PeriodUnit.MINUTE} label={"1m"}
|
||||||
onClick={() => this.changeProfitLossPeriod(1, PeriodUnit.MINUTE)}/>
|
onClick={() => this.changeProfitLossPeriod(1, PeriodUnit.MINUTE)} />
|
||||||
<DateButton key={PeriodUnit.DAY} label={"1D"}
|
<DateButton key={PeriodUnit.DAY} label={"1D"}
|
||||||
onClick={() => this.changeProfitLossPeriod(1, PeriodUnit.DAY)}/>
|
onClick={() => this.changeProfitLossPeriod(1, PeriodUnit.DAY)} />
|
||||||
<DateButton key={PeriodUnit.WEEK} label={"1W"} selected_default={true}
|
<DateButton key={PeriodUnit.WEEK} label={"1W"} selected_default={true}
|
||||||
onClick={() => this.changeProfitLossPeriod(1, PeriodUnit.WEEK)}/>
|
onClick={() => this.changeProfitLossPeriod(1, PeriodUnit.WEEK)} />
|
||||||
<DateButton key={PeriodUnit.MONTH} label={"1M"}
|
<DateButton key={PeriodUnit.MONTH} label={"1M"}
|
||||||
onClick={() => this.changeProfitLossPeriod(1, PeriodUnit.MONTH)}/>
|
onClick={() => this.changeProfitLossPeriod(1, PeriodUnit.MONTH)} />
|
||||||
<DateButton key={PeriodUnit.YEAR} label={"1Y"}
|
<DateButton key={PeriodUnit.YEAR} label={"1Y"}
|
||||||
onClick={() => this.changeProfitLossPeriod(1, PeriodUnit.YEAR)}/>
|
onClick={() => this.changeProfitLossPeriod(1, PeriodUnit.YEAR)} />
|
||||||
{/*<DateButton label={"ALL"} onClick={() => this.changeProfitLossPeriod(1, PeriodUnit.MINUTE)}/>*/}
|
{/*<DateButton label={"ALL"} onClick={() => this.changeProfitLossPeriod(1, PeriodUnit.MINUTE)}/>*/}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -260,8 +271,8 @@ export class Statusbar extends Component<NewTickMessage, StatusBarState> {
|
|||||||
</select>
|
</select>
|
||||||
<div className="pointer-events-none absolute pin-y pin-r flex items-center px-2 text-gray-300">
|
<div className="pointer-events-none absolute pin-y pin-r flex items-center px-2 text-gray-300">
|
||||||
<svg className="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg"
|
<svg className="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg"
|
||||||
viewBox="0 0 20 20">
|
viewBox="0 0 20 20">
|
||||||
<path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z"/>
|
<path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z" />
|
||||||
</svg>
|
</svg>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -270,20 +281,20 @@ export class Statusbar extends Component<NewTickMessage, StatusBarState> {
|
|||||||
<div className="w-1/3 text-center py-8">
|
<div className="w-1/3 text-center py-8">
|
||||||
<div className="border-r">
|
<div className="border-r">
|
||||||
<QuoteStatus key={this.props.price} quote_symbol={"USD"} amount={this.props.price}
|
<QuoteStatus key={this.props.price} quote_symbol={"USD"} amount={this.props.price}
|
||||||
subtitle={"Bitcoin price"}/>
|
subtitle={"Bitcoin price"} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="w-1/3 text-center py-8">
|
<div className="w-1/3 text-center py-8">
|
||||||
<div className="border-r">
|
<div className="border-r">
|
||||||
<QuoteStatus key={this.state.pl} quote_symbol={"USD"} sign={true} amount={this.state.pl}
|
<QuoteStatus key={this.state.pl} quote_symbol={"USD"} sign={true} amount={this.state.pl}
|
||||||
subtitle={"since last ".concat(this.state.pl_period_unit)}/>
|
subtitle={"since last ".concat(this.state.pl_period_unit)} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="w-1/3 text-center py-8">
|
<div className="w-1/3 text-center py-8">
|
||||||
<div>
|
<div>
|
||||||
<QuoteStatus key={this.state.pl_perc} percentage={true} sign={true}
|
<QuoteStatus key={this.state.pl_perc} percentage={true} sign={true}
|
||||||
amount={this.state.pl_perc}
|
amount={this.state.pl_perc}
|
||||||
subtitle={"since last ".concat(this.state.pl_period_unit)}/>
|
subtitle={"since last ".concat(this.state.pl_period_unit)} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
@ -1,6 +1,6 @@
|
|||||||
import React, {Component} from "react"
|
import React, { Component } from "react"
|
||||||
import {PositionProp} from "../types";
|
import { PositionProp } from "../types";
|
||||||
import {ClosePositionModal} from "./Overlays";
|
import { ClosePositionModal } from "./Overlays";
|
||||||
|
|
||||||
type PositionsTableState = {
|
type PositionsTableState = {
|
||||||
showConfirmation: boolean,
|
showConfirmation: boolean,
|
||||||
@ -8,7 +8,7 @@ type PositionsTableState = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class PositionsTable extends Component<{ positions: Array<PositionProp> }, PositionsTableState> {
|
export class PositionsTable extends Component<{ positions: Array<PositionProp> }, PositionsTableState> {
|
||||||
constructor(props) {
|
constructor(props: { positions: PositionProp[]; } | Readonly<{ positions: PositionProp[]; }>) {
|
||||||
super(props);
|
super(props);
|
||||||
this.toggleConfirmation = this.toggleConfirmation.bind(this)
|
this.toggleConfirmation = this.toggleConfirmation.bind(this)
|
||||||
}
|
}
|
||||||
@ -42,13 +42,13 @@ export class PositionsTable extends Component<{ positions: Array<PositionProp> }
|
|||||||
|
|
||||||
renderTableHead() {
|
renderTableHead() {
|
||||||
return ["status", "currency pair", "base price", "amount", "Profit/Loss", "actions"].map((entry) => {
|
return ["status", "currency pair", "base price", "amount", "Profit/Loss", "actions"].map((entry) => {
|
||||||
return (
|
return (
|
||||||
<th scope="col"
|
<th scope="col"
|
||||||
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||||
{entry}
|
{entry}
|
||||||
</th>
|
</th>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -65,7 +65,7 @@ export class PositionsTable extends Component<{ positions: Array<PositionProp> }
|
|||||||
<td className="px-6 py-4 whitespace-nowrap">
|
<td className="px-6 py-4 whitespace-nowrap">
|
||||||
<span
|
<span
|
||||||
className={stateClass}>
|
className={stateClass}>
|
||||||
{position.state}
|
{position.state}
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
|
|
||||||
@ -115,20 +115,20 @@ export class PositionsTable extends Component<{ positions: Array<PositionProp> }
|
|||||||
return (
|
return (
|
||||||
<div className="flex flex-col">
|
<div className="flex flex-col">
|
||||||
<ClosePositionModal positionId={this.state.positionToClose} toggleConfirmation={this.toggleConfirmation}
|
<ClosePositionModal positionId={this.state.positionToClose} toggleConfirmation={this.toggleConfirmation}
|
||||||
show={this.state.showConfirmation}/>
|
show={this.state.showConfirmation} />
|
||||||
<div className="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
|
<div className="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
|
||||||
<div className="py-2 align-middle inline-block min-w-full sm:px-6 lg:px-8">
|
<div className="py-2 align-middle inline-block min-w-full sm:px-6 lg:px-8">
|
||||||
<div className="shadow overflow-hidden border-b border-gray-200 sm:rounded-lg">
|
<div className="shadow overflow-hidden border-b border-gray-200 sm:rounded-lg">
|
||||||
<table className="min-w-full divide-y divide-gray-200">
|
<table className="min-w-full divide-y divide-gray-200">
|
||||||
|
|
||||||
<thead className="bg-gray-50">
|
<thead className="bg-gray-50">
|
||||||
<tr>
|
<tr>
|
||||||
{this.renderTableHead()}
|
{this.renderTableHead()}
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
|
|
||||||
<tbody className="bg-white divide-y divide-gray-200">
|
<tbody className="bg-white divide-y divide-gray-200">
|
||||||
{this.renderTableRows()}
|
{this.renderTableRows()}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
1
websrc/src/custom.d.ts
vendored
Normal file
1
websrc/src/custom.d.ts
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
declare module 'react-cryptocoins';
|
@ -4,10 +4,12 @@ import "./css/tailwind.css";
|
|||||||
import App from "./components/App";
|
import App from "./components/App";
|
||||||
import io from "socket.io-client";
|
import io from "socket.io-client";
|
||||||
|
|
||||||
export const socket = io();
|
export const socket = io.io();
|
||||||
|
|
||||||
socket.on("connect", function () {
|
socket.on("connect", function () {
|
||||||
console.log("Connected!")
|
console.log("Connected!")
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const ws = new WebSocket('ws://localhost:8080');
|
||||||
|
|
||||||
ReactDOM.render(<App/>, document.getElementById("root"));
|
ReactDOM.render(<App/>, document.getElementById("root"));
|
1
websrc/src/react-app-env.d.ts
vendored
Normal file
1
websrc/src/react-app-env.d.ts
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
/// <reference types="react-scripts" />
|
@ -1,4 +1,3 @@
|
|||||||
import {EventProp} from "./components/Events";
|
|
||||||
|
|
||||||
/*******************************
|
/*******************************
|
||||||
* Types
|
* Types
|
||||||
@ -18,6 +17,12 @@ export type CurrencyPair = {
|
|||||||
quote: string
|
quote: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type EventProp = {
|
||||||
|
id: number,
|
||||||
|
name: string,
|
||||||
|
tick: number
|
||||||
|
}
|
||||||
|
|
||||||
export type FirstConnectMessage = {
|
export type FirstConnectMessage = {
|
||||||
ticks: Array<number>,
|
ticks: Array<number>,
|
||||||
prices: Array<number>,
|
prices: Array<number>,
|
@ -1,12 +1,16 @@
|
|||||||
import {CurrencyPair} from "./types";
|
import { CurrencyPair } from "./types";
|
||||||
// import * as Icon from 'react-cryptocoins'
|
// import * as Icon from 'react-cryptocoins'
|
||||||
import {Btc, Eth, Xmr} from 'react-cryptocoins';
|
import { Btc, Eth, Xmr } from 'react-cryptocoins';
|
||||||
|
|
||||||
export function symbolToPair(symbol: string): CurrencyPair {
|
export function symbolToPair(symbol: string): CurrencyPair {
|
||||||
const symbol_regex = "t(?<base>[a-zA-Z]{3})(?<quote>[a-zA-Z]{3})"
|
const symbol_regex = "t(?<base>[a-zA-Z]{3})(?<quote>[a-zA-Z]{3})"
|
||||||
|
|
||||||
const match = symbol.match(symbol_regex)
|
const match = symbol.match(symbol_regex)
|
||||||
|
|
||||||
|
if (!match?.groups) {
|
||||||
|
return { base: "undefined", quote: "undefined" }
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
base: match.groups.base,
|
base: match.groups.base,
|
||||||
quote: match.groups.quote
|
quote: match.groups.quote
|
@ -1,12 +1,29 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"lib": ["esnext", "DOM"],
|
"target": "es5",
|
||||||
"jsx": "react",
|
"lib": [
|
||||||
"moduleResolution": "node",
|
"dom",
|
||||||
"allowSyntheticDefaultImports": true,
|
"dom.iterable",
|
||||||
"esModuleInterop": true,
|
"esnext"
|
||||||
},
|
|
||||||
"exclude": [
|
|
||||||
"node_modules"
|
|
||||||
],
|
],
|
||||||
}
|
"allowJs": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
|
"strict": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"module": "esnext",
|
||||||
|
"moduleResolution": "node",
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"jsx": "react-jsx"
|
||||||
|
},
|
||||||
|
"include": [
|
||||||
|
"src"
|
||||||
|
],
|
||||||
|
"exclude": [
|
||||||
|
"node_modules"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
7966
websrc/yarn.lock
7966
websrc/yarn.lock
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue
Block a user