Compare commits
3 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
27aea7d0c1 | ||
|
b8f239ec31 | ||
|
7014917acb |
80
Cargo.lock → rustybot/Cargo.lock
generated
80
Cargo.lock → rustybot/Cargo.lock
generated
@ -2,9 +2,9 @@
|
||||
# It is not intended for manual editing.
|
||||
[[package]]
|
||||
name = "addr2line"
|
||||
version = "0.14.1"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a55f82cfe485775d02112886f4169bde0c5894d75e79ead7eafe7e40a25e45f7"
|
||||
checksum = "7c0929d69e78dd9bf5408269919fcbcaeb2e35e5d43e5815517cdc6a8e11a423"
|
||||
dependencies = [
|
||||
"gimli",
|
||||
]
|
||||
@ -75,9 +75,9 @@ checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"
|
||||
|
||||
[[package]]
|
||||
name = "backtrace"
|
||||
version = "0.3.56"
|
||||
version = "0.3.55"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9d117600f438b1707d4e4ae15d3595657288f8235a0eb593e80ecc98ab34e1bc"
|
||||
checksum = "ef5140344c85b01f9bbb4d4b7288a8aa4b3287ccef913a14bcc78a1063623598"
|
||||
dependencies = [
|
||||
"addr2line",
|
||||
"cfg-if 1.0.0",
|
||||
@ -109,7 +109,7 @@ dependencies = [
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
"tungstenite 0.13.0",
|
||||
"tungstenite",
|
||||
"url",
|
||||
]
|
||||
|
||||
@ -225,29 +225,12 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dotenv"
|
||||
version = "0.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77c90badedccf4105eca100756a0b1289e191f6fcbdadd3cee1d2f614f97da8f"
|
||||
|
||||
[[package]]
|
||||
name = "dyn-clone"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ee2626afccd7561a06cf1367e2950c4718ea04565e20fb5029b6c7d8ad09abcf"
|
||||
|
||||
[[package]]
|
||||
name = "ears"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e741c53078ec208f07c837fca26cd2624f959140c52268ee0677ad3b8e9b2112"
|
||||
dependencies = [
|
||||
"lazy_static",
|
||||
"libc",
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "encoding_rs"
|
||||
version = "0.8.26"
|
||||
@ -802,9 +785,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "object"
|
||||
version = "0.23.0"
|
||||
version = "0.22.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a9a7ab5d64814df0fe4a4b5ead45ed6c5f181ee3ff04ba344313a6c80446c5d4"
|
||||
checksum = "8d3b63360ec3cb337817c2dbd47ab4a0f170d285d8e5a2064600f3def1402397"
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
@ -1170,16 +1153,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e3bad0ee36814ca07d7968269dd4b7ec89ec2da10c4bb613928d3077083c232"
|
||||
|
||||
[[package]]
|
||||
name = "rustico"
|
||||
name = "rustybot"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"bitfinex",
|
||||
"byteorder",
|
||||
"chrono",
|
||||
"dotenv",
|
||||
"dyn-clone",
|
||||
"ears",
|
||||
"fern",
|
||||
"float-cmp",
|
||||
"futures-retry",
|
||||
@ -1189,7 +1170,7 @@ dependencies = [
|
||||
"regex",
|
||||
"tokio",
|
||||
"tokio-tungstenite",
|
||||
"tungstenite 0.12.0",
|
||||
"tungstenite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -1353,26 +1334,6 @@ dependencies = [
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e0f4a65597094d4483ddaed134f409b2cb7c1beccf25201a9f73c719254fa98e"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7765189610d8241a44529806d6fd1f2e0a08734313a35d5b3a556f92b381f3c0"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thread_local"
|
||||
version = "1.0.1"
|
||||
@ -1470,7 +1431,7 @@ dependencies = [
|
||||
"log 0.4.11",
|
||||
"pin-project 1.0.2",
|
||||
"tokio",
|
||||
"tungstenite 0.12.0",
|
||||
"tungstenite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -1551,27 +1512,6 @@ dependencies = [
|
||||
"utf-8",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tungstenite"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5fe8dada8c1a3aeca77d6b51a4f1314e0f4b8e438b7b1b71e3ddaca8080e4093"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"byteorder",
|
||||
"bytes 1.0.1",
|
||||
"http",
|
||||
"httparse",
|
||||
"input_buffer",
|
||||
"log 0.4.11",
|
||||
"native-tls",
|
||||
"rand 0.8.2",
|
||||
"sha-1",
|
||||
"thiserror",
|
||||
"url",
|
||||
"utf-8",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.12.0"
|
@ -1,5 +1,5 @@
|
||||
[package]
|
||||
name = "rustico"
|
||||
name = "rustybot"
|
||||
version = "0.1.0"
|
||||
authors = ["Giulio De Pasquale <depasquale@giugl.io>"]
|
||||
edition = "2018"
|
||||
@ -21,6 +21,4 @@ float-cmp = "0.8"
|
||||
merge = "0.1"
|
||||
futures-retry = "0.6"
|
||||
tungstenite = "0.12"
|
||||
tokio-tungstenite = "0.13"
|
||||
dotenv = "0.15"
|
||||
ears = "0.8.0"
|
||||
tokio-tungstenite = "0.13"
|
@ -3,32 +3,37 @@ use core::time::Duration;
|
||||
use log::{error, info};
|
||||
use tokio::time::sleep;
|
||||
|
||||
use crate::BoxError;
|
||||
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 Rustico {
|
||||
pub struct BfxBot {
|
||||
ticker: Ticker,
|
||||
exchange_managers: Vec<ExchangeManager>,
|
||||
frontend_connector: FrontendManagerHandle,
|
||||
}
|
||||
|
||||
impl Rustico {
|
||||
// TODO: change constructor to take SymbolPairs and not Symbol
|
||||
impl BfxBot {
|
||||
pub fn new(
|
||||
exchanges: Vec<ExchangeDetails>,
|
||||
trading_pairs: Vec<SymbolPair>,
|
||||
trading_symbols: Vec<Symbol>,
|
||||
quote: Symbol,
|
||||
tick_duration: Duration,
|
||||
) -> Self {
|
||||
let exchange_managers = exchanges
|
||||
let pairs: Vec<_> = trading_symbols
|
||||
.iter()
|
||||
.map(|x| ExchangeManager::new(x, &trading_pairs))
|
||||
.map(|x| SymbolPair::new(quote.clone(), x.clone()))
|
||||
.collect();
|
||||
|
||||
Rustico {
|
||||
let exchange_managers = exchanges
|
||||
.iter()
|
||||
.map(|x| ExchangeManager::new(x, &pairs))
|
||||
.collect();
|
||||
|
||||
BfxBot {
|
||||
ticker: Ticker::new(tick_duration),
|
||||
exchange_managers,
|
||||
frontend_connector: FrontendManagerHandle::new(),
|
@ -4,23 +4,22 @@ use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use bitfinex::api::RestClient;
|
||||
use bitfinex::api::Bitfinex;
|
||||
use bitfinex::book::BookPrecision;
|
||||
use bitfinex::orders::{CancelOrderForm, OrderMeta};
|
||||
use bitfinex::responses::{OrderResponse, TradeResponse};
|
||||
use bitfinex::ticker::TradingPairTicker;
|
||||
use bitfinex::websockets::WebSocketClient;
|
||||
use futures_retry::RetryPolicy;
|
||||
use log::trace;
|
||||
use tokio::macros::support::Future;
|
||||
use tokio::time::Duration;
|
||||
|
||||
use crate::BoxError;
|
||||
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 {
|
||||
@ -37,7 +36,7 @@ pub enum ExchangeDetails {
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Client {
|
||||
exchange: Exchange,
|
||||
inner: Arc<Box<dyn RestConnector>>,
|
||||
inner: Arc<Box<dyn Connector>>,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
@ -124,7 +123,7 @@ impl Client {
|
||||
.active_orders(pair)
|
||||
.await?
|
||||
.into_iter()
|
||||
.filter(|x| x.pair() == pair)
|
||||
.filter(|x| &x.pair() == &pair)
|
||||
.collect())
|
||||
}
|
||||
|
||||
@ -165,13 +164,10 @@ impl Client {
|
||||
) -> Result<Option<Vec<OrderDetails>>, BoxError> {
|
||||
self.inner.orders_history(pair).await
|
||||
}
|
||||
|
||||
pub async fn trading_fees(&self) -> Result<Vec<TradingFees>, BoxError> { self.inner.trading_fees().await }
|
||||
}
|
||||
|
||||
/// This trait represents a REST API service.
|
||||
#[async_trait]
|
||||
pub trait RestConnector: Send + Sync {
|
||||
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>;
|
||||
@ -187,7 +183,7 @@ pub trait RestConnector: Send + Sync {
|
||||
amount: f64,
|
||||
) -> Result<(), BoxError>;
|
||||
async fn trades_from_order(&self, order: &OrderDetails)
|
||||
-> Result<Option<Vec<Trade>>, BoxError>;
|
||||
-> Result<Option<Vec<Trade>>, BoxError>;
|
||||
async fn orders_history(
|
||||
&self,
|
||||
pair: &SymbolPair,
|
||||
@ -195,26 +191,18 @@ pub trait RestConnector: Send + Sync {
|
||||
async fn trading_fees(&self) -> Result<Vec<TradingFees>, BoxError>;
|
||||
}
|
||||
|
||||
impl Debug for dyn RestConnector {
|
||||
impl Debug for dyn Connector {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
|
||||
write!(f, "{}", self.name())
|
||||
}
|
||||
}
|
||||
|
||||
/// This trait represents a WebSocket API service.
|
||||
#[async_trait]
|
||||
pub trait WebSocketConnector: Send + Sync {
|
||||
fn name(&self) -> String;
|
||||
async fn connect(&self) -> Result<(), BoxError>;
|
||||
}
|
||||
|
||||
/**************
|
||||
* BITFINEX
|
||||
**************/
|
||||
|
||||
pub struct BitfinexConnector {
|
||||
rest: bitfinex::api::RestClient,
|
||||
ws: bitfinex::websockets::WebSocketClient,
|
||||
bfx: Bitfinex,
|
||||
}
|
||||
|
||||
impl BitfinexConnector {
|
||||
@ -229,8 +217,7 @@ impl BitfinexConnector {
|
||||
|
||||
pub fn new(api_key: &str, api_secret: &str) -> Self {
|
||||
BitfinexConnector {
|
||||
rest: RestClient::new(Some(api_key.into()), Some(api_secret.into())),
|
||||
ws: WebSocketClient::new(),
|
||||
bfx: Bitfinex::new(Some(api_key.into()), Some(api_secret.into())),
|
||||
}
|
||||
}
|
||||
|
||||
@ -248,9 +235,9 @@ impl BitfinexConnector {
|
||||
// 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>>,
|
||||
where
|
||||
F: FnMut() -> Fut,
|
||||
Fut: Future<Output = Result<O, BoxError>>,
|
||||
{
|
||||
let response = {
|
||||
loop {
|
||||
@ -271,14 +258,14 @@ impl BitfinexConnector {
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl RestConnector for BitfinexConnector {
|
||||
impl Connector for BitfinexConnector {
|
||||
fn name(&self) -> String {
|
||||
"Bitfinex REST".into()
|
||||
"Bitfinex".into()
|
||||
}
|
||||
|
||||
async fn active_positions(&self, pair: &SymbolPair) -> Result<Option<Vec<Position>>, BoxError> {
|
||||
let active_positions =
|
||||
BitfinexConnector::retry_nonce(|| self.rest.positions.active_positions()).await?;
|
||||
BitfinexConnector::retry_nonce(|| self.bfx.positions.active_positions()).await?;
|
||||
|
||||
let positions: Vec<_> = active_positions
|
||||
.into_iter()
|
||||
@ -286,14 +273,14 @@ impl RestConnector for BitfinexConnector {
|
||||
.filter(|x: &Position| x.pair() == pair)
|
||||
.collect();
|
||||
|
||||
trace!("\tRetrieved positions for {}", pair);
|
||||
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.rest.ticker.trading_pair(symbol_name).await?;
|
||||
let ticker: TradingPairTicker = self.bfx.ticker.trading_pair(symbol_name).await?;
|
||||
|
||||
Ok(ticker)
|
||||
}
|
||||
@ -302,9 +289,9 @@ impl RestConnector for BitfinexConnector {
|
||||
let symbol_name = BitfinexConnector::format_trading_pair(pair);
|
||||
|
||||
let response = BitfinexConnector::retry_nonce(|| {
|
||||
self.rest.book.trading_pair(&symbol_name, BookPrecision::P0)
|
||||
self.bfx.book.trading_pair(&symbol_name, BookPrecision::P0)
|
||||
})
|
||||
.await?;
|
||||
.await?;
|
||||
|
||||
let entries = response
|
||||
.into_iter()
|
||||
@ -319,7 +306,7 @@ impl RestConnector for BitfinexConnector {
|
||||
}
|
||||
|
||||
async fn active_orders(&self, _: &SymbolPair) -> Result<Vec<ActiveOrder>, BoxError> {
|
||||
let response = BitfinexConnector::retry_nonce(|| self.rest.orders.active_orders()).await?;
|
||||
let response = BitfinexConnector::retry_nonce(|| self.bfx.orders.active_orders()).await?;
|
||||
|
||||
Ok(response.iter().map(Into::into).collect())
|
||||
}
|
||||
@ -329,53 +316,57 @@ impl RestConnector for BitfinexConnector {
|
||||
let amount = order.amount();
|
||||
|
||||
let order_form = {
|
||||
match order.kind() {
|
||||
OrderKind::Limit { price } => {
|
||||
bitfinex::orders::OrderForm::new(symbol_name, price, amount, order.into())
|
||||
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())
|
||||
}
|
||||
}
|
||||
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 { stop_price: price, limit_price } => {
|
||||
bitfinex::orders::OrderForm::new(symbol_name, price, amount, order.into())
|
||||
.with_price_aux_limit(Some(limit_price))?
|
||||
}
|
||||
OrderKind::TrailingStop { distance } => {
|
||||
bitfinex::orders::OrderForm::new(symbol_name, 0.0, amount, order.into())
|
||||
.with_price_trailing(Some(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(Some(OrderMeta::new(
|
||||
.with_meta(OrderMeta::new(
|
||||
BitfinexConnector::AFFILIATE_CODE.to_string(),
|
||||
)))
|
||||
// TODO: CHANGEME!
|
||||
.with_leverage(Some(15))
|
||||
))
|
||||
};
|
||||
|
||||
// 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.rest.orders.submit_order(&order_form)).await?;
|
||||
BitfinexConnector::retry_nonce(|| self.bfx.orders.submit_order(&order_form)).await?;
|
||||
|
||||
// parsing response into ActiveOrder and adding leverage from order form
|
||||
let order_response: ActiveOrder = (&response).try_into()?;
|
||||
|
||||
// TODO: CHANGEME!!!!
|
||||
Ok(order_response.with_leverage(Some(15.0)))
|
||||
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.rest.orders.cancel_order(&cancel_form)).await?;
|
||||
BitfinexConnector::retry_nonce(|| self.bfx.orders.cancel_order(&cancel_form)).await?;
|
||||
|
||||
Ok((&response).try_into()?)
|
||||
}
|
||||
@ -388,14 +379,14 @@ impl RestConnector for BitfinexConnector {
|
||||
amount: f64,
|
||||
) -> Result<(), BoxError> {
|
||||
BitfinexConnector::retry_nonce(|| {
|
||||
self.rest.account.transfer_between_wallets(
|
||||
self.bfx.account.transfer_between_wallets(
|
||||
from.into(),
|
||||
to.into(),
|
||||
symbol.to_string(),
|
||||
amount,
|
||||
)
|
||||
})
|
||||
.await?;
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@ -405,11 +396,11 @@ impl RestConnector for BitfinexConnector {
|
||||
order: &OrderDetails,
|
||||
) -> Result<Option<Vec<Trade>>, BoxError> {
|
||||
let response = BitfinexConnector::retry_nonce(|| {
|
||||
self.rest
|
||||
self.bfx
|
||||
.trades
|
||||
.generated_by_order(order.pair().trading_repr(), order.id())
|
||||
})
|
||||
.await?;
|
||||
.await?;
|
||||
|
||||
if response.is_empty() {
|
||||
Ok(None)
|
||||
@ -423,7 +414,7 @@ impl RestConnector for BitfinexConnector {
|
||||
pair: &SymbolPair,
|
||||
) -> Result<Option<Vec<OrderDetails>>, BoxError> {
|
||||
let response =
|
||||
BitfinexConnector::retry_nonce(|| self.rest.orders.history(Some(pair.trading_repr())))
|
||||
BitfinexConnector::retry_nonce(|| self.bfx.orders.history(Some(pair.trading_repr())))
|
||||
.await?;
|
||||
let mapped_vec: Vec<_> = response.iter().map(Into::into).collect();
|
||||
|
||||
@ -433,7 +424,7 @@ impl RestConnector for BitfinexConnector {
|
||||
async fn trading_fees(&self) -> Result<Vec<TradingFees>, BoxError> {
|
||||
let mut fees = vec![];
|
||||
let accountfees =
|
||||
BitfinexConnector::retry_nonce(|| self.rest.account.account_summary()).await?;
|
||||
BitfinexConnector::retry_nonce(|| self.bfx.account.account_summary()).await?;
|
||||
|
||||
// Derivatives
|
||||
let derivative_taker = TradingFees::Taker {
|
||||
@ -475,17 +466,6 @@ impl RestConnector for BitfinexConnector {
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl WebSocketConnector for BitfinexConnector {
|
||||
fn name(&self) -> String {
|
||||
"Bitfinex WS".into()
|
||||
}
|
||||
|
||||
async fn connect(&self) -> Result<(), BoxError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&ActiveOrder> for CancelOrderForm {
|
||||
fn from(o: &ActiveOrder) -> Self {
|
||||
Self::from_id(o.id())
|
||||
@ -506,8 +486,8 @@ impl TryFrom<&bitfinex::responses::OrderResponse> for ActiveOrder {
|
||||
response.mts_create(),
|
||||
response.mts_update(),
|
||||
)
|
||||
.with_group_id(response.gid())
|
||||
.with_client_id(Some(response.cid())))
|
||||
.with_group_id(response.gid())
|
||||
.with_client_id(Some(response.cid())))
|
||||
}
|
||||
}
|
||||
|
||||
@ -531,6 +511,7 @@ impl TryInto<Position> for bitfinex::positions::Position {
|
||||
}
|
||||
};
|
||||
|
||||
println!("leverage: {}", self.leverage());
|
||||
Ok(Position::new(
|
||||
SymbolPair::from_str(self.symbol())?,
|
||||
state,
|
||||
@ -543,8 +524,8 @@ impl TryInto<Position> for bitfinex::positions::Position {
|
||||
platform,
|
||||
self.leverage(),
|
||||
)
|
||||
.with_creation_date(self.mts_create())
|
||||
.with_creation_update(self.mts_update()))
|
||||
.with_creation_date(self.mts_create())
|
||||
.with_creation_update(self.mts_update()))
|
||||
}
|
||||
}
|
||||
|
||||
@ -622,7 +603,7 @@ impl From<&bitfinex::responses::OrderResponse> for OrderKind {
|
||||
}
|
||||
bitfinex::orders::OrderKind::StopLimit
|
||||
| bitfinex::orders::OrderKind::ExchangeStopLimit => Self::StopLimit {
|
||||
stop_price: response.price(),
|
||||
price: response.price(),
|
||||
limit_price: response.price_aux_limit().expect("Limit price not found!"),
|
||||
},
|
||||
bitfinex::orders::OrderKind::TrailingStop
|
||||
@ -661,7 +642,7 @@ impl From<&bitfinex::orders::ActiveOrder> for OrderKind {
|
||||
}
|
||||
bitfinex::orders::OrderKind::StopLimit
|
||||
| bitfinex::orders::OrderKind::ExchangeStopLimit => Self::StopLimit {
|
||||
stop_price: response.price(),
|
||||
price: response.price(),
|
||||
limit_price: response.price_aux_limit().expect("Limit price not found!"),
|
||||
},
|
||||
bitfinex::orders::OrderKind::TrailingStop
|
||||
@ -694,8 +675,8 @@ impl From<&bitfinex::orders::ActiveOrder> for ActiveOrder {
|
||||
order.creation_timestamp(),
|
||||
order.update_timestamp(),
|
||||
)
|
||||
.with_client_id(Some(order.client_id()))
|
||||
.with_group_id(order.group_id())
|
||||
.with_client_id(Some(order.client_id()))
|
||||
.with_group_id(order.group_id())
|
||||
}
|
||||
}
|
||||
|
@ -13,8 +13,8 @@ pub struct Symbol {
|
||||
}
|
||||
|
||||
impl<S> From<S> for Symbol
|
||||
where
|
||||
S: Into<String>,
|
||||
where
|
||||
S: Into<String>,
|
||||
{
|
||||
fn from(item: S) -> Self {
|
||||
Symbol::new(item.into())
|
||||
@ -31,8 +31,6 @@ impl Symbol {
|
||||
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");
|
||||
pub const DERIV_ADA: Symbol = Symbol::new_static("ADAF0");
|
||||
pub const DERIV_POLKADOT: Symbol = Symbol::new_static("DOTF0");
|
||||
|
||||
// Paper trading
|
||||
pub const TESTBTC: Symbol = Symbol::new_static("TESTBTC");
|
||||
@ -76,8 +74,8 @@ pub struct SymbolPair {
|
||||
}
|
||||
|
||||
impl SymbolPair {
|
||||
pub fn new(base: Symbol, quote: Symbol) -> Self {
|
||||
SymbolPair { base, quote }
|
||||
pub fn new(quote: Symbol, base: Symbol) -> Self {
|
||||
SymbolPair { quote, base }
|
||||
}
|
||||
pub fn trading_repr(&self) -> String {
|
||||
format!("t{}{}", self.base, self.quote)
|
@ -56,19 +56,14 @@ pub struct Event {
|
||||
}
|
||||
|
||||
impl Event {
|
||||
pub fn new(kind: EventKind, tick: u64) -> Self {
|
||||
pub fn new(kind: EventKind, tick: u64, metadata: Option<EventMetadata>) -> Self {
|
||||
Event {
|
||||
kind,
|
||||
tick,
|
||||
metadata: None,
|
||||
metadata,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_metadata(mut self, metadata: Option<EventMetadata>) -> Self {
|
||||
self.metadata = metadata;
|
||||
self
|
||||
}
|
||||
|
||||
fn has_metadata(&self) -> bool {
|
||||
self.metadata.is_some()
|
||||
}
|
@ -1,15 +1,16 @@
|
||||
use std::net::SocketAddr;
|
||||
use log::info;
|
||||
use tokio::sync::mpsc::{channel, Receiver, Sender};
|
||||
|
||||
use crate::events::{ActorMessage, Message};
|
||||
use crate::BoxError;
|
||||
use futures_util::stream::TryStreamExt;
|
||||
use futures_util::StreamExt;
|
||||
use log::info;
|
||||
use std::collections::HashMap;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
use tokio::sync::mpsc::{channel, Receiver, Sender};
|
||||
use tokio_tungstenite::accept_async;
|
||||
|
||||
use crate::BoxError;
|
||||
use crate::events::ActorMessage;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct FrontendManager {
|
||||
receiver: Receiver<ActorMessage>,
|
||||
@ -21,10 +22,10 @@ impl FrontendManager {
|
||||
}
|
||||
|
||||
async fn handle_ws_connection(stream: TcpStream, addr: SocketAddr) -> Result<(), BoxError> {
|
||||
let websocket = accept_async(stream).await?;
|
||||
let mut websocket = accept_async(stream).await?;
|
||||
info!("Received WebSocket connection <{:?}>", addr);
|
||||
|
||||
let (_, ws_in) = websocket.split();
|
||||
let (ws_out, ws_in) = websocket.split();
|
||||
|
||||
let on_received = ws_in.try_for_each(move |msg| {
|
||||
info!(
|
||||
@ -68,21 +69,21 @@ pub struct FrontendManagerHandle {
|
||||
}
|
||||
|
||||
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();
|
||||
// }
|
||||
// }
|
||||
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);
|
||||
let frontend = FrontendManager::new(receiver);
|
||||
|
||||
tokio::spawn(FrontendManager::websocket());
|
||||
// tokio::spawn(FrontendManagerHandle::run_frontend_manager(frontend));
|
||||
tokio::spawn(FrontendManagerHandle::run_frontend_manager(frontend));
|
||||
|
||||
Self { sender }
|
||||
}
|
78
rustybot/src/main.rs
Normal file
78
rustybot/src/main.rs
Normal file
@ -0,0 +1,78 @@
|
||||
#![feature(drain_filter)]
|
||||
#![feature(bool_to_option)]
|
||||
|
||||
use std::env;
|
||||
|
||||
use fern::colors::{Color, ColoredLevelConfig};
|
||||
use log::LevelFilter::{Debug, 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 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(())
|
||||
}
|
@ -1,22 +1,23 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
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::{Receiver, Sender};
|
||||
use tokio::sync::mpsc::channel;
|
||||
use tokio::sync::mpsc::{Receiver, Sender};
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::time::Duration;
|
||||
|
||||
use crate::BoxError;
|
||||
use crate::connectors::{Client, ExchangeDetails};
|
||||
use crate::currency::SymbolPair;
|
||||
use crate::events::{ActionMessage, ActorMessage, Event};
|
||||
use crate::models::{ActiveOrder, OrderBook, OrderForm, OrderKind, OrderMetadata, Position, PriceTicker};
|
||||
use crate::sounds::{MARKET_ORDER_PLACED_PATH, play_sound};
|
||||
use crate::strategy::{MarketEnforce, PositionStrategy, TrailingStop};
|
||||
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>>);
|
||||
|
||||
@ -233,9 +234,8 @@ impl PositionManager {
|
||||
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;
|
||||
let (fees, opt_active_positions) = tokio::join!(self.client.trading_fees(),self.client.active_positions(&self.pair));
|
||||
let (fees, opt_active_positions) = (fees?, opt_active_positions?);
|
||||
|
||||
// we assume there is only ONE active position per pair
|
||||
match opt_active_positions {
|
||||
@ -258,11 +258,11 @@ impl PositionManager {
|
||||
|
||||
let (pos_on_tick, events_on_tick, messages_on_tick) = self
|
||||
.strategy
|
||||
.on_tick(position, self.current_tick(), &self.positions_history, &fees);
|
||||
.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, &fees);
|
||||
.post_tick(pos_on_tick, self.current_tick(), &self.positions_history);
|
||||
|
||||
events.merge(events_on_tick);
|
||||
events.merge(events_post_tick);
|
||||
@ -280,12 +280,30 @@ impl PositionManager {
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
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>,
|
||||
}
|
||||
@ -311,10 +329,10 @@ impl OrderManagerHandle {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new(pair: SymbolPair, client: Client) -> Self {
|
||||
pub fn new(pair: SymbolPair, client: Client, strategy: Box<dyn OrderStrategy>) -> Self {
|
||||
let (sender, receiver) = channel(1);
|
||||
|
||||
let manager = OrderManager::new(receiver, pair, client);
|
||||
let manager = OrderManager::new(receiver, pair, client, strategy);
|
||||
|
||||
tokio::spawn(OrderManagerHandle::run_order_manager(manager));
|
||||
|
||||
@ -366,9 +384,11 @@ impl OrderManagerHandle {
|
||||
|
||||
pub struct OrderManager {
|
||||
receiver: Receiver<ActorMessage>,
|
||||
orders_map: HashMap<u64, HashSet<ActiveOrder>>,
|
||||
tracked_positions: TrackedPositionsMap,
|
||||
pair: SymbolPair,
|
||||
open_orders: Vec<ActiveOrder>,
|
||||
client: Client,
|
||||
strategy: Box<dyn OrderStrategy>,
|
||||
}
|
||||
|
||||
impl OrderManager {
|
||||
@ -376,93 +396,18 @@ impl OrderManager {
|
||||
receiver: Receiver<ActorMessage>,
|
||||
pair: SymbolPair,
|
||||
client: Client,
|
||||
strategy: Box<dyn OrderStrategy>,
|
||||
) -> Self {
|
||||
OrderManager {
|
||||
receiver,
|
||||
pair,
|
||||
open_orders: Vec::new(),
|
||||
client,
|
||||
orders_map: Default::default(),
|
||||
strategy,
|
||||
tracked_positions: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* PRIVATE METHODS
|
||||
*/
|
||||
|
||||
fn add_to_orders_map(&mut self, position_id: u64, order: ActiveOrder) -> bool {
|
||||
self.orders_map
|
||||
.entry(position_id)
|
||||
.or_default()
|
||||
.insert(order)
|
||||
}
|
||||
|
||||
fn orders_from_position_id(&self, position_id: u64) -> Option<&HashSet<ActiveOrder>> {
|
||||
self.orders_map.get(&position_id)
|
||||
}
|
||||
|
||||
fn all_tracked_orders(&self) -> Option<Vec<ActiveOrder>> {
|
||||
let orders: Vec<_> = self.orders_map.values().flat_map(|x| x.clone()).collect();
|
||||
|
||||
(!orders.is_empty()).then_some(orders)
|
||||
}
|
||||
|
||||
async fn update_orders_map_from_remote(&mut self) -> Result<(), BoxError> {
|
||||
let (res_remote_orders, res_remote_positions) = tokio::join!(self.client.active_orders(&self.pair),
|
||||
self.client.active_positions(&self.pair));
|
||||
let (remote_orders, remote_positions) = (res_remote_orders?, res_remote_positions?);
|
||||
|
||||
match remote_positions {
|
||||
// no positions open, clear internal mapping
|
||||
None => { self.orders_map.clear(); }
|
||||
Some(positions) => {
|
||||
// retain only positions that are open remotely as well
|
||||
self.orders_map.retain(|local_id, _| positions.iter().any(|r| r.id() == *local_id));
|
||||
|
||||
for position in positions {
|
||||
// mapping tracked orders to their ids
|
||||
let tracked_orders: Vec<_> = self.orders_from_position_id(position.id())
|
||||
.iter()
|
||||
.flat_map(|x| x
|
||||
.iter()
|
||||
.map(|x| x.id()))
|
||||
.collect();
|
||||
|
||||
// adding remote order that are not in the internal mapping
|
||||
for remote_order in remote_orders.iter().filter(|x| !tracked_orders.contains(&x.id())) {
|
||||
// the only check to bind an active order to an open position,
|
||||
// is to check for their amount which should be identical
|
||||
if (remote_order.order_form().amount().abs() - position.amount().abs()).abs() < 0.0001 {
|
||||
trace!("Adding order {} to internal mapping from remote.", remote_order.id());
|
||||
self.add_to_orders_map(position.id(), remote_order.clone());
|
||||
}
|
||||
}
|
||||
|
||||
// removing local orders that are not in remote
|
||||
for local_orders in self.orders_map.values_mut() {
|
||||
local_orders.retain(|l| remote_orders.iter().any(|r| r.id() == l.id()));
|
||||
}
|
||||
|
||||
// clean-up empty positions in local mapping
|
||||
let empty_positions_id: Vec<_> = self.orders_map
|
||||
.iter()
|
||||
.filter(|(_, orders)| orders.is_empty())
|
||||
.map(|(&position, _)| position)
|
||||
.collect();
|
||||
|
||||
for position_id in empty_positions_id {
|
||||
self.orders_map.remove(&position_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/*
|
||||
* PUBLIC METHODS
|
||||
*/
|
||||
|
||||
pub async fn handle_message(&mut self, msg: ActorMessage) -> Result<(), BoxError> {
|
||||
let (events, messages) = match msg.message {
|
||||
ActionMessage::Update { .. } => self.update().await?,
|
||||
@ -484,7 +429,14 @@ impl OrderManager {
|
||||
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.orders_map.get(&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()),
|
||||
@ -498,33 +450,25 @@ impl OrderManager {
|
||||
}
|
||||
|
||||
pub async fn submit_order(&mut self, order_form: &OrderForm) -> Result<OptionUpdate, BoxError> {
|
||||
info!("Submitting order: {}", order_form.kind());
|
||||
info!("Submiting {}", order_form.kind());
|
||||
|
||||
// adding strategy to order, if present in the metadata
|
||||
let active_order = {
|
||||
if let Some(metadata) = order_form.metadata() {
|
||||
// TODO: this seems extremely dirty. Double check!
|
||||
self.client.submit_order(order_form).await?.with_strategy(metadata.cloned_strategy())
|
||||
} else {
|
||||
self.client.submit_order(order_form).await?
|
||||
}
|
||||
};
|
||||
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() {
|
||||
debug!("Adding order to tracked orders.");
|
||||
|
||||
if !self.add_to_orders_map(position_id, active_order) {
|
||||
error!("Failed while adding order to internal mapping.");
|
||||
};
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// play sound if Market order is placed
|
||||
if let OrderKind::Market = order_form.kind() {
|
||||
play_sound(MARKET_ORDER_PLACED_PATH);
|
||||
}
|
||||
|
||||
// TODO: return valid messages and events!111!!!1!
|
||||
Ok((None, None))
|
||||
}
|
||||
@ -569,14 +513,10 @@ impl OrderManager {
|
||||
position.platform(),
|
||||
position.amount().neg(),
|
||||
)
|
||||
.with_leverage(Some(position.leverage()))
|
||||
.with_metadata(Some(OrderMetadata::new()
|
||||
.with_strategy(Some(Box::new(MarketEnforce::default())))
|
||||
.with_position_id(Some(position.id())))
|
||||
);
|
||||
.with_leverage(Some(position.leverage()));
|
||||
|
||||
// submitting order
|
||||
if let Err(e) = self.submit_order(&order_form).await {
|
||||
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(),
|
||||
@ -595,43 +535,47 @@ impl OrderManager {
|
||||
pub async fn update(&mut self) -> Result<OptionUpdate, BoxError> {
|
||||
debug!("\t[OrderManager] Updating {}", self.pair);
|
||||
|
||||
// updating internal orders' mapping from remote
|
||||
self.update_orders_map_from_remote().await?;
|
||||
let (res_open_orders, res_order_book) = tokio::join!(
|
||||
self.client.active_orders(&self.pair),
|
||||
self.client.order_book(&self.pair)
|
||||
);
|
||||
|
||||
// calling strategies for the orders and collecting resulting messages
|
||||
let _orders_messages: HashMap<&ActiveOrder, Vec<ActionMessage>> = HashMap::new();
|
||||
let (open_orders, order_book) = (res_open_orders?, res_order_book?);
|
||||
|
||||
if let Some(tracked_orders) = self.all_tracked_orders() {
|
||||
// since there are open orders, retrieve order book
|
||||
let order_book = self.client.order_book(&self.pair).await?;
|
||||
// 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?;
|
||||
|
||||
for active_order in tracked_orders.iter().filter(|x| x.strategy().is_some()) {
|
||||
let strategy = active_order.strategy().as_ref().unwrap();
|
||||
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());
|
||||
|
||||
trace!(
|
||||
"Found open order with \"{}\" strategy.",
|
||||
strategy.name()
|
||||
);
|
||||
|
||||
// executing the order's strategy and collecting its messages, if any
|
||||
let (_, strat_messages) = 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.submit_order(&order_form).await?;
|
||||
info!("Done!");
|
||||
// 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());
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
debug!(
|
||||
"Received unsupported message from order strategy. Unimplemented."
|
||||
)
|
||||
None => {
|
||||
trace!(
|
||||
"Mapped order #{} to position #{}",
|
||||
position.id(),
|
||||
matching_order.id()
|
||||
);
|
||||
self.tracked_positions
|
||||
.insert(position.id(), vec![matching_order.id()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -639,10 +583,39 @@ impl OrderManager {
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
@ -684,11 +657,12 @@ impl PairManager {
|
||||
order_manager: OrderManagerHandle::new(
|
||||
pair.clone(),
|
||||
client.clone(),
|
||||
Box::new(MarketEnforce::default()),
|
||||
),
|
||||
position_manager: PositionManagerHandle::new(
|
||||
pair,
|
||||
client,
|
||||
Box::new(TrailingStop::default()),
|
||||
Box::new(HiddenTrailingStop::default()),
|
||||
),
|
||||
}
|
||||
}
|
@ -2,11 +2,8 @@ use std::fmt;
|
||||
use std::fmt::{Display, Formatter};
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
use dyn_clone::clone_box;
|
||||
|
||||
use crate::connectors::Exchange;
|
||||
use crate::currency::{Symbol, SymbolPair};
|
||||
use crate::strategy::OrderStrategy;
|
||||
|
||||
/***************
|
||||
* Prices
|
||||
@ -151,7 +148,7 @@ impl OrderDetails {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ActiveOrder {
|
||||
exchange: Exchange,
|
||||
id: u64,
|
||||
@ -161,7 +158,6 @@ pub struct ActiveOrder {
|
||||
order_form: OrderForm,
|
||||
creation_timestamp: u64,
|
||||
update_timestamp: u64,
|
||||
strategy: Option<Box<dyn OrderStrategy>>,
|
||||
}
|
||||
|
||||
impl ActiveOrder {
|
||||
@ -182,7 +178,6 @@ impl ActiveOrder {
|
||||
order_form,
|
||||
creation_timestamp,
|
||||
update_timestamp,
|
||||
strategy: None,
|
||||
}
|
||||
}
|
||||
|
||||
@ -196,16 +191,6 @@ impl ActiveOrder {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_strategy(mut self, strategy: Option<Box<dyn OrderStrategy>>) -> Self {
|
||||
self.strategy = strategy;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_leverage(mut self, leverage: Option<f64>) -> Self {
|
||||
self.order_form = self.order_form.with_leverage(leverage);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn exchange(&self) -> Exchange {
|
||||
self.exchange
|
||||
}
|
||||
@ -230,9 +215,6 @@ impl ActiveOrder {
|
||||
pub fn update_timestamp(&self) -> u64 {
|
||||
self.update_timestamp
|
||||
}
|
||||
pub fn strategy(&self) -> &Option<Box<dyn OrderStrategy>> {
|
||||
&self.strategy
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for ActiveOrder {
|
||||
@ -249,22 +231,6 @@ impl PartialEq for ActiveOrder {
|
||||
|
||||
impl Eq for ActiveOrder {}
|
||||
|
||||
impl Clone for ActiveOrder {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
exchange: self.exchange,
|
||||
id: self.id,
|
||||
group_id: self.group_id,
|
||||
client_id: self.client_id,
|
||||
pair: self.pair.clone(),
|
||||
order_form: self.order_form.clone(),
|
||||
creation_timestamp: self.creation_timestamp,
|
||||
update_timestamp: self.update_timestamp,
|
||||
strategy: self.strategy.as_ref().map(|x| clone_box(&**x)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
|
||||
pub enum TradingPlatform {
|
||||
Exchange,
|
||||
@ -295,7 +261,7 @@ pub enum OrderKind {
|
||||
Limit { price: f64 },
|
||||
Market,
|
||||
Stop { price: f64 },
|
||||
StopLimit { stop_price: f64, limit_price: f64 },
|
||||
StopLimit { price: f64, limit_price: f64 },
|
||||
TrailingStop { distance: f64 },
|
||||
FillOrKill { price: f64 },
|
||||
ImmediateOrCancel { price: f64 },
|
||||
@ -319,31 +285,31 @@ 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, )
|
||||
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, )
|
||||
write!(f, "[{} | Price: {:0.5}", self.as_str(), price,)
|
||||
}
|
||||
OrderKind::StopLimit { stop_price, limit_price } => {
|
||||
OrderKind::StopLimit { price, limit_price } => {
|
||||
write!(
|
||||
f,
|
||||
"[{} | Stop: {:0.5}, Limit: {:0.5}]",
|
||||
"[{} | Price: {:0.5}, Limit Price: {:0.5}]",
|
||||
self.as_str(),
|
||||
stop_price,
|
||||
price,
|
||||
limit_price
|
||||
)
|
||||
}
|
||||
OrderKind::TrailingStop { distance } => {
|
||||
write!(f, "[{} | Distance: {:0.5}]", self.as_str(), distance, )
|
||||
write!(f, "[{} | Distance: {:0.5}]", self.as_str(), distance,)
|
||||
}
|
||||
OrderKind::FillOrKill { price } => {
|
||||
write!(f, "[{} | Price: {:0.5}]", self.as_str(), price, )
|
||||
write!(f, "[{} | Price: {:0.5}]", self.as_str(), price,)
|
||||
}
|
||||
OrderKind::ImmediateOrCancel { price } => {
|
||||
write!(f, "[{} | Price: {:0.5}]", self.as_str(), price, )
|
||||
write!(f, "[{} | Price: {:0.5}]", self.as_str(), price,)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -389,90 +355,55 @@ impl OrderForm {
|
||||
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 { stop_price: 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
|
||||
}
|
||||
pub fn is_long(&self) -> bool {
|
||||
self.amount.is_sign_positive()
|
||||
}
|
||||
pub fn is_short(&self) -> bool {
|
||||
self.amount.is_sign_negative()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct OrderMetadata {
|
||||
position_id: Option<u64>,
|
||||
strategy: Option<Box<dyn OrderStrategy>>,
|
||||
}
|
||||
|
||||
impl Clone for OrderMetadata {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
position_id: self.position_id,
|
||||
strategy: self.strategy.as_ref().map(|x| clone_box(&**x)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl OrderMetadata {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
position_id: None,
|
||||
strategy: None,
|
||||
pub fn with_position_id(position_id: u64) -> Self {
|
||||
OrderMetadata {
|
||||
position_id: Some(position_id),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_position_id(mut self, position_id: Option<u64>) -> Self {
|
||||
self.position_id = position_id;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_strategy(mut self, strategy: Option<Box<dyn OrderStrategy>>) -> Self {
|
||||
self.strategy = strategy;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn position_id(&self) -> Option<u64> {
|
||||
self.position_id
|
||||
}
|
||||
pub fn cloned_strategy(&self) -> Option<Box<dyn OrderStrategy>> {
|
||||
match &self.strategy {
|
||||
None => { None }
|
||||
Some(strategy) => {
|
||||
Some(clone_box(&**strategy))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for OrderMetadata {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
/***************
|
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)))
|
||||
}
|
||||
}
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
100
src/main.rs
100
src/main.rs
@ -1,100 +0,0 @@
|
||||
#![feature(drain_filter)]
|
||||
#![feature(bool_to_option)]
|
||||
|
||||
use std::env;
|
||||
|
||||
use fern::colors::{Color, ColoredLevelConfig};
|
||||
use log::error;
|
||||
use log::LevelFilter::Info;
|
||||
use tokio::time::Duration;
|
||||
|
||||
use crate::bot::Rustico;
|
||||
use crate::connectors::ExchangeDetails;
|
||||
use crate::currency::{Symbol, SymbolPair};
|
||||
|
||||
mod bot;
|
||||
mod connectors;
|
||||
mod currency;
|
||||
mod events;
|
||||
mod frontend;
|
||||
mod managers;
|
||||
mod models;
|
||||
mod strategy;
|
||||
mod ticker;
|
||||
mod tests;
|
||||
mod sounds;
|
||||
|
||||
pub type BoxError = Box<dyn std::error::Error + Send + Sync>;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), BoxError> {
|
||||
if let Err(e) = setup_logger() {
|
||||
error!("Could not setup logger: {}", e);
|
||||
return Err(e.into());
|
||||
}
|
||||
|
||||
if let Err(e) = dotenv::dotenv() {
|
||||
error!("Could not open .env file: {}", e);
|
||||
return Err(e.into());
|
||||
}
|
||||
|
||||
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_secret,
|
||||
};
|
||||
|
||||
let pairs = vec![
|
||||
SymbolPair::new(Symbol::BTC, Symbol::USD),
|
||||
SymbolPair::new(Symbol::XMR, Symbol::USD),
|
||||
SymbolPair::new(Symbol::ETH, Symbol::USD),
|
||||
SymbolPair::new(Symbol::DERIV_ADA, Symbol::DERIV_USDT),
|
||||
SymbolPair::new(Symbol::DERIV_POLKADOT, Symbol::DERIV_USDT),
|
||||
SymbolPair::new(Symbol::DERIV_BTC, Symbol::DERIV_USDT),
|
||||
SymbolPair::new(Symbol::DERIV_ETH, Symbol::DERIV_USDT),
|
||||
SymbolPair::new(Symbol::DERIV_TESTBTC, Symbol::DERIV_TESTUSDT),
|
||||
];
|
||||
|
||||
let mut bot = Rustico::new(
|
||||
vec![bitfinex],
|
||||
pairs,
|
||||
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!(
|
||||
"{} | [{}][{}] | {}",
|
||||
chrono::Local::now().format("[%d/%m/%Y][%H:%M:%S]"),
|
||||
record.target().strip_prefix("rustico::").unwrap_or("rustico"),
|
||||
colors.color(record.level()),
|
||||
message
|
||||
))
|
||||
})
|
||||
.level(Info)
|
||||
.filter(|metadata| metadata.target().contains("rustico"))
|
||||
.chain(std::io::stdout())
|
||||
.chain(fern::log_file("rustico.log")?)
|
||||
.apply()?;
|
||||
|
||||
Ok(())
|
||||
}
|
@ -1,19 +0,0 @@
|
||||
use ears::{AudioController, Sound};
|
||||
use log::error;
|
||||
|
||||
pub const MARKET_ORDER_PLACED_PATH: &str = "sounds/smas-smb3_goal.wav";
|
||||
pub const LOSS_TO_BREAK_EVEN_PATH: &str = "sounds/smw2_boing.wav";
|
||||
pub const MIN_PROFIT_SOUND_PATH: &str = "sounds/smw_1-up.wav";
|
||||
pub const GOOD_PROFIT_SOUND_PATH: &str = "sounds/smw_power-up.wav";
|
||||
|
||||
pub fn play_sound(sound_path: &'static str) {
|
||||
std::thread::spawn(move || {
|
||||
match Sound::new(sound_path) {
|
||||
Ok(mut sound) => {
|
||||
sound.play();
|
||||
while sound.is_playing() {}
|
||||
}
|
||||
Err(e) => { error!("Could not play {}: {}", sound_path, e); }
|
||||
}
|
||||
});
|
||||
}
|
449
src/strategy.rs
449
src/strategy.rs
@ -1,449 +0,0 @@
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::{Debug, Formatter};
|
||||
use std::ops::Neg;
|
||||
|
||||
use dyn_clone::DynClone;
|
||||
use log::info;
|
||||
|
||||
use crate::BoxError;
|
||||
use crate::events::{ActionMessage, Event, EventKind, EventMetadata};
|
||||
use crate::managers::OptionUpdate;
|
||||
use crate::models::{ActiveOrder, OrderBook, OrderForm, OrderKind, OrderMetadata, Position, PositionProfitState, TradingFees};
|
||||
use crate::models::PositionProfitState::{BreakEven, Critical, Loss, MinimumProfit, Profit};
|
||||
use crate::sounds::{GOOD_PROFIT_SOUND_PATH, LOSS_TO_BREAK_EVEN_PATH, MIN_PROFIT_SOUND_PATH, play_sound};
|
||||
|
||||
/***************
|
||||
* 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>,
|
||||
fees: &[TradingFees],
|
||||
) -> (Position, Option<Vec<Event>>, Option<Vec<ActionMessage>>);
|
||||
fn post_tick(
|
||||
&mut self,
|
||||
position: Position,
|
||||
current_tick: u64,
|
||||
positions_history: &HashMap<u64, Position>,
|
||||
fees: &[TradingFees],
|
||||
) -> (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 TrailingStop {
|
||||
// Position ID: stop percentage mapping
|
||||
stop_percentages: HashMap<u64, f64>,
|
||||
// Position ID: bool mapping. Represents when the strategy has asked the
|
||||
// order manager to set a stop loss order
|
||||
stop_loss_flags: HashMap<u64, bool>,
|
||||
// Position ID: bool mapping. Represents when the strategy has asked the
|
||||
// order manager to set a limit order to close the position as the stop percentage
|
||||
// has been surpassed
|
||||
trail_set_flags: HashMap<u64, bool>,
|
||||
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 play_sound_on_state(prev_position: &Position, current_position: &Position) {
|
||||
if prev_position.profit_state().is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
if current_position.profit_state().is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
let prev_state = prev_position.profit_state().unwrap();
|
||||
let current_state = current_position.profit_state().unwrap();
|
||||
|
||||
// negative to positive
|
||||
if let Loss | Critical = prev_state {
|
||||
match current_state {
|
||||
PositionProfitState::BreakEven => { play_sound(LOSS_TO_BREAK_EVEN_PATH); }
|
||||
PositionProfitState::MinimumProfit => { play_sound(MIN_PROFIT_SOUND_PATH); }
|
||||
PositionProfitState::Profit => { play_sound(GOOD_PROFIT_SOUND_PATH); }
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
if let BreakEven = prev_state {
|
||||
match current_state {
|
||||
PositionProfitState::MinimumProfit => { play_sound(MIN_PROFIT_SOUND_PATH); }
|
||||
PositionProfitState::Profit => { play_sound(GOOD_PROFIT_SOUND_PATH); }
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn print_status(&self, position: &Position) {
|
||||
match self.stop_percentages.get(&position.id()) {
|
||||
None => {
|
||||
info!(
|
||||
"\tState: {:?} | PL: {:0.2}{} ({:0.2}%)",
|
||||
position.profit_state().unwrap(),
|
||||
position.pl(),
|
||||
position.pair().quote(),
|
||||
position.pl_perc()
|
||||
);
|
||||
}
|
||||
Some(stop_percentage) => {
|
||||
info!(
|
||||
"\tState: {:?} | PL: {:0.2}{} ({:0.2}%) | Stop: {:0.2}",
|
||||
position.profit_state().unwrap(),
|
||||
position.pl(),
|
||||
position.pair().quote(),
|
||||
position.pl_perc(),
|
||||
stop_percentage
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 => self.min_profit_trailing_delta,
|
||||
PositionProfitState::Profit => self.good_profit_trailing_delta,
|
||||
_ => return
|
||||
};
|
||||
|
||||
let current_trailing_delta = position.pl_perc() - profit_state_delta;
|
||||
|
||||
match self.stop_percentages.get(&position.id()) {
|
||||
None => {
|
||||
self.stop_percentages
|
||||
.insert(position.id(), current_trailing_delta);
|
||||
}
|
||||
Some(existing_threshold) => {
|
||||
if existing_threshold < ¤t_trailing_delta {
|
||||
self.stop_percentages
|
||||
.insert(position.id(), current_trailing_delta);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for TrailingStop {
|
||||
fn default() -> Self {
|
||||
let leverage = 15.0;
|
||||
|
||||
// in percentage
|
||||
let capital_min_profit = 8.5;
|
||||
let capital_max_loss = capital_min_profit * 1.9;
|
||||
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;
|
||||
|
||||
TrailingStop {
|
||||
stop_percentages: Default::default(),
|
||||
stop_loss_flags: Default::default(),
|
||||
trail_set_flags: 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>,
|
||||
_: &[TradingFees],
|
||||
) -> (Position, Option<Vec<Event>>, Option<Vec<ActionMessage>>) {
|
||||
let pl_perc = position.pl_perc();
|
||||
|
||||
// setting the state of the position based on its profit/loss percentage
|
||||
let state = {
|
||||
if pl_perc > self.good_profit_percentage {
|
||||
Profit
|
||||
} else if (self.min_profit_percentage..self.good_profit_percentage).contains(&pl_perc) {
|
||||
MinimumProfit
|
||||
} else if (0.0..self.min_profit_percentage).contains(&pl_perc) {
|
||||
BreakEven
|
||||
} else if (self.max_loss_percentage..0.0).contains(&pl_perc) {
|
||||
Loss
|
||||
} else {
|
||||
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));
|
||||
|
||||
// checking if there was a state change between the current position
|
||||
// and its last state
|
||||
match opt_prev_position {
|
||||
Some(prev) => {
|
||||
if prev.profit_state() == Some(state) {
|
||||
return (new_position, None, None);
|
||||
}
|
||||
|
||||
TrailingStop::play_sound_on_state(&prev, &new_position);
|
||||
}
|
||||
None => return (new_position, None, None),
|
||||
};
|
||||
|
||||
let event = match state {
|
||||
PositionProfitState::Critical => {
|
||||
Event::new(
|
||||
EventKind::ReachedMaxLoss,
|
||||
current_tick,
|
||||
)
|
||||
}
|
||||
PositionProfitState::Loss => {
|
||||
Event::new(
|
||||
EventKind::ReachedLoss,
|
||||
current_tick,
|
||||
)
|
||||
}
|
||||
PositionProfitState::BreakEven => {
|
||||
Event::new(
|
||||
EventKind::ReachedBreakEven,
|
||||
current_tick,
|
||||
)
|
||||
}
|
||||
PositionProfitState::MinimumProfit => {
|
||||
Event::new(
|
||||
EventKind::ReachedMinProfit,
|
||||
current_tick,
|
||||
)
|
||||
}
|
||||
PositionProfitState::Profit => {
|
||||
Event::new(
|
||||
EventKind::ReachedGoodProfit,
|
||||
current_tick,
|
||||
)
|
||||
}
|
||||
}.with_metadata(Some(event_metadata));
|
||||
|
||||
(new_position, Some(vec![event]), None)
|
||||
}
|
||||
|
||||
fn post_tick(
|
||||
&mut self,
|
||||
position: Position,
|
||||
_: u64,
|
||||
_: &HashMap<u64, Position>,
|
||||
fees: &[TradingFees],
|
||||
) -> (Position, Option<Vec<Event>>, Option<Vec<ActionMessage>>) {
|
||||
let taker_fee = fees
|
||||
.iter()
|
||||
.filter_map(|x| match x {
|
||||
TradingFees::Taker {
|
||||
platform,
|
||||
percentage,
|
||||
} if platform == &position.platform() => Some(percentage),
|
||||
_ => None,
|
||||
})
|
||||
.next().map_or_else(|| 0.0, |&x| x);
|
||||
|
||||
// we need to consider possible slippage when executing the stop order
|
||||
let slippage_percentage = self.max_loss_percentage * 0.085;
|
||||
|
||||
// calculating the stop price based on short/long position
|
||||
let stop_loss_price = {
|
||||
if position.is_short() {
|
||||
position.base_price() * (1.0 - (self.max_loss_percentage - taker_fee - slippage_percentage) / 100.0)
|
||||
} else {
|
||||
position.base_price() * (1.0 + (self.max_loss_percentage - taker_fee - slippage_percentage) / 100.0)
|
||||
}
|
||||
};
|
||||
|
||||
let close_position_orders_msg = ActionMessage::ClosePositionOrders {
|
||||
position_id: position.id(),
|
||||
};
|
||||
let close_position_msg = ActionMessage::ClosePosition {
|
||||
position_id: position.id(),
|
||||
};
|
||||
let set_stop_loss_msg = ActionMessage::SubmitOrder {
|
||||
order: OrderForm::new(position.pair().clone(),
|
||||
OrderKind::Stop { price: stop_loss_price },
|
||||
position.platform(),
|
||||
position.amount().neg())
|
||||
.with_leverage(Some(self.leverage))
|
||||
.with_metadata(Some(OrderMetadata::new().with_position_id(Some(position.id()))))
|
||||
};
|
||||
let stop_loss_set = *self.stop_loss_flags.entry(position.id()).or_insert(false);
|
||||
|
||||
// if in loss, ask the order manager to set the stop limit order,
|
||||
// if not already set
|
||||
if let Some(PositionProfitState::Critical) | Some(PositionProfitState::Loss) = position.profit_state() {
|
||||
self.print_status(&position);
|
||||
|
||||
if !stop_loss_set {
|
||||
info!("In loss. Opening trailing stop order.");
|
||||
|
||||
self.stop_loss_flags.insert(position.id(), true);
|
||||
return (position, None, Some(vec![set_stop_loss_msg]));
|
||||
}
|
||||
return (position, None, None);
|
||||
}
|
||||
|
||||
// if we get here we are with a profit/loss ration > 0.0
|
||||
|
||||
let mut messages = vec![];
|
||||
|
||||
// if a stop loss order was previously set,
|
||||
// ask the order manager to remove the order first
|
||||
if stop_loss_set {
|
||||
info!("Removing stop loss order.");
|
||||
messages.push(close_position_orders_msg);
|
||||
self.stop_loss_flags.insert(position.id(), false);
|
||||
}
|
||||
|
||||
self.update_stop_percentage(&position);
|
||||
self.print_status(&position);
|
||||
|
||||
// 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.");
|
||||
messages.push(close_position_msg);
|
||||
return (position, None, Some(messages));
|
||||
}
|
||||
}
|
||||
|
||||
(position, None, Some(messages))
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* 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.2 / 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().is_long() {
|
||||
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)))
|
||||
}
|
||||
}
|
89
src/tests.rs
89
src/tests.rs
@ -1,89 +0,0 @@
|
||||
#[cfg(test)]
|
||||
mod common {
|
||||
use crate::currency::{Symbol, SymbolPair};
|
||||
use crate::models::{Position, PositionState, TradingPlatform};
|
||||
use crate::models::PositionProfitState::Loss;
|
||||
|
||||
// TODO: generate other helper generator functions like the one below
|
||||
|
||||
// Generates two short positions with different profit/loss ratios. Both are position in "Loss".
|
||||
pub fn get_short_loss_positions(pair: SymbolPair) -> (Position, Position) {
|
||||
let almost_critical = Position::new(pair.clone(),
|
||||
PositionState::Open,
|
||||
-0.1,
|
||||
100.0,
|
||||
-2.0,
|
||||
-2.0,
|
||||
150.0,
|
||||
0,
|
||||
TradingPlatform::Margin,
|
||||
0.0)
|
||||
.with_profit_state(Some(Loss));
|
||||
let loss = Position::new(pair.clone(),
|
||||
PositionState::Open,
|
||||
-0.1,
|
||||
100.0,
|
||||
-1.0,
|
||||
-1.0,
|
||||
150.0,
|
||||
0,
|
||||
TradingPlatform::Margin,
|
||||
0.0)
|
||||
.with_profit_state(Some(Loss));
|
||||
|
||||
(almost_critical, loss)
|
||||
}
|
||||
|
||||
pub fn get_btcusd_pair() -> SymbolPair {
|
||||
SymbolPair::new(Symbol::BTC, Symbol::USD)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod positions {
|
||||
use crate::models::{Position, PositionState, TradingPlatform};
|
||||
use crate::models::PositionProfitState::Loss;
|
||||
use crate::tests::common::{get_btcusd_pair, get_short_loss_positions};
|
||||
|
||||
#[test]
|
||||
fn short_positions() {
|
||||
let pair = get_btcusd_pair();
|
||||
|
||||
let one = Position::new(pair.clone(),
|
||||
PositionState::Open,
|
||||
-0.1,
|
||||
100.0,
|
||||
-2.0,
|
||||
-2.0,
|
||||
150.0,
|
||||
0,
|
||||
TradingPlatform::Margin,
|
||||
0.0);
|
||||
|
||||
assert_eq!(one.pair(), &pair);
|
||||
assert_eq!(one.is_long(), false);
|
||||
assert_eq!(one.is_short(), true);
|
||||
assert_eq!(one.profit_state(), None);
|
||||
assert_eq!(one.platform(), TradingPlatform::Margin);
|
||||
assert_eq!(one.amount(), -0.1);
|
||||
assert_eq!(one.base_price(), 100.0);
|
||||
assert_eq!(one.pl(), -2.0);
|
||||
assert_eq!(one.pl_perc(), -2.0);
|
||||
assert_eq!(one.id(), 0);
|
||||
assert_eq!(one.leverage(), 0.0);
|
||||
assert_eq!(one.price_liq(), 150.0);
|
||||
assert_eq!(one.state(), PositionState::Open);
|
||||
assert!(one.price_liq() > one.base_price());
|
||||
|
||||
let (two, three) = get_short_loss_positions(pair);
|
||||
|
||||
assert_eq!(two.is_short(), true);
|
||||
assert_eq!(two.is_long(), false);
|
||||
assert_eq!(three.is_short(), true);
|
||||
assert_eq!(three.is_long(), false);
|
||||
assert_eq!(two.profit_state(), Some(Loss));
|
||||
assert_eq!(three.profit_state(), Some(Loss));
|
||||
|
||||
// TODO: add more test positions with and without profit states
|
||||
}
|
||||
}
|
7
svelte/.gitignore
vendored
Normal file
7
svelte/.gitignore
vendored
Normal file
@ -0,0 +1,7 @@
|
||||
.vscode/
|
||||
/node_modules/
|
||||
/public/*
|
||||
|
||||
src/*.ts
|
||||
|
||||
.DS_Store
|
105
svelte/README.md
Normal file
105
svelte/README.md
Normal file
@ -0,0 +1,105 @@
|
||||
*Looking for a shareable component template? Go here --> [sveltejs/component-template](https://github.com/sveltejs/component-template)*
|
||||
|
||||
---
|
||||
|
||||
# svelte app
|
||||
|
||||
This is a project template for [Svelte](https://svelte.dev) apps. It lives at https://github.com/sveltejs/template.
|
||||
|
||||
To create a new project based on this template using [degit](https://github.com/Rich-Harris/degit):
|
||||
|
||||
```bash
|
||||
npx degit sveltejs/template svelte-app
|
||||
cd svelte-app
|
||||
```
|
||||
|
||||
*Note that you will need to have [Node.js](https://nodejs.org) installed.*
|
||||
|
||||
|
||||
## Get started
|
||||
|
||||
Install the dependencies...
|
||||
|
||||
```bash
|
||||
cd svelte-app
|
||||
npm install
|
||||
```
|
||||
|
||||
...then start [Rollup](https://rollupjs.org):
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Navigate to [localhost:5000](http://localhost:5000). You should see your app running. Edit a component file in `src`, save it, and reload the page to see your changes.
|
||||
|
||||
By default, the server will only respond to requests from localhost. To allow connections from other computers, edit the `sirv` commands in package.json to include the option `--host 0.0.0.0`.
|
||||
|
||||
If you're using [Visual Studio Code](https://code.visualstudio.com/) we recommend installing the official extension [Svelte for VS Code](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode). If you are using other editors you may need to install a plugin in order to get syntax highlighting and intellisense.
|
||||
|
||||
## Building and running in production mode
|
||||
|
||||
To create an optimised version of the app:
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
You can run the newly built app with `npm run start`. This uses [sirv](https://github.com/lukeed/sirv), which is included in your package.json's `dependencies` so that the app will work when you deploy to platforms like [Heroku](https://heroku.com).
|
||||
|
||||
|
||||
## Single-page app mode
|
||||
|
||||
By default, sirv will only respond to requests that match files in `public`. This is to maximise compatibility with static fileservers, allowing you to deploy your app anywhere.
|
||||
|
||||
If you're building a single-page app (SPA) with multiple routes, sirv needs to be able to respond to requests for *any* path. You can make it so by editing the `"start"` command in package.json:
|
||||
|
||||
```js
|
||||
"start": "sirv public --single"
|
||||
```
|
||||
|
||||
## Using TypeScript
|
||||
|
||||
This template comes with a script to set up a TypeScript development environment, you can run it immediately after cloning the template with:
|
||||
|
||||
```bash
|
||||
node scripts/setupTypeScript.js
|
||||
```
|
||||
|
||||
Or remove the script via:
|
||||
|
||||
```bash
|
||||
rm scripts/setupTypeScript.js
|
||||
```
|
||||
|
||||
## Deploying to the web
|
||||
|
||||
### With [Vercel](https://vercel.com)
|
||||
|
||||
Install `vercel` if you haven't already:
|
||||
|
||||
```bash
|
||||
npm install -g vercel
|
||||
```
|
||||
|
||||
Then, from within your project folder:
|
||||
|
||||
```bash
|
||||
cd public
|
||||
vercel deploy --name my-project
|
||||
```
|
||||
|
||||
### With [surge](https://surge.sh/)
|
||||
|
||||
Install `surge` if you haven't already:
|
||||
|
||||
```bash
|
||||
npm install -g surge
|
||||
```
|
||||
|
||||
Then, from within your project folder:
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
surge public my-project.surge.sh
|
||||
```
|
34
svelte/package.json
Normal file
34
svelte/package.json
Normal file
@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "rustico-ui",
|
||||
"version": "1.0.0",
|
||||
"scripts": {
|
||||
"build": "rollup -c",
|
||||
"dev": "rollup -c -w",
|
||||
"start": "sirv public",
|
||||
"validate": "svelte-check"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rollup/plugin-commonjs": "^17.0.0",
|
||||
"@rollup/plugin-node-resolve": "^11.0.0",
|
||||
"@rollup/plugin-typescript": "^6.0.0",
|
||||
"@tsconfig/svelte": "^1.0.0",
|
||||
"postcss": "^8.2.6",
|
||||
"rollup": "^2.3.4",
|
||||
"rollup-plugin-css-only": "^3.1.0",
|
||||
"rollup-plugin-livereload": "^2.0.0",
|
||||
"rollup-plugin-postcss": "^4.0.0",
|
||||
"rollup-plugin-svelte": "^7.0.0",
|
||||
"rollup-plugin-terser": "^7.0.0",
|
||||
"svelte": "^3.0.0",
|
||||
"svelte-check": "^1.0.0",
|
||||
"svelte-preprocess": "^4.0.0",
|
||||
"tslib": "^2.0.0",
|
||||
"typescript": "^3.9.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@rollup/plugin-typescript": "^8.2.0",
|
||||
"autoprefixer": "^10.2.4",
|
||||
"sirv-cli": "^1.0.0",
|
||||
"tailwindcss": "^2.0.3"
|
||||
}
|
||||
}
|
6
svelte/postcss.config.js
Normal file
6
svelte/postcss.config.js
Normal file
@ -0,0 +1,6 @@
|
||||
module.exports = {
|
||||
plugins: [
|
||||
require("tailwindcss"),
|
||||
require("autoprefixer")
|
||||
],
|
||||
};
|
83
svelte/rollup.config.js
Normal file
83
svelte/rollup.config.js
Normal file
@ -0,0 +1,83 @@
|
||||
import svelte from 'rollup-plugin-svelte';
|
||||
import commonjs from '@rollup/plugin-commonjs';
|
||||
import resolve from '@rollup/plugin-node-resolve';
|
||||
import livereload from 'rollup-plugin-livereload';
|
||||
import { terser } from 'rollup-plugin-terser';
|
||||
import sveltePreprocess from 'svelte-preprocess';
|
||||
import typescript from '@rollup/plugin-typescript';
|
||||
import css from 'rollup-plugin-css-only';
|
||||
|
||||
const production = !process.env.ROLLUP_WATCH;
|
||||
|
||||
function serve() {
|
||||
let server;
|
||||
|
||||
function toExit() {
|
||||
if (server) server.kill(0);
|
||||
}
|
||||
|
||||
return {
|
||||
writeBundle() {
|
||||
if (server) return;
|
||||
server = require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
|
||||
stdio: ['ignore', 'inherit', 'inherit'],
|
||||
shell: true
|
||||
});
|
||||
|
||||
process.on('SIGTERM', toExit);
|
||||
process.on('exit', toExit);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default {
|
||||
input: 'src/main.ts',
|
||||
output: {
|
||||
sourcemap: true,
|
||||
format: 'iife',
|
||||
name: 'app',
|
||||
file: 'public/build/bundle.js'
|
||||
},
|
||||
plugins: [
|
||||
svelte({
|
||||
preprocess: sveltePreprocess({ sourceMap: !production, postcss: true }),
|
||||
compilerOptions: {
|
||||
// enable run-time checks when not in production
|
||||
dev: !production,
|
||||
}
|
||||
}),
|
||||
typescript({ sourceMap: !production }),
|
||||
// we'll extract any component CSS out into
|
||||
// a separate file - better for performance
|
||||
css({ output: 'bundle.css' }),
|
||||
// If you have external dependencies installed from
|
||||
// npm, you'll most likely need these plugins. In
|
||||
// some cases you'll need additional configuration -
|
||||
// consult the documentation for details:
|
||||
// https://github.com/rollup/plugins/tree/master/packages/commonjs
|
||||
resolve({
|
||||
browser: true,
|
||||
dedupe: ['svelte']
|
||||
}),
|
||||
commonjs(),
|
||||
typescript({
|
||||
sourceMap: !production,
|
||||
inlineSources: !production
|
||||
}),
|
||||
|
||||
// In dev mode, call `npm run start` once
|
||||
// the bundle has been generated
|
||||
!production && serve(),
|
||||
|
||||
// Watch the `public` directory and refresh the
|
||||
// browser on changes when not in production
|
||||
!production && livereload('public'),
|
||||
|
||||
// If we're building for production (npm run build
|
||||
// instead of npm run dev), minify
|
||||
production && terser()
|
||||
],
|
||||
watch: {
|
||||
clearScreen: false
|
||||
}
|
||||
};
|
23
svelte/src/App.svelte
Normal file
23
svelte/src/App.svelte
Normal file
@ -0,0 +1,23 @@
|
||||
<script lang="ts">
|
||||
export let name: string;
|
||||
</script>
|
||||
|
||||
<main>
|
||||
<h1 class="bg-gray-400">Hello {name}!</h1>
|
||||
<p>
|
||||
Visit the <a href="https://svelte.dev/tutorial">Svelte tutorial</a> to learn
|
||||
how to build Svelte apps.
|
||||
</p>
|
||||
</main>
|
||||
|
||||
<style global lang="postcss">
|
||||
/* only apply purgecss on utilities, per Tailwind docs */
|
||||
/* purgecss start ignore */
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
/* purgecss end ignore */
|
||||
|
||||
@tailwind utilities;
|
||||
|
||||
</style>
|
||||
|
30
svelte/tailwind.config.js
Normal file
30
svelte/tailwind.config.js
Normal file
@ -0,0 +1,30 @@
|
||||
const isProduction = !process.env.ROLLUP_WATCH; // or some other env var like NODE_ENV
|
||||
|
||||
module.exports = {
|
||||
// only needed in Tailwind 1.0 for tailwind 2.0 compat
|
||||
// future: {
|
||||
// purgeLayersByDefault: true,
|
||||
// removeDeprecatedGapUtilities: true,
|
||||
// },
|
||||
plugins: [
|
||||
// for tailwind UI users only
|
||||
// require('@tailwindcss/ui'),
|
||||
// other plugins here
|
||||
],
|
||||
purge: {
|
||||
content: [
|
||||
"./src/**/*.svelte",
|
||||
// may also want to include HTML files
|
||||
// "./src/**/*.html"
|
||||
],
|
||||
// this is for extracting Svelte `class:` syntax but is not perfect yet, see below
|
||||
defaultExtractor: content => {
|
||||
const broadMatches = content.match(/[^<>"'`\s]*[^<>"'`\s:]/g) || []
|
||||
const broadMatchesWithoutTrailingSlash = broadMatches.map(match => _.trimEnd(match, '\\'))
|
||||
const matches = broadMatches
|
||||
.concat(broadMatchesWithoutTrailingSlash)
|
||||
return matches
|
||||
},
|
||||
enabled: isProduction // disable purge in dev
|
||||
},
|
||||
};
|
6
svelte/tsconfig.json
Normal file
6
svelte/tsconfig.json
Normal file
@ -0,0 +1,6 @@
|
||||
{
|
||||
"extends": "@tsconfig/svelte/tsconfig.json",
|
||||
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules/*", "__sapper__/*", "public/*"]
|
||||
}
|
2290
svelte/yarn.lock
Normal file
2290
svelte/yarn.lock
Normal file
File diff suppressed because it is too large
Load Diff
1
websrc/.eslintcache
Normal file
1
websrc/.eslintcache
Normal file
File diff suppressed because one or more lines are too long
23
websrc/.gitignore
vendored
Normal file
23
websrc/.gitignore
vendored
Normal file
@ -0,0 +1,23 @@
|
||||
# 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)
|
131
websrc/components/App.tsx
Normal file
131
websrc/components/App.tsx
Normal file
@ -0,0 +1,131 @@
|
||||
import React, {Component} from "react";
|
||||
import {EventProp} from "./Events";
|
||||
import {
|
||||
Balance,
|
||||
CurrencyPair,
|
||||
EventName,
|
||||
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;
|
155
websrc/components/Cards.tsx
Normal file
155
websrc/components/Cards.tsx
Normal file
@ -0,0 +1,155 @@
|
||||
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) {
|
||||
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 bg-te"}>
|
||||
{/*{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>
|
||||
)
|
||||
}
|
||||
}
|
55
websrc/package.json
Normal file
55
websrc/package.json
Normal file
@ -0,0 +1,55 @@
|
||||
{
|
||||
"name": "bfxbot",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@testing-library/jest-dom": "^5.11.4",
|
||||
"@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-dom": "^17.0.0",
|
||||
"plotly.js": "^1.58.4",
|
||||
"react": "^17.0.1",
|
||||
"react-dom": "^17.0.1",
|
||||
"react-plotly.js": "^2.5.1",
|
||||
"react-scripts": "4.0.1",
|
||||
"socket.io-client": "^3.0.4",
|
||||
"typescript": "^4.1.3",
|
||||
"web-vitals": "^0.2.4"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "react-scripts start",
|
||||
"build": "react-scripts build",
|
||||
"test": "react-scripts test",
|
||||
"eject": "react-scripts eject"
|
||||
},
|
||||
"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>
|
||||
}
|
||||
|
50
websrc/src/components/Icons.tsx
Normal file
50
websrc/src/components/Icons.tsx
Normal file
@ -0,0 +1,50 @@
|
||||
import React, {Component} from "react";
|
||||
|
||||
type IconProps = {
|
||||
width: number,
|
||||
height: number,
|
||||
}
|
||||
|
||||
class Icon extends Component <IconProps> {
|
||||
private readonly width: string;
|
||||
private readonly height: string;
|
||||
|
||||
constructor(props: IconProps) {
|
||||
super(props);
|
||||
|
||||
this.width = "w-" + this.props.width.toString();
|
||||
this.height = "h-" + this.props.width.toString();
|
||||
}
|
||||
|
||||
dimensionsClassName() {
|
||||
return (this.height + " " + this.width)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export class DollarIcon extends Icon {
|
||||
render() {
|
||||
return (
|
||||
<svg className={this.dimensionsClassName()} xmlns="http://www.w3.org/2000/svg" fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
|
||||
d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export class ClockIcon extends Icon {
|
||||
render() {
|
||||
return (
|
||||
<svg className={this.dimensionsClassName()} xmlns="http://www.w3.org/2000/svg" fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
|
||||
d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
71
websrc/src/components/Navbars.tsx
Normal file
71
websrc/src/components/Navbars.tsx
Normal file
@ -0,0 +1,71 @@
|
||||
import React, { Component } from "react";
|
||||
import { WalletCard } from "./Cards";
|
||||
|
||||
export class Navbar extends Component {
|
||||
constructor(props: {}) {
|
||||
super(props);
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<nav
|
||||
className="ml-1 w-24 flex flex-col items-center bg-gray-700 dark:bg-gray-700 py-4 my-1 rounded-tl rounded-bl">
|
||||
|
||||
<ul className="flex-1 mt-2 text-gray-700 dark:text-gray-400 capitalize">
|
||||
{/* Links */}
|
||||
<li className="mt-3 p-2 text-gray-400 dark:text-blue-300 rounded-lg">
|
||||
<a href="#" className=" flex flex-col items-center">
|
||||
<svg className="fill-current h-5 w-5" viewBox="0 0 24 24">
|
||||
<path
|
||||
d="M19 5v2h-4V5h4M9 5v6H5V5h4m10 8v6h-4v-6h4M9
|
||||
17v2H5v-2h4M21 3h-8v6h8V3M11 3H3v10h8V3m10
|
||||
8h-8v10h8V11m-10 4H3v6h8v-6z"/>
|
||||
</svg>
|
||||
<span className="text-xs mt-2 text-gray-300">Dashboard</span>
|
||||
</a>
|
||||
</li>
|
||||
<li className="mt-3 p-2 text-gray-400 dark:text-blue-300 rounded-lg">
|
||||
<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"
|
||||
stroke="currentColor">
|
||||
<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" />
|
||||
</svg>
|
||||
<span className="text-xs mt-2 text-gray-300">Reports</span>
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
<ul className="text-gray-700 dark:text-gray-400 capitalize">
|
||||
<li className="mt-auto p-2 text-gray-400 dark:text-blue-300 rounded-lg">
|
||||
<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"
|
||||
stroke="currentColor">
|
||||
<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" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
|
||||
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
</svg>
|
||||
<span className="text-xs mt-2 text-gray-300">Settings</span>
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export class Sidebar extends Component {
|
||||
constructor(props: {}) {
|
||||
super(props);
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<aside
|
||||
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">
|
||||
<WalletCard />
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
}
|
90
websrc/src/components/Overlays.tsx
Normal file
90
websrc/src/components/Overlays.tsx
Normal file
@ -0,0 +1,90 @@
|
||||
import React, {Component} from "react";
|
||||
import {socket} from "../index";
|
||||
import {EventName} from "../types";
|
||||
|
||||
export type ModalProps = {
|
||||
show: boolean,
|
||||
positionId: number,
|
||||
toggleConfirmation: any
|
||||
}
|
||||
|
||||
export class ClosePositionModal extends Component<ModalProps, any> {
|
||||
constructor(props: ModalProps) {
|
||||
super(props);
|
||||
}
|
||||
|
||||
render() {
|
||||
if (!this.props.show) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed z-10 inset-0 overflow-y-auto">
|
||||
<div className="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
|
||||
<div className="fixed inset-0 transition-opacity" aria-hidden="true">
|
||||
<div className="absolute inset-0 bg-gray-500 opacity-75"/>
|
||||
</div>
|
||||
|
||||
{/*This element is to trick the browser into centering the modal contents. -->*/}
|
||||
<span className="hidden sm:inline-block sm:align-middle sm:h-screen"
|
||||
aria-hidden="true">​</span>
|
||||
|
||||
{/*Modal panel, show/hide based on modal state.*/}
|
||||
|
||||
{/*Entering: "ease-out duration-300"*/}
|
||||
{/* From: "opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"*/}
|
||||
{/* To: "opacity-100 translate-y-0 sm:scale-100"*/}
|
||||
{/*Leaving: "ease-in duration-200"*/}
|
||||
{/* From: "opacity-100 translate-y-0 sm:scale-100"*/}
|
||||
{/* To: "opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"*/}
|
||||
|
||||
<div
|
||||
className="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full"
|
||||
role="dialog" aria-modal="true" aria-labelledby="modal-headline">
|
||||
<div className="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
|
||||
<div className="sm:flex sm:items-start">
|
||||
<div
|
||||
className="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
|
||||
{/*Heroicon name: exclamation -->*/}
|
||||
<svg className="h-6 w-6 text-red-600" xmlns="http://www.w3.org/2000/svg" fill="none"
|
||||
viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2"
|
||||
d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
|
||||
<h3 className="text-lg leading-6 font-medium text-gray-900" id="modal-headline">
|
||||
Close position
|
||||
</h3>
|
||||
<div className="mt-2">
|
||||
<p className="text-sm text-gray-500">
|
||||
Are you sure you want to close the position? This action cannot be undone.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
|
||||
<button type="button"
|
||||
className="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:text-sm"
|
||||
onClick={event => {
|
||||
socket.emit(EventName.ClosePosition, {
|
||||
position_id: this.props.positionId
|
||||
})
|
||||
|
||||
this.props.toggleConfirmation()
|
||||
}}>
|
||||
Close
|
||||
</button>
|
||||
<button type="button"
|
||||
className="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm"
|
||||
onClick={() => this.props.toggleConfirmation()}>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
168
websrc/src/components/RPlot.tsx
Normal file
168
websrc/src/components/RPlot.tsx
Normal file
@ -0,0 +1,168 @@
|
||||
import React, { Component } from "react"
|
||||
import Plot from "react-plotly.js"
|
||||
|
||||
import { socket } from '../';
|
||||
import { EventName, NewTickMessage } from "../types";
|
||||
|
||||
|
||||
type FirstConnectData = {
|
||||
ticks: Array<number>,
|
||||
prices: Array<number>
|
||||
}
|
||||
|
||||
|
||||
type PriceLine = {
|
||||
x0: number,
|
||||
y0: number,
|
||||
x1: number,
|
||||
y1: number
|
||||
}
|
||||
|
||||
type PlotState = {
|
||||
x: Array<number>,
|
||||
y: Array<number>,
|
||||
current_price_line: PriceLine,
|
||||
positions_price_lines: Array<PriceLine>,
|
||||
}
|
||||
|
||||
class RPlot extends Component<{}, PlotState> {
|
||||
state = {
|
||||
x: [],
|
||||
y: [],
|
||||
current_price_line: { x0: 0, x1: 0, y0: 0, y1: 0 },
|
||||
positions_price_lines: []
|
||||
}
|
||||
|
||||
constructor(props: {}) {
|
||||
super(props)
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
socket.on(EventName.FirstConnect, (data: FirstConnectData) => {
|
||||
const last_tick = data.ticks[data.ticks.length - 1];
|
||||
const last_price = data.prices[data.prices.length - 1];
|
||||
|
||||
this.setState({
|
||||
x: data.ticks,
|
||||
y: data.prices,
|
||||
current_price_line: {
|
||||
x0: 0,
|
||||
y0: last_price,
|
||||
x1: last_tick,
|
||||
y1: last_price
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
socket.on(EventName.NewTick, (data: NewTickMessage) => {
|
||||
const position_price_lines = data.positions.map((pstat): PriceLine => {
|
||||
return {
|
||||
x0: 0,
|
||||
y0: pstat.base_price,
|
||||
x1: data.tick,
|
||||
y1: pstat.base_price
|
||||
}
|
||||
})
|
||||
|
||||
this.setState((state) => ({
|
||||
x: state.x.concat(data.tick),
|
||||
y: state.y.concat(data.price),
|
||||
current_price_line: {
|
||||
x0: 0,
|
||||
y0: data.price,
|
||||
x1: data.tick,
|
||||
y1: data.price
|
||||
},
|
||||
positions_price_lines: position_price_lines
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
render() {
|
||||
// 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) {
|
||||
// additional_shapes = this.state.positions_price_lines.map((priceline: PriceLine) => {
|
||||
// return {
|
||||
// type: 'line',
|
||||
// x0: priceline.x0,
|
||||
// y0: priceline.y0,
|
||||
// x1: priceline.x1,
|
||||
// y1: priceline.y1,
|
||||
// line: {
|
||||
// color: 'rgb(1, 1, 1)',
|
||||
// width: 1,
|
||||
// dash: 'solid'
|
||||
// }
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
||||
return (
|
||||
<Plot
|
||||
data={[
|
||||
{
|
||||
x: this.state.x,
|
||||
y: this.state.y,
|
||||
type: 'scatter',
|
||||
mode: 'lines+markers',
|
||||
},
|
||||
]}
|
||||
layout={{
|
||||
margin: {
|
||||
l: 110,
|
||||
r: 20,
|
||||
b: 100,
|
||||
t: 20,
|
||||
pad: 4
|
||||
},
|
||||
dragmode: "pan",
|
||||
// shapes: [
|
||||
// {
|
||||
// type: 'line',
|
||||
// x0: this.state.current_price_line.x0,
|
||||
// y0: this.state.current_price_line.y0,
|
||||
// x1: this.state.current_price_line.x1,
|
||||
// y1: this.state.current_price_line.y1,
|
||||
// line: {
|
||||
// color: 'rgb(50, 171, 96)',
|
||||
// width: 2,
|
||||
// dash: 'dashdot'
|
||||
// }
|
||||
// },
|
||||
// ].concat(additional_shapes),
|
||||
xaxis: {
|
||||
title: {
|
||||
text: 'Tick',
|
||||
font: {
|
||||
family: 'Courier New, monospace',
|
||||
size: 18,
|
||||
color: '#7f7f7f'
|
||||
}
|
||||
},
|
||||
},
|
||||
yaxis: {
|
||||
title: {
|
||||
text: 'Price',
|
||||
font: {
|
||||
family: 'Courier New, monospace',
|
||||
size: 18,
|
||||
color: '#7f7f7f'
|
||||
}
|
||||
},
|
||||
tickformat: 'r',
|
||||
}
|
||||
}}
|
||||
config={{
|
||||
scrollZoom: true,
|
||||
displayModeBar: false,
|
||||
responsive: true,
|
||||
}}
|
||||
style={{ width: '100%', height: '100%' }}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export default RPlot;
|
304
websrc/src/components/Statusbar.tsx
Normal file
304
websrc/src/components/Statusbar.tsx
Normal file
@ -0,0 +1,304 @@
|
||||
import React, { Component } from "react";
|
||||
import { EventName, GetProfitLossMessage, NewTickMessage, PutProfitLossMessage } from "../types";
|
||||
import { socket } from "../index";
|
||||
import { DateTime } from "luxon";
|
||||
|
||||
type QuoteStatusProps = {
|
||||
percentage?: boolean,
|
||||
quote_symbol?: string,
|
||||
amount: number,
|
||||
subtitle: string,
|
||||
sign?: boolean
|
||||
}
|
||||
|
||||
export class QuoteStatus extends Component<QuoteStatusProps> {
|
||||
private whole: number;
|
||||
private decimal: number;
|
||||
private sign: string;
|
||||
private signClass: string;
|
||||
|
||||
constructor(props: QuoteStatusProps) {
|
||||
super(props);
|
||||
|
||||
this.whole = 0;
|
||||
this.decimal = 0;
|
||||
this.sign = "";
|
||||
this.signClass = "";
|
||||
|
||||
this.deriveProps()
|
||||
}
|
||||
|
||||
deriveProps() {
|
||||
this.whole = Math.abs(Math.trunc(this.props.amount))
|
||||
this.decimal = Math.trunc(this.props.amount % 1 * 100)
|
||||
this.sign = this.props.amount > 0 ? "+" : "-"
|
||||
|
||||
this.signClass = this.props.amount > 0 ? "text-green-500" : "text-red-500"
|
||||
}
|
||||
|
||||
renderSign() {
|
||||
if (this.props.sign) {
|
||||
return (
|
||||
<span
|
||||
className={this.signClass}>{this.sign}</span>
|
||||
)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
symbolOrPercentageRender() {
|
||||
if (this.props.percentage) {
|
||||
return (
|
||||
<>
|
||||
<span className="text-4xl text-bold align-top">
|
||||
{this.renderSign()}</span>
|
||||
<span className="text-5xl">{Math.abs(this.props.amount).toFixed(2)}</span>
|
||||
<span className="text-3xl align-top">%</span>
|
||||
</>
|
||||
)
|
||||
} else {
|
||||
return (
|
||||
<>
|
||||
<span className="text-4xl text-bold align-top">{this.renderSign()}{this.props.quote_symbol}</span>
|
||||
<span className="text-5xl">{this.whole.toLocaleString()}</span>
|
||||
<span className="text-3xl align-top">.{Math.abs(this.decimal)}</span>
|
||||
</>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<>
|
||||
<div className="text-gray-700 mb-2">
|
||||
{this.symbolOrPercentageRender()}
|
||||
</div>
|
||||
<div className="text-sm uppercase text-gray-300 tracking-wide">
|
||||
{this.props.subtitle}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
type DateButtonProps = {
|
||||
label: string,
|
||||
onClick: any,
|
||||
selected_default?: boolean
|
||||
}
|
||||
|
||||
type DateButtonState = {
|
||||
selected: boolean,
|
||||
}
|
||||
|
||||
class DateButton extends Component<DateButtonProps, DateButtonState> {
|
||||
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 currentClass: string = "";
|
||||
|
||||
state = {
|
||||
selected: false
|
||||
}
|
||||
|
||||
constructor(props: DateButtonProps) {
|
||||
super(props);
|
||||
|
||||
if (this.props.selected_default) {
|
||||
this.state = {
|
||||
selected: this.props.selected_default
|
||||
}
|
||||
}
|
||||
|
||||
this.updateClass()
|
||||
}
|
||||
|
||||
onClick() {
|
||||
this.setState({ selected: !this.state.selected }, this.updateClass)
|
||||
|
||||
this.props.onClick()
|
||||
}
|
||||
|
||||
updateClass() {
|
||||
this.currentClass = this.state.selected ? this.classSelected : this.classNotSelected
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<button key={this.props.label} type="button"
|
||||
className={this.currentClass} onClick={this.onClick.bind(this)}>
|
||||
{this.props.label}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const PeriodUnit = {
|
||||
SECOND: "second",
|
||||
MINUTE: "minute",
|
||||
HOUR: "hour",
|
||||
DAY: "day",
|
||||
WEEK: "week",
|
||||
MONTH: "month",
|
||||
YEAR: "year"
|
||||
}
|
||||
|
||||
type StatusBarState = {
|
||||
pl_period_unit: string,
|
||||
pl_period_amount: number,
|
||||
pl: number,
|
||||
pl_perc: number
|
||||
}
|
||||
|
||||
export class Statusbar extends Component<NewTickMessage, StatusBarState> {
|
||||
|
||||
constructor(props: NewTickMessage) {
|
||||
super(props);
|
||||
|
||||
this.state = {
|
||||
pl_period_unit: PeriodUnit.WEEK,
|
||||
pl_period_amount: 1,
|
||||
pl: 0.0,
|
||||
pl_perc: 0.0
|
||||
}
|
||||
|
||||
this.emitGetProfitLoss = this.emitGetProfitLoss.bind(this)
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
socket.on(EventName.PutProfitLoss, (data: PutProfitLossMessage) => {
|
||||
this.setState({
|
||||
pl: data.pl,
|
||||
pl_perc: data.pl_perc
|
||||
})
|
||||
})
|
||||
|
||||
socket.on(EventName.FirstConnect, this.emitGetProfitLoss)
|
||||
socket.on(EventName.NewTick, this.emitGetProfitLoss)
|
||||
}
|
||||
|
||||
|
||||
durationObjectfromStr(str: string) {
|
||||
switch (str) {
|
||||
case PeriodUnit.MINUTE:
|
||||
return {
|
||||
minutes: this.state.pl_period_amount
|
||||
}
|
||||
case PeriodUnit.HOUR:
|
||||
return {
|
||||
hours: this.state.pl_period_amount
|
||||
}
|
||||
case PeriodUnit.DAY:
|
||||
return {
|
||||
days: this.state.pl_period_amount
|
||||
}
|
||||
case PeriodUnit.WEEK:
|
||||
return {
|
||||
weeks: this.state.pl_period_amount
|
||||
}
|
||||
case PeriodUnit.MONTH:
|
||||
return {
|
||||
months: this.state.pl_period_amount
|
||||
}
|
||||
case PeriodUnit.YEAR:
|
||||
return {
|
||||
years: this.state.pl_period_amount
|
||||
}
|
||||
default:
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
emitGetProfitLoss() {
|
||||
const message: GetProfitLossMessage = {
|
||||
start: DateTime.local().minus(this.durationObjectfromStr(this.state.pl_period_unit)).toMillis(),
|
||||
end: DateTime.local().toMillis()
|
||||
}
|
||||
|
||||
socket.emit(EventName.GetProfitLoss, message)
|
||||
}
|
||||
|
||||
changeProfitLossPeriod(amount: number, unit: string) {
|
||||
this.setState({
|
||||
pl_period_amount: amount,
|
||||
pl_period_unit: unit
|
||||
}, this.emitGetProfitLoss)
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<div className="bg-white border-t border-b sm:border-l sm:border-r sm:rounded-lg shadow flex-grow mb-6">
|
||||
<div className="bg-gray-50 rounded-tl-lg rounded-tr-lg border-b px-6">
|
||||
<div className="flex justify-between -mb-px">
|
||||
<div className="lg:hidden text-blue-600 py-4 text-lg">
|
||||
Price Charts
|
||||
</div>
|
||||
<div className="hidden lg:flex">
|
||||
<button type="button"
|
||||
className="appearance-none py-4 text-blue-600 border-b border-blue-dark mr-6">
|
||||
Bitcoin
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex text-sm">
|
||||
<DateButton key={PeriodUnit.MINUTE} label={"1m"}
|
||||
onClick={() => this.changeProfitLossPeriod(1, PeriodUnit.MINUTE)} />
|
||||
<DateButton key={PeriodUnit.DAY} label={"1D"}
|
||||
onClick={() => this.changeProfitLossPeriod(1, PeriodUnit.DAY)} />
|
||||
<DateButton key={PeriodUnit.WEEK} label={"1W"} selected_default={true}
|
||||
onClick={() => this.changeProfitLossPeriod(1, PeriodUnit.WEEK)} />
|
||||
<DateButton key={PeriodUnit.MONTH} label={"1M"}
|
||||
onClick={() => this.changeProfitLossPeriod(1, PeriodUnit.MONTH)} />
|
||||
<DateButton key={PeriodUnit.YEAR} label={"1Y"}
|
||||
onClick={() => this.changeProfitLossPeriod(1, PeriodUnit.YEAR)} />
|
||||
{/*<DateButton label={"ALL"} onClick={() => this.changeProfitLossPeriod(1, PeriodUnit.MINUTE)}/>*/}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center px-6 lg:hidden">
|
||||
<div className="flex-grow flex-no-shrink py-6">
|
||||
<div className="text-gray-700 mb-2">
|
||||
<span className="text-3xl align-top">CA$</span>
|
||||
<span className="text-5xl">21,404</span>
|
||||
<span className="text-3xl align-top">.74</span>
|
||||
</div>
|
||||
<div className="text-green-300 text-sm">
|
||||
↑ CA$12,955.35 (154.16%)
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-shrink w-32 inline-block relative">
|
||||
<select
|
||||
className="block appearance-none w-full bg-white border border-grey-light px-4 py-2 pr-8 rounded">
|
||||
<option>BTC</option>
|
||||
</select>
|
||||
<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"
|
||||
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" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="hidden lg:flex">
|
||||
<div className="w-1/3 text-center py-8">
|
||||
<div className="border-r">
|
||||
<QuoteStatus key={this.props.price} quote_symbol={"USD"} amount={this.props.price}
|
||||
subtitle={"Bitcoin price"} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="w-1/3 text-center py-8">
|
||||
<div className="border-r">
|
||||
<QuoteStatus key={this.state.pl} quote_symbol={"USD"} sign={true} amount={this.state.pl}
|
||||
subtitle={"since last ".concat(this.state.pl_period_unit)} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="w-1/3 text-center py-8">
|
||||
<div>
|
||||
<QuoteStatus key={this.state.pl_perc} percentage={true} sign={true}
|
||||
amount={this.state.pl_perc}
|
||||
subtitle={"since last ".concat(this.state.pl_period_unit)} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
141
websrc/src/components/Tables.tsx
Normal file
141
websrc/src/components/Tables.tsx
Normal file
@ -0,0 +1,141 @@
|
||||
import React, { Component } from "react"
|
||||
import { PositionProp } from "../types";
|
||||
import { ClosePositionModal } from "./Overlays";
|
||||
|
||||
type PositionsTableState = {
|
||||
showConfirmation: boolean,
|
||||
positionToClose: number
|
||||
}
|
||||
|
||||
export class PositionsTable extends Component<{ positions: Array<PositionProp> }, PositionsTableState> {
|
||||
constructor(props: { positions: PositionProp[]; } | Readonly<{ positions: PositionProp[]; }>) {
|
||||
super(props);
|
||||
this.toggleConfirmation = this.toggleConfirmation.bind(this)
|
||||
}
|
||||
|
||||
state = {
|
||||
showConfirmation: false,
|
||||
positionToClose: 0,
|
||||
}
|
||||
|
||||
toggleConfirmation() {
|
||||
this.setState((state) => ({
|
||||
showConfirmation: !state.showConfirmation
|
||||
}))
|
||||
}
|
||||
|
||||
stateColor(state: string): string {
|
||||
const lower_state = state.toLowerCase()
|
||||
let res: string
|
||||
|
||||
if (lower_state.includes("profit")) {
|
||||
res = "green"
|
||||
} else if (lower_state.includes("break")) {
|
||||
res = "yellow"
|
||||
} else {
|
||||
res = "red"
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
|
||||
renderTableHead() {
|
||||
return ["status", "currency pair", "base price", "amount", "Profit/Loss", "actions"].map((entry) => {
|
||||
return (
|
||||
<th scope="col"
|
||||
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
{entry}
|
||||
</th>
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
renderTableRows() {
|
||||
return this.props.positions.map((position) => {
|
||||
// TODO: move symbolToPair out of here?
|
||||
const stateBg = "bg-".concat(this.stateColor(position.state)).concat("-100 ")
|
||||
const stateText = "text-".concat(this.stateColor(position.state)).concat("-800 ")
|
||||
const stateClass = "px-2 inline-flex text-xs leading-5 font-semibold rounded-full ".concat(stateBg).concat(stateText)
|
||||
|
||||
return (
|
||||
<tr key={position.id}>
|
||||
{/* Status */}
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<span
|
||||
className={stateClass}>
|
||||
{position.state}
|
||||
</span>
|
||||
</td>
|
||||
|
||||
<td className="px-6 py-1 whitespace-nowrap">
|
||||
<div className="text-sm text-gray-900">{position.pair.base}/{position.pair.quote}</div>
|
||||
{/*<div className="text-sm text-gray-500">{position.}</div>*/}
|
||||
</td>
|
||||
|
||||
<td className="px-6 py-1 whitespace-nowrap">
|
||||
<div
|
||||
className="text-sm text-gray-900">{position.base_price.toLocaleString()} {position.pair.quote}/{position.pair.base}</div>
|
||||
{/*<div className="text-sm text-gray-500">Insert total % here?</div>*/}
|
||||
</td>
|
||||
|
||||
<td className="px-6 py-1 whitespace-nowrap">
|
||||
<div className="text-sm text-gray-900">{position.amount.toFixed(5)} {position.pair.base}</div>
|
||||
<div className="text-sm text-gray-500">Insert total % here?</div>
|
||||
</td>
|
||||
|
||||
<td className="px-6 py-1 whitespace-nowrap">
|
||||
<div
|
||||
className="text-sm text-gray-900 font-semibold">{position.profit_loss.toLocaleString()} {position.pair.quote}</div>
|
||||
<div className={"text-sm ".concat(stateClass)}>{position.profit_loss_percentage.toFixed(2)}%
|
||||
</div>
|
||||
</td>
|
||||
|
||||
<td className="px-6 py-1 whitespace-nowrap text-right text-sm font-medium">
|
||||
<div className="p-2 md:w-40">
|
||||
<div
|
||||
className="p-4 flex justify-center bg-red-200 rounded-lg shadow-xs cursor-pointer hover:bg-red-500 hover:text-red-100"
|
||||
onClick={() => {
|
||||
this.setState({
|
||||
showConfirmation: true,
|
||||
positionToClose: position.id
|
||||
})
|
||||
}}>
|
||||
<span className="ml-2">Close</span>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
<ClosePositionModal positionId={this.state.positionToClose} toggleConfirmation={this.toggleConfirmation}
|
||||
show={this.state.showConfirmation} />
|
||||
<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="shadow overflow-hidden border-b border-gray-200 sm:rounded-lg">
|
||||
<table className="min-w-full divide-y divide-gray-200">
|
||||
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
{this.renderTableHead()}
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{this.renderTableRows()}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
)
|
||||
}
|
||||
}
|
1
websrc/src/css/.gitignore
vendored
Normal file
1
websrc/src/css/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
tailwind.css
|
3
websrc/src/css/index.css
Normal file
3
websrc/src/css/index.css
Normal file
@ -0,0 +1,3 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
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';
|
15
websrc/src/index.tsx
Normal file
15
websrc/src/index.tsx
Normal file
@ -0,0 +1,15 @@
|
||||
import React from "react";
|
||||
import ReactDOM from "react-dom";
|
||||
import "./css/tailwind.css";
|
||||
import App from "./components/App";
|
||||
import io from "socket.io-client";
|
||||
|
||||
export const socket = io.io();
|
||||
|
||||
socket.on("connect", function () {
|
||||
console.log("Connected!")
|
||||
})
|
||||
|
||||
const ws = new WebSocket('ws://localhost:8080');
|
||||
|
||||
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" />
|
82
websrc/src/types.ts
Normal file
82
websrc/src/types.ts
Normal file
@ -0,0 +1,82 @@
|
||||
|
||||
/*******************************
|
||||
* Types
|
||||
*******************************/
|
||||
|
||||
export type Balance = {
|
||||
currency: string,
|
||||
amount: number,
|
||||
// exchange / margin
|
||||
kind: string,
|
||||
quote: string,
|
||||
quote_equivalent: number,
|
||||
}
|
||||
|
||||
export type CurrencyPair = {
|
||||
base: string,
|
||||
quote: string
|
||||
}
|
||||
|
||||
export type EventProp = {
|
||||
id: number,
|
||||
name: string,
|
||||
tick: number
|
||||
}
|
||||
|
||||
export type FirstConnectMessage = {
|
||||
ticks: Array<number>,
|
||||
prices: Array<number>,
|
||||
positions: Array<PositionProp>,
|
||||
balances: Array<Balance>
|
||||
}
|
||||
|
||||
export type GetProfitLossMessage = {
|
||||
start: number,
|
||||
end: number
|
||||
}
|
||||
|
||||
export type NewEventMessage = {
|
||||
tick: number,
|
||||
kind: string,
|
||||
}
|
||||
|
||||
export type NewTickMessage = {
|
||||
tick: number,
|
||||
price: number,
|
||||
positions: Array<PositionProp>,
|
||||
balances: Array<Balance>
|
||||
}
|
||||
|
||||
export type PositionCloseMessage = {
|
||||
message_name: string,
|
||||
position_id: number,
|
||||
}
|
||||
|
||||
export type PositionProp = {
|
||||
id: number,
|
||||
state: string,
|
||||
base_price: number,
|
||||
amount: number,
|
||||
pair: CurrencyPair,
|
||||
profit_loss: number,
|
||||
profit_loss_percentage: number
|
||||
}
|
||||
|
||||
export type PutProfitLossMessage = {
|
||||
pl: number,
|
||||
pl_perc: number
|
||||
}
|
||||
|
||||
/*******************************
|
||||
* ENUMS
|
||||
*******************************/
|
||||
|
||||
export enum EventName {
|
||||
NewTick = "new_tick",
|
||||
FirstConnect = "first_connect",
|
||||
NewEvent = "new_event",
|
||||
ClosePosition = "close_position",
|
||||
GetProfitLoss = "get_profit_loss",
|
||||
PutProfitLoss = "put_profit_loss"
|
||||
}
|
||||
|
45
websrc/src/utils.ts
Normal file
45
websrc/src/utils.ts
Normal file
@ -0,0 +1,45 @@
|
||||
import { CurrencyPair } from "./types";
|
||||
// import * as Icon from 'react-cryptocoins'
|
||||
import { Btc, Eth, Xmr } from 'react-cryptocoins';
|
||||
|
||||
export function symbolToPair(symbol: string): CurrencyPair {
|
||||
const symbol_regex = "t(?<base>[a-zA-Z]{3})(?<quote>[a-zA-Z]{3})"
|
||||
|
||||
const match = symbol.match(symbol_regex)
|
||||
|
||||
if (!match?.groups) {
|
||||
return { base: "undefined", quote: "undefined" }
|
||||
}
|
||||
|
||||
return {
|
||||
base: match.groups.base,
|
||||
quote: match.groups.quote
|
||||
}
|
||||
}
|
||||
|
||||
export type SymbolAccesory = {
|
||||
name: string,
|
||||
icon: React.Component,
|
||||
color: string
|
||||
}
|
||||
|
||||
export const SymbolAccessories: Array<SymbolAccesory> = [
|
||||
{
|
||||
name: "BTC",
|
||||
icon: Btc,
|
||||
color: "yellow"
|
||||
},
|
||||
{
|
||||
name: "XMR",
|
||||
icon: Xmr,
|
||||
color: "yellow"
|
||||
},
|
||||
{
|
||||
name: "ETH",
|
||||
icon: Eth,
|
||||
color: "yellow"
|
||||
}
|
||||
];
|
||||
|
||||
|
||||
|
29
websrc/tsconfig.json
Normal file
29
websrc/tsconfig.json
Normal file
@ -0,0 +1,29 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es5",
|
||||
"lib": [
|
||||
"dom",
|
||||
"dom.iterable",
|
||||
"esnext"
|
||||
],
|
||||
"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"
|
||||
]
|
||||
}
|
14196
websrc/yarn.lock
Normal file
14196
websrc/yarn.lock
Normal file
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue
Block a user