Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/add dashboard auth #58

Merged
merged 18 commits into from
Jul 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bots/controllers/directional_trading/macd_bb_v1.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ class MACDBBV1Controller(DirectionalTradingControllerBase):

def __init__(self, config: MACDBBV1ControllerConfig, *args, **kwargs):
self.config = config
self.max_records = max(config.macd_slow, config.macd_fast, config.macd_signal, config.bb_length)
self.max_records = max(config.macd_slow, config.macd_fast, config.macd_signal, config.bb_length) + 200
if len(self.config.candles_config) == 0:
self.config.candles_config = [CandlesConfig(
connector=config.candles_connector,
Expand Down
2 changes: 1 addition & 1 deletion bots/controllers/market_making/pmm_dynamic.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ class PMMDynamicController(MarketMakingControllerBase):
"""
def __init__(self, config: PMMDynamicControllerConfig, *args, **kwargs):
self.config = config
self.max_records = max(config.macd_slow, config.macd_fast, config.macd_signal, config.natr_length) + 10
self.max_records = max(config.macd_slow, config.macd_fast, config.macd_signal, config.natr_length) + 200
if len(self.config.candles_config) == 0:
self.config.candles_config = [CandlesConfig(
connector=config.candles_connector,
Expand Down
15 changes: 15 additions & 0 deletions credentials.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# This only works if you change the env variable in the docker-compose.yml
credentials:
usernames:
admin:
email: [email protected]
name: Admin User
logged_in: False
password: abc
cookie:
expiry_days: 0
key: some_signature_key # Must be string
name: some_cookie_name
pre-authorized:
emails:
- [email protected]
4 changes: 4 additions & 0 deletions docker-compose-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,12 @@ services:
ports:
- "8501:8501"
environment:
- AUTH_SYSTEM_ENABLED=False
- BACKEND_API_HOST=backend-api
- BACKEND_API_PORT=8000
volumes:
- ./credentials.yml:/home/dashboard/credentials.yml
- ./pages:/home/dashboard/frontend/pages
networks:
- emqx-bridge
backend-api:
Expand Down
4 changes: 4 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,12 @@ services:
ports:
- "8501:8501"
environment:
- AUTH_SYSTEM_ENABLED=False
- BACKEND_API_HOST=backend-api
- BACKEND_API_PORT=8000
volumes:
- ./credentials.yml:/home/dashboard/credentials.yml
- ./pages:/home/dashboard/frontend/pages
networks:
- emqx-bridge
backend-api:
Expand Down
Empty file added pages/__init__.py
Empty file.
Empty file added pages/config/__init__.py
Empty file.
67 changes: 67 additions & 0 deletions pages/config/bollinger_v1/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Bollinger V1 Configuration Tool

Welcome to the Bollinger V1 Configuration Tool! This tool allows you to create, modify, visualize, backtest, and save configurations for the Bollinger V1 directional trading strategy. Here’s how you can make the most out of it.

## Features

- **Start from Default Configurations**: Begin with a default configuration or use the values from an existing configuration.
- **Modify Configuration Values**: Change various parameters of the configuration to suit your trading strategy.
- **Visualize Results**: See the impact of your changes through visual charts.
- **Backtest Your Strategy**: Run backtests to evaluate the performance of your strategy.
- **Save and Deploy**: Once satisfied, save the configuration to deploy it later.

## How to Use

### 1. Load Default Configuration

Start by loading the default configuration for the Bollinger V1 strategy. This provides a baseline setup that you can customize to fit your needs.

### 2. User Inputs

Input various parameters for the strategy configuration. These parameters include:

- **Connector Name**: Select the trading platform or exchange.
- **Trading Pair**: Choose the cryptocurrency trading pair.
- **Leverage**: Set the leverage ratio. (Note: if you are using spot trading, set the leverage to 1)
- **Total Amount (Quote Currency)**: Define the total amount you want to allocate for trading.
- **Max Executors per Side**: Specify the maximum number of executors per side.
- **Cooldown Time**: Set the cooldown period between trades.
- **Position Mode**: Choose between different position modes.
- **Candles Connector**: Select the data source for candlestick data.
- **Candles Trading Pair**: Choose the trading pair for candlestick data.
- **Interval**: Set the interval for candlestick data.
- **Bollinger Bands Length**: Define the length of the Bollinger Bands.
- **Standard Deviation Multiplier**: Set the standard deviation multiplier for the Bollinger Bands.
- **Long Threshold**: Configure the threshold for long positions.
- **Short Threshold**: Configure the threshold for short positions.
- **Risk Management**: Set parameters for stop loss, take profit, time limit, and trailing stop settings.

### 3. Visualize Bollinger Bands

Visualize the Bollinger Bands on the OHLC (Open, High, Low, Close) chart to see the impact of your configuration. Here are some hints to help you fine-tune the Bollinger Bands:

- **Bollinger Bands Length**: A larger length will make the Bollinger Bands wider and smoother, while a smaller length will make them narrower and more volatile.
- **Long Threshold**: This is a reference to the Bollinger Band. A value of 0 means the lower band, and a value of 1 means the upper band. For example, if the long threshold is 0, long positions will only be taken if the price is below the lower band.
- **Short Threshold**: Similarly, a value of 1.1 means the price must be above the upper band by 0.1 of the band’s range to take a short position.
- **Thresholds**: The closer you set the thresholds to 0.5, the more trades will be executed. The farther away they are, the fewer trades will be executed.

### 4. Executor Distribution

The total amount in the quote currency will be distributed among the maximum number of executors per side. For example, if the total amount quote is 1000 and the max executors per side is 5, each executor will have 200 to trade. If the signal is on, the first executor will place an order and wait for the cooldown time before the next one executes, continuing this pattern for the subsequent orders.

### 5. Backtesting

Run backtests to evaluate the performance of your configured strategy. The backtesting section allows you to:

- **Process Data**: Analyze historical trading data.
- **Visualize Results**: See performance metrics and charts.
- **Evaluate Accuracy**: Assess the accuracy of your strategy’s predictions and trades.
- **Understand Close Types**: Review different types of trade closures and their frequencies.

### 6. Save Configuration

Once you are satisfied with your configuration and backtest results, save the configuration for future use in the Deploy tab. This allows you to deploy the same strategy later without having to reconfigure it from scratch.

---

Feel free to experiment with different configurations to find the optimal setup for your trading strategy. Happy trading!
Empty file.
65 changes: 65 additions & 0 deletions pages/config/bollinger_v1/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import pandas_ta as ta # noqa: F401
import streamlit as st
from plotly.subplots import make_subplots

from frontend.components.backtesting import backtesting_section
from frontend.components.config_loader import get_default_config_loader
from frontend.components.save_config import render_save_config
from frontend.pages.config.bollinger_v1.user_inputs import user_inputs
from frontend.pages.config.utils import get_candles
from frontend.st_utils import get_backend_api_client, initialize_st_page
from frontend.visualization import theme
from frontend.visualization.backtesting import create_backtesting_figure
from frontend.visualization.backtesting_metrics import render_accuracy_metrics, render_backtesting_metrics, render_close_types
from frontend.visualization.candles import get_candlestick_trace
from frontend.visualization.indicators import get_bbands_traces, get_volume_trace
from frontend.visualization.signals import get_bollinger_v1_signal_traces
from frontend.visualization.utils import add_traces_to_fig

# Initialize the Streamlit page
initialize_st_page(title="Bollinger V1", icon="📈", initial_sidebar_state="expanded")
backend_api_client = get_backend_api_client()

st.text("This tool will let you create a config for Bollinger V1 and visualize the strategy.")
get_default_config_loader("bollinger_v1")

inputs = user_inputs()
st.session_state["default_config"].update(inputs)

st.write("### Visualizing Bollinger Bands and Trading Signals")
days_to_visualize = st.number_input("Days to Visualize", min_value=1, max_value=365, value=7)
# Load candle data
candles = get_candles(connector_name=inputs["candles_connector"], trading_pair=inputs["candles_trading_pair"],
interval=inputs["interval"], days=days_to_visualize)

# Create a subplot with 2 rows
fig = make_subplots(rows=2, cols=1, shared_xaxes=True,
vertical_spacing=0.02, subplot_titles=('Candlestick with Bollinger Bands', 'Volume'),
row_heights=[0.8, 0.2])

add_traces_to_fig(fig, [get_candlestick_trace(candles)], row=1, col=1)
add_traces_to_fig(fig, get_bbands_traces(candles, inputs["bb_length"], inputs["bb_std"]), row=1, col=1)
add_traces_to_fig(fig, get_bollinger_v1_signal_traces(candles, inputs["bb_length"], inputs["bb_std"],
inputs["bb_long_threshold"], inputs["bb_short_threshold"]), row=1,
col=1)
add_traces_to_fig(fig, [get_volume_trace(candles)], row=2, col=1)

fig.update_layout(**theme.get_default_layout())
# Use Streamlit's functionality to display the plot
st.plotly_chart(fig, use_container_width=True)
bt_results = backtesting_section(inputs, backend_api_client)
if bt_results:
fig = create_backtesting_figure(
df=bt_results["processed_data"],
executors=bt_results["executors"],
config=inputs)
c1, c2 = st.columns([0.9, 0.1])
with c1:
render_backtesting_metrics(bt_results["results"])
st.plotly_chart(fig, use_container_width=True)
with c2:
render_accuracy_metrics(bt_results["results"])
st.write("---")
render_close_types(bt_results["results"])
st.write("---")
render_save_config(st.session_state["default_config"]["id"], st.session_state["default_config"])
51 changes: 51 additions & 0 deletions pages/config/bollinger_v1/user_inputs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import streamlit as st

from frontend.components.directional_trading_general_inputs import get_directional_trading_general_inputs
from frontend.components.risk_management import get_risk_management_inputs


def user_inputs():
default_config = st.session_state.get("default_config", {})
bb_length = default_config.get("bb_length", 100)
bb_std = default_config.get("bb_std", 2.0)
bb_long_threshold = default_config.get("bb_long_threshold", 0.0)
bb_short_threshold = default_config.get("bb_short_threshold", 1.0)
connector_name, trading_pair, leverage, total_amount_quote, max_executors_per_side, cooldown_time, position_mode, \
candles_connector_name, candles_trading_pair, interval = get_directional_trading_general_inputs()
sl, tp, time_limit, ts_ap, ts_delta, take_profit_order_type = get_risk_management_inputs()
with st.expander("Bollinger Bands Configuration", expanded=True):
c1, c2, c3, c4 = st.columns(4)
with c1:
bb_length = st.number_input("Bollinger Bands Length", min_value=5, max_value=1000, value=bb_length)
with c2:
bb_std = st.number_input("Standard Deviation Multiplier", min_value=1.0, max_value=2.0, value=bb_std)
with c3:
bb_long_threshold = st.number_input("Long Threshold", value=bb_long_threshold)
with c4:
bb_short_threshold = st.number_input("Short Threshold", value=bb_short_threshold)
return {
"controller_name": "bollinger_v1",
"controller_type": "directional_trading",
"connector_name": connector_name,
"trading_pair": trading_pair,
"leverage": leverage,
"total_amount_quote": total_amount_quote,
"max_executors_per_side": max_executors_per_side,
"cooldown_time": cooldown_time,
"position_mode": position_mode,
"candles_connector": candles_connector_name,
"candles_trading_pair": candles_trading_pair,
"interval": interval,
"bb_length": bb_length,
"bb_std": bb_std,
"bb_long_threshold": bb_long_threshold,
"bb_short_threshold": bb_short_threshold,
"stop_loss": sl,
"take_profit": tp,
"time_limit": time_limit,
"trailing_stop": {
"activation_price": ts_ap,
"trailing_delta": ts_delta
},
"take_profit_order_type": take_profit_order_type.value
}
61 changes: 61 additions & 0 deletions pages/config/dman_maker_v2/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# D-Man Maker V2 Configuration Tool

Welcome to the D-Man Maker V2 Configuration Tool! This tool allows you to create, modify, visualize, backtest, and save configurations for the D-Man Maker V2 trading strategy. Here’s how you can make the most out of it.

## Features

- **Start from Default Configurations**: Begin with a default configuration or use the values from an existing configuration.
- **Modify Configuration Values**: Change various parameters of the configuration to suit your trading strategy.
- **Visualize Results**: See the impact of your changes through visual charts.
- **Backtest Your Strategy**: Run backtests to evaluate the performance of your strategy.
- **Save and Deploy**: Once satisfied, save the configuration to deploy it later.

## How to Use

### 1. Load Default Configuration

Start by loading the default configuration for the D-Man Maker V2 strategy. This provides a baseline setup that you can customize to fit your needs.

### 2. User Inputs

Input various parameters for the strategy configuration. These parameters include:

- **Connector Name**: Select the trading platform or exchange.
- **Trading Pair**: Choose the cryptocurrency trading pair.
- **Leverage**: Set the leverage ratio. (Note: if you are using spot trading, set the leverage to 1)
- **Total Amount (Quote Currency)**: Define the total amount you want to allocate for trading.
- **Position Mode**: Choose between different position modes.
- **Cooldown Time**: Set the cooldown period between trades.
- **Executor Refresh Time**: Define how often the executors refresh.
- **Buy/Sell Spread Distributions**: Configure the distribution of buy and sell spreads.
- **Order Amounts**: Specify the percentages for buy and sell order amounts.
- **Custom D-Man Maker V2 Settings**: Set specific parameters like top executor refresh time and activation bounds.

### 3. Executor Distribution Visualization

Visualize the distribution of your trading executors. This helps you understand how your buy and sell orders are spread across different price levels and amounts.

### 4. DCA Distribution

After setting the executor distribution, you will need to configure the internal distribution of the DCA (Dollar Cost Averaging). This involves multiple open orders and one close order per executor level. Visualize the DCA distribution to see how the entry prices are spread and ensure the initial DCA order amounts are above the minimum order size of the exchange.

### 5. Risk Management

Configure risk management settings, including take profit, stop loss, time limit, and trailing stop settings for each DCA. This step is crucial for managing your trades and minimizing risk.

### 6. Backtesting

Run backtests to evaluate the performance of your configured strategy. The backtesting section allows you to:

- **Process Data**: Analyze historical trading data.
- **Visualize Results**: See performance metrics and charts.
- **Evaluate Accuracy**: Assess the accuracy of your strategy’s predictions and trades.
- **Understand Close Types**: Review different types of trade closures and their frequencies.

### 7. Save Configuration

Once you are satisfied with your configuration and backtest results, save the configuration for future use in the Deploy tab. This allows you to deploy the same strategy later without having to reconfigure it from scratch.

---

Feel free to experiment with different configurations to find the optimal setup for your trading strategy. Happy trading!
Empty file.
68 changes: 68 additions & 0 deletions pages/config/dman_maker_v2/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import streamlit as st

from frontend.components.backtesting import backtesting_section
from frontend.components.config_loader import get_default_config_loader
from frontend.components.dca_distribution import get_dca_distribution_inputs
from frontend.components.save_config import render_save_config
from frontend.pages.config.dman_maker_v2.user_inputs import user_inputs
from frontend.st_utils import get_backend_api_client, initialize_st_page
from frontend.visualization.backtesting import create_backtesting_figure
from frontend.visualization.backtesting_metrics import render_accuracy_metrics, render_backtesting_metrics, render_close_types
from frontend.visualization.dca_builder import create_dca_graph
from frontend.visualization.executors_distribution import create_executors_distribution_traces

# Initialize the Streamlit page
initialize_st_page(title="D-Man Maker V2", icon="🧙‍♂️")
backend_api_client = get_backend_api_client()

# Page content
st.text("This tool will let you create a config for D-Man Maker V2 and upload it to the BackendAPI.")
get_default_config_loader("dman_maker_v2")

inputs = user_inputs()
with st.expander("Executor Distribution:", expanded=True):
fig = create_executors_distribution_traces(inputs["buy_spreads"], inputs["sell_spreads"], inputs["buy_amounts_pct"],
inputs["sell_amounts_pct"], inputs["total_amount_quote"])
st.plotly_chart(fig, use_container_width=True)

dca_inputs = get_dca_distribution_inputs()

st.write("### Visualizing DCA Distribution for specific Executor Level")
st.write("---")
buy_order_levels = len(inputs["buy_spreads"])
sell_order_levels = len(inputs["sell_spreads"])

buy_executor_levels = [f"BUY_{i}" for i in range(buy_order_levels)]
sell_executor_levels = [f"SELL_{i}" for i in range(sell_order_levels)]
c1, c2 = st.columns(2)
with c1:
executor_level = st.selectbox("Executor Level", buy_executor_levels + sell_executor_levels)
side, level = executor_level.split("_")
if side == "BUY":
dca_amount = inputs["buy_amounts_pct"][int(level)] * inputs["total_amount_quote"]
else:
dca_amount = inputs["sell_amounts_pct"][int(level)] * inputs["total_amount_quote"]
with c2:
st.metric(label="DCA Amount", value=f"{dca_amount:.2f}")
fig = create_dca_graph(dca_inputs, dca_amount)
st.plotly_chart(fig, use_container_width=True)

# Combine inputs and dca_inputs into final config
config = {**inputs, **dca_inputs}
st.session_state["default_config"].update(config)
bt_results = backtesting_section(config, backend_api_client)
if bt_results:
fig = create_backtesting_figure(
df=bt_results["processed_data"],
executors=bt_results["executors"],
config=inputs)
c1, c2 = st.columns([0.9, 0.1])
with c1:
render_backtesting_metrics(bt_results["results"])
st.plotly_chart(fig, use_container_width=True)
with c2:
render_accuracy_metrics(bt_results["results"])
st.write("---")
render_close_types(bt_results["results"])
st.write("---")
render_save_config(st.session_state["default_config"]["id"], st.session_state["default_config"])
Loading