Compare commits
49 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
d08e175ea7 | ||
|
bf85e39c2c | ||
|
fbe445f712 | ||
|
78b5b4d0f7 | ||
|
4f7d9042d6 | ||
|
f43fcb0206 | ||
|
354ef407f3 | ||
|
a3ce3682ad | ||
|
f4431f26c0 | ||
|
545bfe28de | ||
|
8bd9eb048d | ||
|
093269b173 | ||
|
5cd6f8d37c | ||
|
a2cddead14 | ||
|
8e6e58435d | ||
|
df45866b5f | ||
|
793fd40b4c | ||
|
888843d853 | ||
|
9be8c2e6ff | ||
|
1948b0f032 | ||
|
fdc93e9cbe | ||
|
d8d0e07a0b | ||
|
415944bde5 | ||
|
6d873f3c14 | ||
|
f31c778d66 | ||
|
5e39f2767f | ||
|
4df9e38569 | ||
|
0df1511a59 | ||
|
47ddc44721 | ||
|
f4d7786e03 | ||
|
551ca054c6 | ||
|
a73e59e0e3 | ||
|
20b838f635 | ||
|
2aa9bcdb95 | ||
|
3adceef1e9 | ||
|
4592d755aa | ||
|
ae54166ea2 | ||
|
b5007c8f95 | ||
|
634f86c6fa | ||
|
669bd70946 | ||
|
2d81358fa0 | ||
|
386137f16e | ||
|
35d967e6d9 | ||
|
7252dd4f8b | ||
23e5f2fbae | |||
bc78d3247b | |||
|
96c694c2a3 | ||
6960bb85a2 | |||
|
3f5e6e3a70 |
136
rustybot/Cargo.lock → Cargo.lock
generated
136
rustybot/Cargo.lock → Cargo.lock
generated
@ -2,9 +2,9 @@
|
||||
# It is not intended for manual editing.
|
||||
[[package]]
|
||||
name = "addr2line"
|
||||
version = "0.14.0"
|
||||
version = "0.14.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7c0929d69e78dd9bf5408269919fcbcaeb2e35e5d43e5815517cdc6a8e11a423"
|
||||
checksum = "a55f82cfe485775d02112886f4169bde0c5894d75e79ead7eafe7e40a25e45f7"
|
||||
dependencies = [
|
||||
"gimli",
|
||||
]
|
||||
@ -75,9 +75,9 @@ checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"
|
||||
|
||||
[[package]]
|
||||
name = "backtrace"
|
||||
version = "0.3.55"
|
||||
version = "0.3.56"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ef5140344c85b01f9bbb4d4b7288a8aa4b3287ccef913a14bcc78a1063623598"
|
||||
checksum = "9d117600f438b1707d4e4ae15d3595657288f8235a0eb593e80ecc98ab34e1bc"
|
||||
dependencies = [
|
||||
"addr2line",
|
||||
"cfg-if 1.0.0",
|
||||
@ -87,12 +87,6 @@ dependencies = [
|
||||
"rustc-demangle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.12.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3441f0f7b02788e948e47f457ca01f1d7e6d92c693bc132c22b087d3141c03ff"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.13.0"
|
||||
@ -114,8 +108,8 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"tokio 1.1.0",
|
||||
"tungstenite 0.12.0",
|
||||
"tokio",
|
||||
"tungstenite 0.13.0",
|
||||
"url",
|
||||
]
|
||||
|
||||
@ -152,12 +146,6 @@ version = "0.5.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e4cec68f03f32e44924783795810fa50a7035d8c8ebe78580ad7e6c703fba38"
|
||||
|
||||
[[package]]
|
||||
name = "bytes"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e0dcbc35f504eb6fc275a6d20e4ebcda18cf50d40ba6fabff8c711fa16cb3b16"
|
||||
|
||||
[[package]]
|
||||
name = "bytes"
|
||||
version = "1.0.1"
|
||||
@ -249,6 +237,17 @@ 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"
|
||||
@ -386,7 +385,7 @@ checksum = "fde5a672a61f96552aa5ed9fd9c81c3fbdae4be9b1e205d6eaf17c83705adc0f"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"pin-project-lite",
|
||||
"tokio 1.1.0",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -476,7 +475,7 @@ dependencies = [
|
||||
"http",
|
||||
"indexmap",
|
||||
"slab",
|
||||
"tokio 1.1.0",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"tracing",
|
||||
"tracing-futures",
|
||||
@ -554,7 +553,7 @@ dependencies = [
|
||||
"itoa",
|
||||
"pin-project 1.0.2",
|
||||
"socket2",
|
||||
"tokio 1.1.0",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
"want",
|
||||
@ -569,7 +568,7 @@ dependencies = [
|
||||
"bytes 1.0.1",
|
||||
"hyper",
|
||||
"native-tls",
|
||||
"tokio 1.1.0",
|
||||
"tokio",
|
||||
"tokio-native-tls",
|
||||
]
|
||||
|
||||
@ -594,15 +593,6 @@ dependencies = [
|
||||
"hashbrown",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "input_buffer"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "19a8a95243d5a0398cae618ec29477c6e3cb631152be5c19481f80bc71559754"
|
||||
dependencies = [
|
||||
"bytes 0.5.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "input_buffer"
|
||||
version = "0.4.0"
|
||||
@ -812,9 +802,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "object"
|
||||
version = "0.22.0"
|
||||
version = "0.23.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8d3b63360ec3cb337817c2dbd47ab4a0f170d285d8e5a2064600f3def1402397"
|
||||
checksum = "a9a7ab5d64814df0fe4a4b5ead45ed6c5f181ee3ff04ba344313a6c80446c5d4"
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
@ -1130,7 +1120,7 @@ version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fd281b1030aa675fb90aa994d07187645bb3c8fc756ca766e7c3070b439de9de"
|
||||
dependencies = [
|
||||
"base64 0.13.0",
|
||||
"base64",
|
||||
"bytes 1.0.1",
|
||||
"encoding_rs",
|
||||
"futures-core",
|
||||
@ -1149,7 +1139,7 @@ dependencies = [
|
||||
"pin-project-lite",
|
||||
"serde",
|
||||
"serde_urlencoded",
|
||||
"tokio 1.1.0",
|
||||
"tokio",
|
||||
"tokio-native-tls",
|
||||
"url",
|
||||
"wasm-bindgen",
|
||||
@ -1180,7 +1170,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e3bad0ee36814ca07d7968269dd4b7ec89ec2da10c4bb613928d3077083c232"
|
||||
|
||||
[[package]]
|
||||
name = "rustybot"
|
||||
name = "rustico"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
@ -1189,6 +1179,7 @@ dependencies = [
|
||||
"chrono",
|
||||
"dotenv",
|
||||
"dyn-clone",
|
||||
"ears",
|
||||
"fern",
|
||||
"float-cmp",
|
||||
"futures-retry",
|
||||
@ -1196,8 +1187,9 @@ dependencies = [
|
||||
"log 0.4.11",
|
||||
"merge",
|
||||
"regex",
|
||||
"tokio 1.1.0",
|
||||
"tokio",
|
||||
"tokio-tungstenite",
|
||||
"tungstenite 0.12.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -1361,6 +1353,26 @@ 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"
|
||||
@ -1396,20 +1408,6 @@ version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c"
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "0.3.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "720ba21c25078711bf456d607987d95bce90f7c3bea5abe1db587862e7a1e87c"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
"bytes 0.6.0",
|
||||
"libc",
|
||||
"memchr",
|
||||
"mio",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.1.0"
|
||||
@ -1448,7 +1446,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f7d995660bd2b7f8c1568414c1126076c13fbb725c40112dc0120b78eb9b717b"
|
||||
dependencies = [
|
||||
"native-tls",
|
||||
"tokio 1.1.0",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -1459,20 +1457,20 @@ checksum = "76066865172052eb8796c686f0b441a93df8b08d40a950b062ffb9a426f00edd"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"pin-project-lite",
|
||||
"tokio 1.1.0",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-tungstenite"
|
||||
version = "0.12.0"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0381c1e6e08908317cee104781ca48afe03f37cc857792b85f01f9828fb55ba3"
|
||||
checksum = "e1a5f475f1b9d077ea1017ecbc60890fda8e54942d680ca0b1d2b47cfa2d861b"
|
||||
dependencies = [
|
||||
"futures-util",
|
||||
"log 0.4.11",
|
||||
"pin-project 1.0.2",
|
||||
"tokio 0.3.6",
|
||||
"tungstenite 0.11.1",
|
||||
"tokio",
|
||||
"tungstenite 0.12.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -1487,7 +1485,7 @@ dependencies = [
|
||||
"futures-sink",
|
||||
"log 0.4.11",
|
||||
"pin-project-lite",
|
||||
"tokio 1.1.0",
|
||||
"tokio",
|
||||
"tokio-stream",
|
||||
]
|
||||
|
||||
@ -1535,18 +1533,19 @@ checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642"
|
||||
|
||||
[[package]]
|
||||
name = "tungstenite"
|
||||
version = "0.11.1"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0308d80d86700c5878b9ef6321f020f29b1bb9d5ff3cab25e75e23f3a492a23"
|
||||
checksum = "8ada8297e8d70872fa9a551d93250a9f407beb9f37ef86494eb20012a2ff7c24"
|
||||
dependencies = [
|
||||
"base64 0.12.3",
|
||||
"base64",
|
||||
"byteorder",
|
||||
"bytes 0.5.6",
|
||||
"bytes 1.0.1",
|
||||
"http",
|
||||
"httparse",
|
||||
"input_buffer 0.3.1",
|
||||
"input_buffer",
|
||||
"log 0.4.11",
|
||||
"rand 0.7.3",
|
||||
"native-tls",
|
||||
"rand 0.8.2",
|
||||
"sha-1",
|
||||
"url",
|
||||
"utf-8",
|
||||
@ -1554,20 +1553,21 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tungstenite"
|
||||
version = "0.12.0"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ada8297e8d70872fa9a551d93250a9f407beb9f37ef86494eb20012a2ff7c24"
|
||||
checksum = "5fe8dada8c1a3aeca77d6b51a4f1314e0f4b8e438b7b1b71e3ddaca8080e4093"
|
||||
dependencies = [
|
||||
"base64 0.13.0",
|
||||
"base64",
|
||||
"byteorder",
|
||||
"bytes 1.0.1",
|
||||
"http",
|
||||
"httparse",
|
||||
"input_buffer 0.4.0",
|
||||
"input_buffer",
|
||||
"log 0.4.11",
|
||||
"native-tls",
|
||||
"rand 0.8.2",
|
||||
"sha-1",
|
||||
"thiserror",
|
||||
"url",
|
||||
"utf-8",
|
||||
]
|
@ -1,5 +1,5 @@
|
||||
[package]
|
||||
name = "rustybot"
|
||||
name = "rustico"
|
||||
version = "0.1.0"
|
||||
authors = ["Giulio De Pasquale <depasquale@giugl.io>"]
|
||||
edition = "2018"
|
||||
@ -9,7 +9,6 @@ edition = "2018"
|
||||
[dependencies]
|
||||
bitfinex = { path= "/home/giulio/dev/bitfinex-rs" }
|
||||
tokio = { version = "1", features=["full"]}
|
||||
tokio-tungstenite = "*"
|
||||
futures-util = { version = "0.3", default-features = false, features = ["async-await", "sink", "std"] }
|
||||
async-trait = "0.1"
|
||||
regex = "1"
|
||||
@ -21,4 +20,7 @@ byteorder = "1"
|
||||
float-cmp = "0.8"
|
||||
merge = "0.1"
|
||||
futures-retry = "0.6"
|
||||
dotenv = "0.15"
|
||||
tungstenite = "0.12"
|
||||
tokio-tungstenite = "0.13"
|
||||
dotenv = "0.15"
|
||||
ears = "0.8.0"
|
@ -1,78 +0,0 @@
|
||||
#![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,587 +0,0 @@
|
||||
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)))
|
||||
}
|
||||
}
|
BIN
sounds/smas-smb3_goal.wav
Normal file
BIN
sounds/smas-smb3_goal.wav
Normal file
Binary file not shown.
BIN
sounds/smw2_boing.wav
Normal file
BIN
sounds/smw2_boing.wav
Normal file
Binary file not shown.
BIN
sounds/smw_1-up.wav
Normal file
BIN
sounds/smw_1-up.wav
Normal file
Binary file not shown.
BIN
sounds/smw_power-up.wav
Normal file
BIN
sounds/smw_power-up.wav
Normal file
Binary file not shown.
@ -3,37 +3,35 @@ 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 BfxBot {
|
||||
pub struct Rustico {
|
||||
ticker: Ticker,
|
||||
exchange_managers: Vec<ExchangeManager>,
|
||||
frontend_connector: FrontendManagerHandle,
|
||||
}
|
||||
|
||||
impl BfxBot {
|
||||
impl Rustico {
|
||||
// TODO: change constructor to take SymbolPairs and not Symbol
|
||||
pub fn new(
|
||||
exchanges: Vec<ExchangeDetails>,
|
||||
trading_symbols: Vec<Symbol>,
|
||||
quote: Symbol,
|
||||
trading_pairs: Vec<SymbolPair>,
|
||||
tick_duration: Duration,
|
||||
) -> Self {
|
||||
let pairs: Vec<_> = trading_symbols
|
||||
.iter()
|
||||
.map(|x| SymbolPair::new(quote.clone(), x.clone()))
|
||||
.collect();
|
||||
|
||||
let exchange_managers = exchanges
|
||||
.iter()
|
||||
.map(|x| ExchangeManager::new(x, &pairs))
|
||||
.map(|x| ExchangeManager::new(x, &trading_pairs))
|
||||
.collect();
|
||||
|
||||
BfxBot {
|
||||
Rustico {
|
||||
ticker: Ticker::new(tick_duration),
|
||||
exchange_managers,
|
||||
frontend_connector: FrontendManagerHandle::new(),
|
||||
}
|
||||
}
|
||||
|
@ -4,22 +4,23 @@ use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use bitfinex::api::Bitfinex;
|
||||
use bitfinex::api::RestClient;
|
||||
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 {
|
||||
@ -36,7 +37,7 @@ pub enum ExchangeDetails {
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Client {
|
||||
exchange: Exchange,
|
||||
inner: Arc<Box<dyn Connector>>,
|
||||
inner: Arc<Box<dyn RestConnector>>,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
@ -123,7 +124,7 @@ impl Client {
|
||||
.active_orders(pair)
|
||||
.await?
|
||||
.into_iter()
|
||||
.filter(|x| &x.pair() == &pair)
|
||||
.filter(|x| x.pair() == pair)
|
||||
.collect())
|
||||
}
|
||||
|
||||
@ -164,10 +165,13 @@ 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 Connector: Send + Sync {
|
||||
pub trait RestConnector: 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>;
|
||||
@ -183,7 +187,7 @@ pub trait Connector: 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,
|
||||
@ -191,18 +195,26 @@ pub trait Connector: Send + Sync {
|
||||
async fn trading_fees(&self) -> Result<Vec<TradingFees>, BoxError>;
|
||||
}
|
||||
|
||||
impl Debug for dyn Connector {
|
||||
impl Debug for dyn RestConnector {
|
||||
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 {
|
||||
bfx: Bitfinex,
|
||||
rest: bitfinex::api::RestClient,
|
||||
ws: bitfinex::websockets::WebSocketClient,
|
||||
}
|
||||
|
||||
impl BitfinexConnector {
|
||||
@ -217,7 +229,8 @@ impl BitfinexConnector {
|
||||
|
||||
pub fn new(api_key: &str, api_secret: &str) -> Self {
|
||||
BitfinexConnector {
|
||||
bfx: Bitfinex::new(Some(api_key.into()), Some(api_secret.into())),
|
||||
rest: RestClient::new(Some(api_key.into()), Some(api_secret.into())),
|
||||
ws: WebSocketClient::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@ -235,9 +248,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 {
|
||||
@ -258,14 +271,14 @@ impl BitfinexConnector {
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Connector for BitfinexConnector {
|
||||
impl RestConnector for BitfinexConnector {
|
||||
fn name(&self) -> String {
|
||||
"Bitfinex".into()
|
||||
"Bitfinex REST".into()
|
||||
}
|
||||
|
||||
async fn active_positions(&self, pair: &SymbolPair) -> Result<Option<Vec<Position>>, BoxError> {
|
||||
let active_positions =
|
||||
BitfinexConnector::retry_nonce(|| self.bfx.positions.active_positions()).await?;
|
||||
BitfinexConnector::retry_nonce(|| self.rest.positions.active_positions()).await?;
|
||||
|
||||
let positions: Vec<_> = active_positions
|
||||
.into_iter()
|
||||
@ -273,14 +286,14 @@ impl Connector for BitfinexConnector {
|
||||
.filter(|x: &Position| x.pair() == pair)
|
||||
.collect();
|
||||
|
||||
trace!("\t[PositionManager] Retrieved positions for {}", pair);
|
||||
trace!("\tRetrieved positions for {}", pair);
|
||||
Ok((!positions.is_empty()).then_some(positions))
|
||||
}
|
||||
|
||||
async fn current_prices(&self, pair: &SymbolPair) -> Result<TradingPairTicker, BoxError> {
|
||||
let symbol_name = BitfinexConnector::format_trading_pair(pair);
|
||||
|
||||
let ticker: TradingPairTicker = self.bfx.ticker.trading_pair(symbol_name).await?;
|
||||
let ticker: TradingPairTicker = self.rest.ticker.trading_pair(symbol_name).await?;
|
||||
|
||||
Ok(ticker)
|
||||
}
|
||||
@ -289,9 +302,9 @@ impl Connector for BitfinexConnector {
|
||||
let symbol_name = BitfinexConnector::format_trading_pair(pair);
|
||||
|
||||
let response = BitfinexConnector::retry_nonce(|| {
|
||||
self.bfx.book.trading_pair(&symbol_name, BookPrecision::P0)
|
||||
self.rest.book.trading_pair(&symbol_name, BookPrecision::P0)
|
||||
})
|
||||
.await?;
|
||||
.await?;
|
||||
|
||||
let entries = response
|
||||
.into_iter()
|
||||
@ -306,7 +319,7 @@ impl Connector for BitfinexConnector {
|
||||
}
|
||||
|
||||
async fn active_orders(&self, _: &SymbolPair) -> Result<Vec<ActiveOrder>, BoxError> {
|
||||
let response = BitfinexConnector::retry_nonce(|| self.bfx.orders.active_orders()).await?;
|
||||
let response = BitfinexConnector::retry_nonce(|| self.rest.orders.active_orders()).await?;
|
||||
|
||||
Ok(response.iter().map(Into::into).collect())
|
||||
}
|
||||
@ -316,57 +329,53 @@ impl Connector for BitfinexConnector {
|
||||
let amount = order.amount();
|
||||
|
||||
let order_form = {
|
||||
let pre_leverage = {
|
||||
match order.kind() {
|
||||
OrderKind::Limit { price } => {
|
||||
bitfinex::orders::OrderForm::new(symbol_name, price, amount, order.into())
|
||||
}
|
||||
OrderKind::Market => {
|
||||
bitfinex::orders::OrderForm::new(symbol_name, 0.0, amount, order.into())
|
||||
}
|
||||
OrderKind::Stop { price } => {
|
||||
bitfinex::orders::OrderForm::new(symbol_name, price, amount, order.into())
|
||||
}
|
||||
OrderKind::StopLimit { price, limit_price } => {
|
||||
bitfinex::orders::OrderForm::new(symbol_name, price, amount, order.into())
|
||||
.with_price_aux_limit(limit_price)?
|
||||
}
|
||||
OrderKind::TrailingStop { distance } => {
|
||||
bitfinex::orders::OrderForm::new(symbol_name, 0.0, amount, order.into())
|
||||
.with_price_trailing(distance)?
|
||||
}
|
||||
OrderKind::FillOrKill { price } => {
|
||||
bitfinex::orders::OrderForm::new(symbol_name, price, amount, order.into())
|
||||
}
|
||||
OrderKind::ImmediateOrCancel { price } => {
|
||||
bitfinex::orders::OrderForm::new(symbol_name, price, amount, order.into())
|
||||
}
|
||||
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 { 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(OrderMeta::new(
|
||||
BitfinexConnector::AFFILIATE_CODE.to_string(),
|
||||
))
|
||||
};
|
||||
|
||||
// adding leverage, if any
|
||||
match order.leverage() {
|
||||
// TODO: CHANGEME!!!!
|
||||
Some(_leverage) => pre_leverage.with_leverage(15),
|
||||
// Some(leverage) => pre_leverage.with_leverage(leverage.round() as u32),
|
||||
None => pre_leverage,
|
||||
}
|
||||
.with_meta(Some(OrderMeta::new(
|
||||
BitfinexConnector::AFFILIATE_CODE.to_string(),
|
||||
)))
|
||||
// TODO: CHANGEME!
|
||||
.with_leverage(Some(15))
|
||||
};
|
||||
|
||||
let response =
|
||||
BitfinexConnector::retry_nonce(|| self.bfx.orders.submit_order(&order_form)).await?;
|
||||
BitfinexConnector::retry_nonce(|| self.rest.orders.submit_order(&order_form)).await?;
|
||||
|
||||
Ok((&response).try_into()?)
|
||||
// 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)))
|
||||
}
|
||||
|
||||
async fn cancel_order(&self, order: &ActiveOrder) -> Result<ActiveOrder, BoxError> {
|
||||
let cancel_form = order.into();
|
||||
|
||||
let response =
|
||||
BitfinexConnector::retry_nonce(|| self.bfx.orders.cancel_order(&cancel_form)).await?;
|
||||
BitfinexConnector::retry_nonce(|| self.rest.orders.cancel_order(&cancel_form)).await?;
|
||||
|
||||
Ok((&response).try_into()?)
|
||||
}
|
||||
@ -379,14 +388,14 @@ impl Connector for BitfinexConnector {
|
||||
amount: f64,
|
||||
) -> Result<(), BoxError> {
|
||||
BitfinexConnector::retry_nonce(|| {
|
||||
self.bfx.account.transfer_between_wallets(
|
||||
self.rest.account.transfer_between_wallets(
|
||||
from.into(),
|
||||
to.into(),
|
||||
symbol.to_string(),
|
||||
amount,
|
||||
)
|
||||
})
|
||||
.await?;
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@ -396,11 +405,11 @@ impl Connector for BitfinexConnector {
|
||||
order: &OrderDetails,
|
||||
) -> Result<Option<Vec<Trade>>, BoxError> {
|
||||
let response = BitfinexConnector::retry_nonce(|| {
|
||||
self.bfx
|
||||
self.rest
|
||||
.trades
|
||||
.generated_by_order(order.pair().trading_repr(), order.id())
|
||||
})
|
||||
.await?;
|
||||
.await?;
|
||||
|
||||
if response.is_empty() {
|
||||
Ok(None)
|
||||
@ -414,7 +423,7 @@ impl Connector for BitfinexConnector {
|
||||
pair: &SymbolPair,
|
||||
) -> Result<Option<Vec<OrderDetails>>, BoxError> {
|
||||
let response =
|
||||
BitfinexConnector::retry_nonce(|| self.bfx.orders.history(Some(pair.trading_repr())))
|
||||
BitfinexConnector::retry_nonce(|| self.rest.orders.history(Some(pair.trading_repr())))
|
||||
.await?;
|
||||
let mapped_vec: Vec<_> = response.iter().map(Into::into).collect();
|
||||
|
||||
@ -424,7 +433,7 @@ impl Connector for BitfinexConnector {
|
||||
async fn trading_fees(&self) -> Result<Vec<TradingFees>, BoxError> {
|
||||
let mut fees = vec![];
|
||||
let accountfees =
|
||||
BitfinexConnector::retry_nonce(|| self.bfx.account.account_summary()).await?;
|
||||
BitfinexConnector::retry_nonce(|| self.rest.account.account_summary()).await?;
|
||||
|
||||
// Derivatives
|
||||
let derivative_taker = TradingFees::Taker {
|
||||
@ -466,6 +475,17 @@ impl Connector 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())
|
||||
@ -486,8 +506,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())))
|
||||
}
|
||||
}
|
||||
|
||||
@ -511,7 +531,6 @@ impl TryInto<Position> for bitfinex::positions::Position {
|
||||
}
|
||||
};
|
||||
|
||||
println!("leverage: {}", self.leverage());
|
||||
Ok(Position::new(
|
||||
SymbolPair::from_str(self.symbol())?,
|
||||
state,
|
||||
@ -524,8 +543,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()))
|
||||
}
|
||||
}
|
||||
|
||||
@ -603,7 +622,7 @@ impl From<&bitfinex::responses::OrderResponse> for OrderKind {
|
||||
}
|
||||
bitfinex::orders::OrderKind::StopLimit
|
||||
| bitfinex::orders::OrderKind::ExchangeStopLimit => Self::StopLimit {
|
||||
price: response.price(),
|
||||
stop_price: response.price(),
|
||||
limit_price: response.price_aux_limit().expect("Limit price not found!"),
|
||||
},
|
||||
bitfinex::orders::OrderKind::TrailingStop
|
||||
@ -642,7 +661,7 @@ impl From<&bitfinex::orders::ActiveOrder> for OrderKind {
|
||||
}
|
||||
bitfinex::orders::OrderKind::StopLimit
|
||||
| bitfinex::orders::OrderKind::ExchangeStopLimit => Self::StopLimit {
|
||||
price: response.price(),
|
||||
stop_price: response.price(),
|
||||
limit_price: response.price_aux_limit().expect("Limit price not found!"),
|
||||
},
|
||||
bitfinex::orders::OrderKind::TrailingStop
|
||||
@ -675,8 +694,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,6 +31,8 @@ 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");
|
||||
@ -74,8 +76,8 @@ pub struct SymbolPair {
|
||||
}
|
||||
|
||||
impl SymbolPair {
|
||||
pub fn new(quote: Symbol, base: Symbol) -> Self {
|
||||
SymbolPair { quote, base }
|
||||
pub fn new(base: Symbol, quote: Symbol) -> Self {
|
||||
SymbolPair { base, quote }
|
||||
}
|
||||
pub fn trading_repr(&self) -> String {
|
||||
format!("t{}{}", self.base, self.quote)
|
@ -56,14 +56,19 @@ pub struct Event {
|
||||
}
|
||||
|
||||
impl Event {
|
||||
pub fn new(kind: EventKind, tick: u64, metadata: Option<EventMetadata>) -> Self {
|
||||
pub fn new(kind: EventKind, tick: u64) -> Self {
|
||||
Event {
|
||||
kind,
|
||||
tick,
|
||||
metadata,
|
||||
metadata: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_metadata(mut self, metadata: Option<EventMetadata>) -> Self {
|
||||
self.metadata = metadata;
|
||||
self
|
||||
}
|
||||
|
||||
fn has_metadata(&self) -> bool {
|
||||
self.metadata.is_some()
|
||||
}
|
89
src/frontend.rs
Normal file
89
src/frontend.rs
Normal file
@ -0,0 +1,89 @@
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use futures_util::stream::TryStreamExt;
|
||||
use futures_util::StreamExt;
|
||||
use log::info;
|
||||
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>,
|
||||
}
|
||||
|
||||
impl FrontendManager {
|
||||
pub fn new(receiver: Receiver<ActorMessage>) -> Self {
|
||||
Self { receiver }
|
||||
}
|
||||
|
||||
async fn handle_ws_connection(stream: TcpStream, addr: SocketAddr) -> Result<(), BoxError> {
|
||||
let websocket = accept_async(stream).await?;
|
||||
info!("Received WebSocket connection <{:?}>", addr);
|
||||
|
||||
let (_, ws_in) = websocket.split();
|
||||
|
||||
let on_received = ws_in.try_for_each(move |msg| {
|
||||
info!(
|
||||
"Received a message from {:?}: {}",
|
||||
addr,
|
||||
msg.to_text().unwrap()
|
||||
);
|
||||
|
||||
futures_util::future::ok(())
|
||||
});
|
||||
|
||||
tokio::spawn(on_received);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn websocket() -> Result<(), BoxError> {
|
||||
let server = TcpListener::bind("127.0.0.1:3012").await?;
|
||||
|
||||
while let Ok((stream, addr)) = server.accept().await {
|
||||
tokio::spawn(FrontendManager::handle_ws_connection(stream, addr));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn handle_message(&mut self, message: ActorMessage) -> Result<(), BoxError> {
|
||||
match message.message {
|
||||
_ => {}
|
||||
}
|
||||
|
||||
Ok(message
|
||||
.respond_to
|
||||
.send((None, None))
|
||||
.map_err(|_| BoxError::from("Could not send message."))?)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FrontendManagerHandle {
|
||||
sender: Sender<ActorMessage>,
|
||||
}
|
||||
|
||||
impl FrontendManagerHandle {
|
||||
// async fn run_frontend_manager(mut manager: FrontendManager) {
|
||||
// info!("Frontend handler ready");
|
||||
//
|
||||
// while let Some(msg) = manager.receiver.recv().await {
|
||||
// manager.handle_message(msg).await.unwrap();
|
||||
// }
|
||||
// }
|
||||
|
||||
pub fn new() -> Self {
|
||||
let (sender, receiver) = channel(1);
|
||||
|
||||
let _frontend = FrontendManager::new(receiver);
|
||||
|
||||
tokio::spawn(FrontendManager::websocket());
|
||||
// tokio::spawn(FrontendManagerHandle::run_frontend_manager(frontend));
|
||||
|
||||
Self { sender }
|
||||
}
|
||||
}
|
100
src/main.rs
Normal file
100
src/main.rs
Normal file
@ -0,0 +1,100 @@
|
||||
#![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,23 +1,22 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::ops::Neg;
|
||||
|
||||
use futures_util::stream::FuturesUnordered;
|
||||
use futures_util::StreamExt;
|
||||
use log::{debug, error, info, trace};
|
||||
use merge::Merge;
|
||||
use tokio::sync::mpsc::channel;
|
||||
use tokio::sync::mpsc::{Receiver, Sender};
|
||||
use tokio::sync::mpsc::channel;
|
||||
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, Position, PriceTicker,
|
||||
};
|
||||
use crate::strategy::{HiddenTrailingStop, MarketEnforce, OrderStrategy, PositionStrategy};
|
||||
use crate::BoxError;
|
||||
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};
|
||||
|
||||
pub type OptionUpdate = (Option<Vec<Event>>, Option<Vec<ActionMessage>>);
|
||||
|
||||
@ -234,8 +233,9 @@ 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);
|
||||
.on_tick(position, self.current_tick(), &self.positions_history, &fees);
|
||||
|
||||
let (pos_post_tick, events_post_tick, messages_post_tick) = self
|
||||
.strategy
|
||||
.post_tick(pos_on_tick, self.current_tick(), &self.positions_history);
|
||||
.post_tick(pos_on_tick, self.current_tick(), &self.positions_history, &fees);
|
||||
|
||||
events.merge(events_on_tick);
|
||||
events.merge(events_post_tick);
|
||||
@ -280,30 +280,12 @@ 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>,
|
||||
}
|
||||
@ -329,10 +311,10 @@ impl OrderManagerHandle {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new(pair: SymbolPair, client: Client, strategy: Box<dyn OrderStrategy>) -> Self {
|
||||
pub fn new(pair: SymbolPair, client: Client) -> Self {
|
||||
let (sender, receiver) = channel(1);
|
||||
|
||||
let manager = OrderManager::new(receiver, pair, client, strategy);
|
||||
let manager = OrderManager::new(receiver, pair, client);
|
||||
|
||||
tokio::spawn(OrderManagerHandle::run_order_manager(manager));
|
||||
|
||||
@ -384,11 +366,9 @@ impl OrderManagerHandle {
|
||||
|
||||
pub struct OrderManager {
|
||||
receiver: Receiver<ActorMessage>,
|
||||
tracked_positions: TrackedPositionsMap,
|
||||
orders_map: HashMap<u64, HashSet<ActiveOrder>>,
|
||||
pair: SymbolPair,
|
||||
open_orders: Vec<ActiveOrder>,
|
||||
client: Client,
|
||||
strategy: Box<dyn OrderStrategy>,
|
||||
}
|
||||
|
||||
impl OrderManager {
|
||||
@ -396,18 +376,93 @@ impl OrderManager {
|
||||
receiver: Receiver<ActorMessage>,
|
||||
pair: SymbolPair,
|
||||
client: Client,
|
||||
strategy: Box<dyn OrderStrategy>,
|
||||
) -> Self {
|
||||
OrderManager {
|
||||
receiver,
|
||||
pair,
|
||||
open_orders: Vec::new(),
|
||||
client,
|
||||
strategy,
|
||||
tracked_positions: HashMap::new(),
|
||||
orders_map: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* 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?,
|
||||
@ -429,14 +484,7 @@ 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.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();
|
||||
|
||||
if let Some(position_orders) = self.orders_map.get(&position_id) {
|
||||
for order in position_orders {
|
||||
match self.client.cancel_order(order).await {
|
||||
Ok(_) => info!("Order #{} closed successfully.", order.id()),
|
||||
@ -450,25 +498,33 @@ impl OrderManager {
|
||||
}
|
||||
|
||||
pub async fn submit_order(&mut self, order_form: &OrderForm) -> Result<OptionUpdate, BoxError> {
|
||||
info!("Submiting {}", order_form.kind());
|
||||
info!("Submitting order: {}", order_form.kind());
|
||||
|
||||
let active_order = self.client.submit_order(order_form).await?;
|
||||
|
||||
debug!("Adding order to tracked orders.");
|
||||
if let Some(metadata) = order_form.metadata() {
|
||||
if let Some(position_id) = metadata.position_id() {
|
||||
match self.tracked_positions.get_mut(&position_id) {
|
||||
None => {
|
||||
self.tracked_positions
|
||||
.insert(position_id, vec![active_order.id()]);
|
||||
}
|
||||
Some(position_orders) => {
|
||||
position_orders.push(active_order.id());
|
||||
}
|
||||
}
|
||||
// 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?
|
||||
}
|
||||
};
|
||||
|
||||
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.");
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// 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))
|
||||
}
|
||||
@ -513,10 +569,14 @@ impl OrderManager {
|
||||
position.platform(),
|
||||
position.amount().neg(),
|
||||
)
|
||||
.with_leverage(Some(position.leverage()));
|
||||
.with_leverage(Some(position.leverage()))
|
||||
.with_metadata(Some(OrderMetadata::new()
|
||||
.with_strategy(Some(Box::new(MarketEnforce::default())))
|
||||
.with_position_id(Some(position.id())))
|
||||
);
|
||||
|
||||
info!("Submitting {} order", order_form.kind());
|
||||
if let Err(e) = self.client.submit_order(&order_form).await {
|
||||
// submitting order
|
||||
if let Err(e) = self.submit_order(&order_form).await {
|
||||
error!(
|
||||
"Could not submit {} to close position #{}: {}",
|
||||
order_form.kind(),
|
||||
@ -535,47 +595,43 @@ impl OrderManager {
|
||||
pub async fn update(&mut self) -> Result<OptionUpdate, BoxError> {
|
||||
debug!("\t[OrderManager] Updating {}", self.pair);
|
||||
|
||||
let (res_open_orders, res_order_book) = tokio::join!(
|
||||
self.client.active_orders(&self.pair),
|
||||
self.client.order_book(&self.pair)
|
||||
);
|
||||
// updating internal orders' mapping from remote
|
||||
self.update_orders_map_from_remote().await?;
|
||||
|
||||
let (open_orders, order_book) = (res_open_orders?, res_order_book?);
|
||||
// calling strategies for the orders and collecting resulting messages
|
||||
let _orders_messages: HashMap<&ActiveOrder, Vec<ActionMessage>> = HashMap::new();
|
||||
|
||||
// retrieving open positions to check whether the positions have open orders.
|
||||
// we need to update our internal mapping in that case.
|
||||
if !open_orders.is_empty() {
|
||||
let open_positions = self.client.active_positions(&self.pair).await?;
|
||||
if let Some(tracked_orders) = self.all_tracked_orders() {
|
||||
// since there are open orders, retrieve order book
|
||||
let order_book = self.client.order_book(&self.pair).await?;
|
||||
|
||||
if let Some(positions) = open_positions {
|
||||
// currently, we are only trying to match orders with an amount equal to
|
||||
// a position amount.
|
||||
for position in positions {
|
||||
let matching_order = open_orders
|
||||
.iter()
|
||||
.find(|x| x.order_form().amount().abs() == position.amount().abs());
|
||||
for active_order in tracked_orders.iter().filter(|x| x.strategy().is_some()) {
|
||||
let strategy = active_order.strategy().as_ref().unwrap();
|
||||
|
||||
// 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());
|
||||
}
|
||||
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!");
|
||||
}
|
||||
None => {
|
||||
trace!(
|
||||
"Mapped order #{} to position #{}",
|
||||
position.id(),
|
||||
matching_order.id()
|
||||
);
|
||||
self.tracked_positions
|
||||
.insert(position.id(), vec![matching_order.id()]);
|
||||
_ => {
|
||||
debug!(
|
||||
"Received unsupported message from order strategy. Unimplemented."
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -583,39 +639,10 @@ 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();
|
||||
@ -657,12 +684,11 @@ impl PairManager {
|
||||
order_manager: OrderManagerHandle::new(
|
||||
pair.clone(),
|
||||
client.clone(),
|
||||
Box::new(MarketEnforce::default()),
|
||||
),
|
||||
position_manager: PositionManagerHandle::new(
|
||||
pair,
|
||||
client,
|
||||
Box::new(HiddenTrailingStop::default()),
|
||||
Box::new(TrailingStop::default()),
|
||||
),
|
||||
}
|
||||
}
|
@ -2,8 +2,11 @@ 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
|
||||
@ -148,7 +151,7 @@ impl OrderDetails {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Debug)]
|
||||
pub struct ActiveOrder {
|
||||
exchange: Exchange,
|
||||
id: u64,
|
||||
@ -158,6 +161,7 @@ pub struct ActiveOrder {
|
||||
order_form: OrderForm,
|
||||
creation_timestamp: u64,
|
||||
update_timestamp: u64,
|
||||
strategy: Option<Box<dyn OrderStrategy>>,
|
||||
}
|
||||
|
||||
impl ActiveOrder {
|
||||
@ -178,6 +182,7 @@ impl ActiveOrder {
|
||||
order_form,
|
||||
creation_timestamp,
|
||||
update_timestamp,
|
||||
strategy: None,
|
||||
}
|
||||
}
|
||||
|
||||
@ -191,6 +196,16 @@ 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
|
||||
}
|
||||
@ -215,6 +230,9 @@ 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 {
|
||||
@ -231,6 +249,22 @@ 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,
|
||||
@ -261,7 +295,7 @@ pub enum OrderKind {
|
||||
Limit { price: f64 },
|
||||
Market,
|
||||
Stop { price: f64 },
|
||||
StopLimit { price: f64, limit_price: f64 },
|
||||
StopLimit { stop_price: f64, limit_price: f64 },
|
||||
TrailingStop { distance: f64 },
|
||||
FillOrKill { price: f64 },
|
||||
ImmediateOrCancel { price: f64 },
|
||||
@ -285,31 +319,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 { price, limit_price } => {
|
||||
OrderKind::StopLimit { stop_price, limit_price } => {
|
||||
write!(
|
||||
f,
|
||||
"[{} | Price: {:0.5}, Limit Price: {:0.5}]",
|
||||
"[{} | Stop: {:0.5}, Limit: {:0.5}]",
|
||||
self.as_str(),
|
||||
price,
|
||||
stop_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, )
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -355,55 +389,90 @@ 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 { price, .. } => Some(price),
|
||||
OrderKind::StopLimit { stop_price: 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, Clone)]
|
||||
#[derive(Debug)]
|
||||
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 with_position_id(position_id: u64) -> Self {
|
||||
OrderMetadata {
|
||||
position_id: Some(position_id),
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
position_id: None,
|
||||
strategy: None,
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
/***************
|
19
src/sounds.rs
Normal file
19
src/sounds.rs
Normal file
@ -0,0 +1,19 @@
|
||||
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
Normal file
449
src/strategy.rs
Normal file
@ -0,0 +1,449 @@
|
||||
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
Normal file
89
src/tests.rs
Normal file
@ -0,0 +1,89 @@
|
||||
#[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
|
||||
}
|
||||
}
|
File diff suppressed because one or more lines are too long
23
websrc/.gitignore
vendored
23
websrc/.gitignore
vendored
@ -1,23 +0,0 @@
|
||||
# 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*
|
@ -1,70 +0,0 @@
|
||||
# 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)
|
@ -1,131 +0,0 @@
|
||||
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;
|
@ -1,155 +0,0 @@
|
||||
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>
|
||||
)
|
||||
}
|
||||
}
|
@ -1,55 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
Binary file not shown.
Before Width: | Height: | Size: 3.8 KiB |
@ -1,43 +0,0 @@
|
||||
<!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>
|
Binary file not shown.
Before Width: | Height: | Size: 5.2 KiB |
Binary file not shown.
Before Width: | Height: | Size: 9.4 KiB |
@ -1,25 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
@ -1,3 +0,0 @@
|
||||
# https://www.robotstxt.org/robotstxt.html
|
||||
User-agent: *
|
||||
Disallow:
|
@ -1,131 +0,0 @@
|
||||
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;
|
@ -1,154 +0,0 @@
|
||||
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>
|
||||
)
|
||||
}
|
||||
}
|
@ -1,9 +0,0 @@
|
||||
import React, { Component } from "react";
|
||||
import { CurrencyPair } from "../types";
|
||||
|
||||
|
||||
export type CurrencyPairProps = {
|
||||
active_pair: CurrencyPair,
|
||||
pairs: Array<CurrencyPair>
|
||||
}
|
||||
|
@ -1,50 +0,0 @@
|
||||
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>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
@ -1,71 +0,0 @@
|
||||
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>
|
||||
)
|
||||
}
|
||||
}
|
@ -1,90 +0,0 @@
|
||||
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>
|
||||
)
|
||||
}
|
||||
}
|
@ -1,168 +0,0 @@
|
||||
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;
|
@ -1,304 +0,0 @@
|
||||
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>
|
||||
)
|
||||
}
|
||||
}
|
@ -1,141 +0,0 @@
|
||||
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
1
websrc/src/css/.gitignore
vendored
@ -1 +0,0 @@
|
||||
tailwind.css
|
@ -1,3 +0,0 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
1
websrc/src/custom.d.ts
vendored
1
websrc/src/custom.d.ts
vendored
@ -1 +0,0 @@
|
||||
declare module 'react-cryptocoins';
|
@ -1,15 +0,0 @@
|
||||
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
1
websrc/src/react-app-env.d.ts
vendored
@ -1 +0,0 @@
|
||||
/// <reference types="react-scripts" />
|
@ -1,82 +0,0 @@
|
||||
|
||||
/*******************************
|
||||
* 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"
|
||||
}
|
||||
|
@ -1,45 +0,0 @@
|
||||
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"
|
||||
}
|
||||
];
|
||||
|
||||
|
||||
|
@ -1,29 +0,0 @@
|
||||
{
|
||||
"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
14196
websrc/yarn.lock
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue
Block a user