(feat) add config and backtesting pages

This commit is contained in:
cardosofede
2024-07-09 18:10:55 +03:00
parent ea3e4484a8
commit 23962833eb
40 changed files with 1975 additions and 0 deletions

0
pages/config/__init__.py Normal file
View File

View File

@@ -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. Heres 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 bands 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 strategys 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!

View File

View File

@@ -0,0 +1,65 @@
import streamlit as st
import pandas_ta as ta # noqa: F401
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.utils import get_candles
from frontend.st_utils import initialize_st_page, get_backend_api_client
from frontend.pages.config.bollinger_v1.user_inputs import user_inputs
from plotly.subplots import make_subplots
from frontend.visualization import theme
from frontend.visualization.backtesting import create_backtesting_figure
from frontend.visualization.backtesting_metrics import render_backtesting_metrics, render_accuracy_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"])

View File

@@ -0,0 +1,49 @@
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
}

View File

@@ -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. Heres 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 strategys 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!

View File

View File

@@ -0,0 +1,71 @@
import streamlit as st
from CONFIG import BACKEND_API_HOST, BACKEND_API_PORT
from backend.services.backend_api_client import BackendAPIClient
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 initialize_st_page, get_backend_api_client
from frontend.visualization.backtesting import create_backtesting_figure
from frontend.visualization.backtesting_metrics import render_backtesting_metrics, render_accuracy_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"])

View File

@@ -0,0 +1,37 @@
import streamlit as st
from frontend.components.executors_distribution import get_executors_distribution_inputs
from frontend.components.market_making_general_inputs import get_market_making_general_inputs
def user_inputs():
connector_name, trading_pair, leverage, total_amount_quote, position_mode, cooldown_time, executor_refresh_time, _, _, _ = get_market_making_general_inputs()
buy_spread_distributions, sell_spread_distributions, buy_order_amounts_pct, sell_order_amounts_pct = get_executors_distribution_inputs()
with st.expander("Custom D-Man Maker V2 Settings"):
c1, c2 = st.columns(2)
with c1:
top_executor_refresh_time = st.number_input("Top Refresh Time (minutes)", value=60) * 60
with c2:
executor_activation_bounds = st.number_input("Activation Bounds (%)", value=0.1) / 100
# Create the config
config = {
"controller_name": "dman_maker_v2",
"controller_type": "market_making",
"manual_kill_switch": None,
"candles_config": [],
"connector_name": connector_name,
"trading_pair": trading_pair,
"total_amount_quote": total_amount_quote,
"buy_spreads": buy_spread_distributions,
"sell_spreads": sell_spread_distributions,
"buy_amounts_pct": buy_order_amounts_pct,
"sell_amounts_pct": sell_order_amounts_pct,
"executor_refresh_time": executor_refresh_time,
"cooldown_time": cooldown_time,
"leverage": leverage,
"position_mode": position_mode,
"top_executor_refresh_time": top_executor_refresh_time,
"executor_activation_bounds": [executor_activation_bounds]
}
return config

View File

@@ -0,0 +1,19 @@
# D-Man Maker V2
## Features
- **Interactive Configuration**: Configure market making parameters such as spreads, amounts, and order levels through an intuitive web interface.
- **Visual Feedback**: Visualize order spread and amount distributions using dynamic Plotly charts.
- **Backend Integration**: Save and deploy configurations directly to a backend system for active management and execution.
### Using the Tool
1. **Configure Parameters**: Use the Streamlit interface to input parameters such as connector type, trading pair, and leverage.
2. **Set Distributions**: Define distributions for buy and sell orders, including spread and amount, either manually or through predefined distribution types like Geometric or Fibonacci.
3. **Visualize Orders**: View the configured order distributions on a Plotly graph, which illustrates the relationship between spread and amount.
4. **Export Configuration**: Once the configuration is set, export it as a YAML file or directly upload it to the Backend API.
5. **Upload**: Use the "Upload Config to BackendAPI" button to send your configuration to the backend system. Then can be used to deploy a new bot.
## Troubleshooting
- **UI Not Loading**: Ensure all Python dependencies are installed and that the Streamlit server is running correctly.
- **API Errors**: Check the console for any error messages that may indicate issues with the backend connection.
For more detailed documentation on the backend API and additional configurations, please refer to the project's documentation or contact the development team.

View File

147
pages/config/dman_v5/app.py Normal file
View File

@@ -0,0 +1,147 @@
import streamlit as st
import pandas as pd
import plotly.graph_objects as go
import yaml
from plotly.subplots import make_subplots
from CONFIG import BACKEND_API_HOST, BACKEND_API_PORT
from backend.services.backend_api_client import BackendAPIClient
from frontend.st_utils import initialize_st_page, get_backend_api_client
# Initialize the Streamlit page
initialize_st_page(title="D-Man V5", icon="📊", initial_sidebar_state="expanded")
@st.cache_data
def get_candles(connector_name, trading_pair, interval, max_records):
backend_client = BackendAPIClient(BACKEND_API_HOST, BACKEND_API_PORT)
return backend_client.get_real_time_candles(connector_name, trading_pair, interval, max_records)
@st.cache_data
def add_indicators(df, macd_fast, macd_slow, macd_signal, diff_lookback):
# MACD
df.ta.macd(fast=macd_fast, slow=macd_slow, signal=macd_signal, append=True)
# Decision Logic
macdh = df[f"MACDh_{macd_fast}_{macd_slow}_{macd_signal}"]
macdh_diff = df[f"MACDh_{macd_fast}_{macd_slow}_{macd_signal}"].diff(diff_lookback)
long_condition = (macdh > 0) & (macdh_diff > 0)
short_condition = (macdh < 0) & (macdh_diff < 0)
df["signal"] = 0
df.loc[long_condition, "signal"] = 1
df.loc[short_condition, "signal"] = -1
return df
st.write("## Configuration")
c1, c2, c3 = st.columns(3)
with c1:
connector_name = st.text_input("Connector Name", value="binance_perpetual")
trading_pair = st.text_input("Trading Pair", value="WLD-USDT")
with c2:
interval = st.selectbox("Candle Interval", ["1m", "3m", "5m", "15m", "30m"], index=1)
max_records = st.number_input("Max Records", min_value=100, max_value=10000, value=1000)
with c3:
macd_fast = st.number_input("MACD Fast", min_value=1, value=21)
macd_slow = st.number_input("MACD Slow", min_value=1, value=42)
macd_signal = st.number_input("MACD Signal", min_value=1, value=9)
diff_lookback = st.number_input("MACD Diff Lookback", min_value=1, value=5)
# Fetch and process data
candle_data = get_candles(connector_name, trading_pair, interval, max_records)
df = pd.DataFrame(candle_data)
df.index = pd.to_datetime(df['timestamp'], unit='s')
df = add_indicators(df, macd_fast, macd_slow, macd_signal, diff_lookback)
# Prepare data for signals
signals = df[df['signal'] != 0]
buy_signals = signals[signals['signal'] == 1]
sell_signals = signals[signals['signal'] == -1]
# Define your color palette
tech_colors = {
'upper_band': '#4682B4',
'middle_band': '#FFD700',
'lower_band': '#32CD32',
'buy_signal': '#1E90FF',
'sell_signal': '#FF0000',
}
# Create a subplot with 3 rows
fig = make_subplots(rows=3, cols=1, shared_xaxes=True,
vertical_spacing=0.05, # Adjust spacing to make the plot look better
subplot_titles=('Candlestick', 'MACD Line and Histogram', 'Trading Signals'),
row_heights=[0.5, 0.3, 0.2]) # Adjust heights to give more space to candlestick and MACD
# Candlestick and Bollinger Bands
fig.add_trace(go.Candlestick(x=df.index,
open=df['open'],
high=df['high'],
low=df['low'],
close=df['close'],
name="Candlesticks", increasing_line_color='#2ECC71', decreasing_line_color='#E74C3C'),
row=1, col=1)
# MACD Line and Histogram
fig.add_trace(go.Scatter(x=df.index, y=df[f"MACD_{macd_fast}_{macd_slow}_{macd_signal}"], line=dict(color='orange'), name='MACD Line'), row=2, col=1)
fig.add_trace(go.Scatter(x=df.index, y=df[f"MACDs_{macd_fast}_{macd_slow}_{macd_signal}"], line=dict(color='purple'), name='MACD Signal'), row=2, col=1)
fig.add_trace(go.Bar(x=df.index, y=df[f"MACDh_{macd_fast}_{macd_slow}_{macd_signal}"], name='MACD Histogram', marker_color=df[f"MACDh_{macd_fast}_{macd_slow}_{macd_signal}"].apply(lambda x: '#FF6347' if x < 0 else '#32CD32')), row=2, col=1)
# Signals plot
fig.add_trace(go.Scatter(x=buy_signals.index, y=buy_signals['close'], mode='markers',
marker=dict(color=tech_colors['buy_signal'], size=10, symbol='triangle-up'),
name='Buy Signal'), row=1, col=1)
fig.add_trace(go.Scatter(x=sell_signals.index, y=sell_signals['close'], mode='markers',
marker=dict(color=tech_colors['sell_signal'], size=10, symbol='triangle-down'),
name='Sell Signal'), row=1, col=1)
# Trading Signals
fig.add_trace(go.Scatter(x=signals.index, y=signals['signal'], mode='markers', marker=dict(color=signals['signal'].map({1: '#1E90FF', -1: '#FF0000'}), size=10), name='Trading Signals'), row=3, col=1)
# Update layout settings for a clean look
fig.update_layout(height=1000, title="MACD and Bollinger Bands Strategy", xaxis_title="Time", yaxis_title="Price", template="plotly_dark", showlegend=True)
fig.update_xaxes(rangeslider_visible=False, row=1, col=1)
fig.update_xaxes(rangeslider_visible=False, row=2, col=1)
fig.update_xaxes(rangeslider_visible=False, row=3, col=1)
# Display the chart
st.plotly_chart(fig, use_container_width=True)
c1, c2, c3 = st.columns([2, 2, 1])
with c1:
config_base = st.text_input("Config Base", value=f"macd_bb_v1-{connector_name}-{trading_pair.split('-')[0]}")
with c2:
config_tag = st.text_input("Config Tag", value="1.1")
# Save the configuration
id = f"{config_base}-{config_tag}"
config = {
"id": id,
"connector_name": connector_name,
"trading_pair": trading_pair,
"interval": interval,
"macd_fast": macd_fast,
"macd_slow": macd_slow,
"macd_signal": macd_signal,
}
yaml_config = yaml.dump(config, default_flow_style=False)
with c3:
download_config = st.download_button(
label="Download YAML",
data=yaml_config,
file_name=f'{id.lower()}.yml',
mime='text/yaml'
)
upload_config_to_backend = st.button("Upload Config to BackendAPI")
if upload_config_to_backend:
backend_api_client = get_backend_api_client()
backend_api_client.add_controller_config(config)
st.success("Config uploaded successfully!")

View File

@@ -0,0 +1,19 @@
# D-Man Maker V2
## Features
- **Interactive Configuration**: Configure market making parameters such as spreads, amounts, and order levels through an intuitive web interface.
- **Visual Feedback**: Visualize order spread and amount distributions using dynamic Plotly charts.
- **Backend Integration**: Save and deploy configurations directly to a backend system for active management and execution.
### Using the Tool
1. **Configure Parameters**: Use the Streamlit interface to input parameters such as connector type, trading pair, and leverage.
2. **Set Distributions**: Define distributions for buy and sell orders, including spread and amount, either manually or through predefined distribution types like Geometric or Fibonacci.
3. **Visualize Orders**: View the configured order distributions on a Plotly graph, which illustrates the relationship between spread and amount.
4. **Export Configuration**: Once the configuration is set, export it as a YAML file or directly upload it to the Backend API.
5. **Upload**: Use the "Upload Config to BackendAPI" button to send your configuration to the backend system. Then can be used to deploy a new bot.
## Troubleshooting
- **UI Not Loading**: Ensure all Python dependencies are installed and that the Streamlit server is running correctly.
- **API Errors**: Check the console for any error messages that may indicate issues with the backend connection.
For more detailed documentation on the backend API and additional configurations, please refer to the project's documentation or contact the development team.

View File

@@ -0,0 +1,225 @@
import streamlit as st
import pandas as pd
import plotly.graph_objects as go
import yaml
from hummingbot.connector.connector_base import OrderType
from pykalman import KalmanFilter
from CONFIG import BACKEND_API_HOST, BACKEND_API_PORT
from backend.services.backend_api_client import BackendAPIClient
from frontend.st_utils import initialize_st_page, get_backend_api_client
# Initialize the Streamlit page
initialize_st_page(title="Kalman Filter V1", icon="📈", initial_sidebar_state="expanded")
@st.cache_data
def get_candles(connector_name="binance", trading_pair="BTC-USDT", interval="1m", max_records=5000):
backend_client = BackendAPIClient(BACKEND_API_HOST, BACKEND_API_PORT)
return backend_client.get_real_time_candles(connector_name, trading_pair, interval, max_records)
@st.cache_data
def add_indicators(df, observation_covariance=1, transition_covariance=0.01, initial_state_covariance=0.001):
# Add Bollinger Bands
# Construct a Kalman filter
kf = KalmanFilter(transition_matrices=[1],
observation_matrices=[1],
initial_state_mean=df["close"].values[0],
initial_state_covariance=initial_state_covariance,
observation_covariance=observation_covariance,
transition_covariance=transition_covariance)
mean, cov = kf.filter(df["close"].values)
df["kf"] = pd.Series(mean.flatten(), index=df["close"].index)
df["kf_upper"] = pd.Series(mean.flatten() + 1.96 * cov.flatten(), index=df["close"].index)
df["kf_lower"] = pd.Series(mean.flatten() - 1.96 * cov.flatten(), index=df["close"].index)
# Generate signal
long_condition = df["close"] < df["kf_lower"]
short_condition = df["close"] > df["kf_upper"]
# Generate signal
df["signal"] = 0
df.loc[long_condition, "signal"] = 1
df.loc[short_condition, "signal"] = -1
return df
st.text("This tool will let you create a config for Kalman Filter V1 and visualize the strategy.")
st.write("---")
# Inputs for Kalman Filter configuration
st.write("## Candles Configuration")
c1, c2, c3, c4 = st.columns(4)
with c1:
connector_name = st.text_input("Connector Name", value="binance_perpetual")
candles_connector = st.text_input("Candles Connector", value="binance_perpetual")
with c2:
trading_pair = st.text_input("Trading Pair", value="WLD-USDT")
candles_trading_pair = st.text_input("Candles Trading Pair", value="WLD-USDT")
with c3:
interval = st.selectbox("Candle Interval", options=["1m", "3m", "5m", "15m", "30m"], index=1)
with c4:
max_records = st.number_input("Max Records", min_value=100, max_value=10000, value=1000)
st.write("## Positions Configuration")
c1, c2, c3, c4 = st.columns(4)
with c1:
sl = st.number_input("Stop Loss (%)", min_value=0.0, max_value=100.0, value=2.0, step=0.1)
tp = st.number_input("Take Profit (%)", min_value=0.0, max_value=100.0, value=3.0, step=0.1)
take_profit_order_type = st.selectbox("Take Profit Order Type", (OrderType.LIMIT, OrderType.MARKET))
with c2:
ts_ap = st.number_input("Trailing Stop Activation Price (%)", min_value=0.0, max_value=100.0, value=1.0, step=0.1)
ts_delta = st.number_input("Trailing Stop Delta (%)", min_value=0.0, max_value=100.0, value=0.3, step=0.1)
time_limit = st.number_input("Time Limit (minutes)", min_value=0, value=60 * 6)
with c3:
executor_amount_quote = st.number_input("Executor Amount Quote", min_value=10.0, value=100.0, step=1.0)
max_executors_per_side = st.number_input("Max Executors Per Side", min_value=1, value=2)
cooldown_time = st.number_input("Cooldown Time (seconds)", min_value=0, value=300)
with c4:
leverage = st.number_input("Leverage", min_value=1, value=20)
position_mode = st.selectbox("Position Mode", ("HEDGE", "ONEWAY"))
st.write("## Kalman Filter Configuration")
c1, c2 = st.columns(2)
with c1:
observation_covariance = st.number_input("Observation Covariance", value=1.0)
with c2:
transition_covariance = st.number_input("Transition Covariance", value=0.001, step=0.0001, format="%.4f")
# Load candle data
candle_data = get_candles(connector_name=candles_connector, trading_pair=candles_trading_pair, interval=interval, max_records=max_records)
df = pd.DataFrame(candle_data)
df.index = pd.to_datetime(df['timestamp'], unit='s')
candles_processed = add_indicators(df, observation_covariance, transition_covariance)
# Prepare data for signals
signals = candles_processed[candles_processed['signal'] != 0]
buy_signals = signals[signals['signal'] == 1]
sell_signals = signals[signals['signal'] == -1]
from plotly.subplots import make_subplots
# Define your color palette
tech_colors = {
'upper_band': '#4682B4', # Steel Blue for the Upper Bollinger Band
'middle_band': '#FFD700', # Gold for the Middle Bollinger Band
'lower_band': '#32CD32', # Green for the Lower Bollinger Band
'buy_signal': '#1E90FF', # Dodger Blue for Buy Signals
'sell_signal': '#FF0000', # Red for Sell Signals
}
# Create a subplot with 2 rows
fig = make_subplots(rows=2, cols=1, shared_xaxes=True,
vertical_spacing=0.02, subplot_titles=('Candlestick with Kalman Filter', 'Trading Signals'),
row_heights=[0.7, 0.3])
# Candlestick plot
fig.add_trace(go.Candlestick(x=candles_processed.index,
open=candles_processed['open'],
high=candles_processed['high'],
low=candles_processed['low'],
close=candles_processed['close'],
name="Candlesticks", increasing_line_color='#2ECC71', decreasing_line_color='#E74C3C'),
row=1, col=1)
# Bollinger Bands
fig.add_trace(go.Scatter(x=candles_processed.index, y=candles_processed['kf_upper'], line=dict(color=tech_colors['upper_band']), name='Upper Band'), row=1, col=1)
fig.add_trace(go.Scatter(x=candles_processed.index, y=candles_processed['kf'], line=dict(color=tech_colors['middle_band']), name='Middle Band'), row=1, col=1)
fig.add_trace(go.Scatter(x=candles_processed.index, y=candles_processed['kf_lower'], line=dict(color=tech_colors['lower_band']), name='Lower Band'), row=1, col=1)
# Signals plot
fig.add_trace(go.Scatter(x=buy_signals.index, y=buy_signals['close'], mode='markers',
marker=dict(color=tech_colors['buy_signal'], size=10, symbol='triangle-up'),
name='Buy Signal'), row=1, col=1)
fig.add_trace(go.Scatter(x=sell_signals.index, y=sell_signals['close'], mode='markers',
marker=dict(color=tech_colors['sell_signal'], size=10, symbol='triangle-down'),
name='Sell Signal'), row=1, col=1)
fig.add_trace(go.Scatter(x=signals.index, y=signals['signal'], mode='markers',
marker=dict(color=signals['signal'].map({1: tech_colors['buy_signal'], -1: tech_colors['sell_signal']}), size=10),
showlegend=False), row=2, col=1)
# Update layout
fig.update_layout(
height=1000, # Increased height for better visibility
title="Kalman Filter and Trading Signals",
xaxis_title="Time",
yaxis_title="Price",
template="plotly_dark",
showlegend=False
)
# Update xaxis properties
fig.update_xaxes(
rangeslider_visible=False, # Disable range slider for all
row=1, col=1
)
fig.update_xaxes(
row=2, col=1
)
# Update yaxis properties
fig.update_yaxes(
title_text="Price", row=1, col=1
)
fig.update_yaxes(
title_text="Signal", row=2, col=1
)
# Use Streamlit's functionality to display the plot
st.plotly_chart(fig, use_container_width=True)
c1, c2, c3 = st.columns([2, 2, 1])
with c1:
config_base = st.text_input("Config Base", value=f"bollinger_v1-{connector_name}-{trading_pair.split('-')[0]}")
with c2:
config_tag = st.text_input("Config Tag", value="1.1")
id = f"{config_base}-{config_tag}"
config = {
"id": id,
"controller_name": "bollinger_v1",
"controller_type": "directional_trading",
"manual_kill_switch": None,
"candles_config": [],
"connector_name": connector_name,
"trading_pair": trading_pair,
"executor_amount_quote": executor_amount_quote,
"max_executors_per_side": max_executors_per_side,
"cooldown_time": cooldown_time,
"leverage": leverage,
"position_mode": position_mode,
"stop_loss": sl / 100,
"take_profit": tp / 100,
"time_limit": time_limit,
"take_profit_order_type": take_profit_order_type.value,
"trailing_stop": {
"activation_price": ts_ap / 100,
"trailing_delta": ts_delta / 100
},
"candles_connector": candles_connector,
"candles_trading_pair": candles_trading_pair,
"interval": interval,
}
yaml_config = yaml.dump(config, default_flow_style=False)
with c3:
download_config = st.download_button(
label="Download YAML",
data=yaml_config,
file_name=f'{id.lower()}.yml',
mime='text/yaml'
)
upload_config_to_backend = st.button("Upload Config to BackendAPI")
if upload_config_to_backend:
backend_api_client = get_backend_api_client()
backend_api_client.add_controller_config(config)
st.success("Config uploaded successfully!")

View File

@@ -0,0 +1,80 @@
# MACD BB V1 Configuration Tool
Welcome to the MACD BB V1 Configuration Tool! This tool allows you to create, modify, visualize, backtest, and save configurations for the MACD BB V1 directional trading strategy. Heres 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 MACD BB 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.
- **MACD Fast**: Set the fast period for the MACD indicator.
- **MACD Slow**: Set the slow period for the MACD indicator.
- **MACD Signal**: Set the signal period for the MACD indicator.
- **Risk Management**: Set parameters for stop loss, take profit, time limit, and trailing stop settings.
### 3. Visualize Indicators
Visualize the Bollinger Bands and MACD 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 indicators:
- **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 bands 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.
- **MACD**: The MACD is used to determine trend changes. If the MACD value is negative and the histogram becomes positive, it signals a market trend up, suggesting a long position. Conversely, if the MACD value is positive and the histogram becomes negative, it signals a market trend down, suggesting a short position.
### Combining MACD and Bollinger Bands for Trade Signals
The MACD BB V1 strategy uses the MACD to identify potential trend changes and the Bollinger Bands to filter these signals:
- **Long Signal**: The MACD value must be negative, and the histogram must become positive, indicating a potential uptrend. The price must also be below the long threshold of the Bollinger Bands (e.g., below the lower band if the threshold is 0).
- **Short Signal**: The MACD value must be positive, and the histogram must become negative, indicating a potential downtrend. The price must also be above the short threshold of the Bollinger Bands (e.g., above the upper band if the threshold is 1.1).
This combination ensures that you only take trend-following trades when the market is already deviated from the mean, enhancing the effectiveness of your trading strategy.
### 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 strategys 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!

View File

View File

@@ -0,0 +1,64 @@
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.macd_bb_v1.user_inputs import user_inputs
from frontend.pages.config.utils import get_candles
from frontend.st_utils import initialize_st_page, get_backend_api_client
from frontend.visualization import theme
from frontend.visualization.backtesting import create_backtesting_figure
from frontend.visualization.backtesting_metrics import render_backtesting_metrics, render_accuracy_metrics, \
render_close_types
from frontend.visualization.candles import get_candlestick_trace
from frontend.visualization.indicators import get_bbands_traces, get_macd_traces
from frontend.visualization.signals import get_macdbb_v1_signal_traces
from frontend.visualization.utils import add_traces_to_fig
# Initialize the Streamlit page
initialize_st_page(title="MACD_BB V1", icon="📊", initial_sidebar_state="expanded")
backend_api_client = get_backend_api_client()
get_default_config_loader("macd_bb_v1")
# User inputs
inputs = user_inputs()
st.session_state["default_config"].update(inputs)
st.write("### Visualizing MACD Bollinger 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', "MACD"),
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_macdbb_v1_signal_traces(df=candles, bb_length=inputs["bb_length"], bb_std=inputs["bb_std"],
bb_long_threshold=inputs["bb_long_threshold"], bb_short_threshold=inputs["bb_short_threshold"],
macd_fast=inputs["macd_fast"], macd_slow=inputs["macd_slow"], macd_signal=inputs["macd_signal"]), row=1, col=1)
add_traces_to_fig(fig, get_macd_traces(df=candles, macd_fast=inputs["macd_fast"], macd_slow=inputs["macd_slow"], macd_signal=inputs["macd_signal"]), 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"])

View File

@@ -0,0 +1,62 @@
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)
macd_fast = default_config.get("macd_fast", 21)
macd_slow = default_config.get("macd_slow", 42)
macd_signal = default_config.get("macd_signal", 9)
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("MACD Bollinger Configuration", expanded=True):
c1, c2, c3, c4, c5, c6, c7 = st.columns(7)
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)
with c5:
macd_fast = st.number_input("MACD Fast", min_value=1, value=macd_fast)
with c6:
macd_slow = st.number_input("MACD Slow", min_value=1, value=macd_slow)
with c7:
macd_signal = st.number_input("MACD Signal", min_value=1, value=macd_signal)
return {
"controller_name": "macd_bb_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,
"macd_fast": macd_fast,
"macd_slow": macd_slow,
"macd_signal": macd_signal,
"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
}

View File

@@ -0,0 +1,62 @@
# PMM Dynamic Configuration Tool
Welcome to the PMM Dynamic Configuration Tool! This tool allows you to create, modify, visualize, backtest, and save configurations for the PMM Dynamic trading strategy. Heres 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, including indicators like MACD and NATR.
- **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 PMM Dynamic 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.
- **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.
- **MACD Fast Period**: Set the fast period for the MACD indicator.
- **MACD Slow Period**: Set the slow period for the MACD indicator.
- **MACD Signal Period**: Set the signal period for the MACD indicator.
- **NATR Length**: Define the length for the NATR indicator.
- **Risk Management**: Set parameters for stop loss, take profit, time limit, and trailing stop settings.
### 3. Indicator Visualization
Visualize the candlestick data along with the MACD and NATR indicators. This helps you understand how the MACD will shift the mid-price and how the NATR will be used as a base multiplier for spreads.
### 4. Executor Distribution
The distribution of orders is now a multiplier of the base spread, which is determined by the NATR indicator. This allows the algorithm to adapt to changing market conditions by adjusting the spread based on the average size of the candles.
### 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 strategys 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!

View File

View File

@@ -0,0 +1,85 @@
import streamlit as st
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from frontend.components.config_loader import get_default_config_loader
from frontend.components.executors_distribution import get_executors_distribution_inputs
from frontend.components.save_config import render_save_config
# Import submodules
from frontend.components.backtesting import backtesting_section
from frontend.pages.config.pmm_dynamic.spread_and_price_multipliers import get_pmm_dynamic_multipliers
from frontend.pages.config.pmm_dynamic.user_inputs import user_inputs
from frontend.pages.config.utils import get_candles
from frontend.st_utils import initialize_st_page, get_backend_api_client
from frontend.visualization import theme
from frontend.visualization.backtesting import create_backtesting_figure
from frontend.visualization.candles import get_candlestick_trace
from frontend.visualization.executors_distribution import create_executors_distribution_traces
from frontend.visualization.backtesting_metrics import render_backtesting_metrics, render_close_types, \
render_accuracy_metrics
from frontend.visualization.indicators import get_macd_traces
from frontend.visualization.utils import add_traces_to_fig
# Initialize the Streamlit page
initialize_st_page(title="PMM Dynamic", icon="👩‍🏫")
backend_api_client = get_backend_api_client()
# Page content
st.text("This tool will let you create a config for PMM Dynamic, backtest and upload it to the Backend API.")
get_default_config_loader("pmm_dynamic")
# Get user inputs
inputs = user_inputs()
st.write("### Visualizing MACD and NATR indicators for PMM Dynamic")
st.text("The MACD is used to shift the mid price and the NATR to make the spreads dynamic. "
"In the order distributions graph, we are going to see the values of the orders affected by the average NATR")
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)
with st.expander("Visualizing PMM Dynamic Indicators", expanded=True):
fig = make_subplots(rows=4, cols=1, shared_xaxes=True,
vertical_spacing=0.02, subplot_titles=('Candlestick with Bollinger Bands', 'MACD', "Price Multiplier", "Spreads Multiplier"),
row_heights=[0.8, 0.2, 0.2, 0.2])
add_traces_to_fig(fig, [get_candlestick_trace(candles)], row=1, col=1)
add_traces_to_fig(fig, get_macd_traces(df=candles, macd_fast=inputs["macd_fast"], macd_slow=inputs["macd_slow"], macd_signal=inputs["macd_signal"]), row=2, col=1)
price_multiplier, spreads_multiplier = get_pmm_dynamic_multipliers(candles, inputs["macd_fast"], inputs["macd_slow"], inputs["macd_signal"], inputs["natr_length"])
add_traces_to_fig(fig, [go.Scatter(x=candles.index, y=price_multiplier, name="Price Multiplier", line=dict(color="blue"))], row=3, col=1)
add_traces_to_fig(fig, [go.Scatter(x=candles.index, y=spreads_multiplier, name="Base Spread", line=dict(color="red"))], row=4, col=1)
fig.update_layout(**theme.get_default_layout(height=1000))
fig.update_yaxes(tickformat=".2%", row=3, col=1)
fig.update_yaxes(tickformat=".2%", row=4, col=1)
st.plotly_chart(fig, use_container_width=True)
st.write("### Executors Distribution")
st.write("The order distributions are affected by the average NATR. This means that if the first order has a spread of "
"1 and the NATR is 0.005, the first order will have a spread of 0.5% of the mid price.")
buy_spread_distributions, sell_spread_distributions, buy_order_amounts_pct, sell_order_amounts_pct = get_executors_distribution_inputs(use_custom_spread_units=True)
inputs["buy_spreads"] = [spread * 100 for spread in buy_spread_distributions]
inputs["sell_spreads"] = [spread * 100 for spread in sell_spread_distributions]
inputs["buy_amounts_pct"] = buy_order_amounts_pct
inputs["sell_amounts_pct"] = sell_order_amounts_pct
st.session_state["default_config"].update(inputs)
with st.expander("Executor Distribution:", expanded=True):
natr_avarage = spreads_multiplier.mean()
buy_spreads = [spread * natr_avarage for spread in inputs["buy_spreads"]]
sell_spreads = [spread * natr_avarage for spread in inputs["sell_spreads"]]
st.write(f"Average NATR: {natr_avarage:.2%}")
fig = create_executors_distribution_traces(buy_spreads, sell_spreads, inputs["buy_amounts_pct"], inputs["sell_amounts_pct"], inputs["total_amount_quote"])
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"])

View File

@@ -0,0 +1,17 @@
import pandas_ta as ta # noqa: F401
def get_pmm_dynamic_multipliers(df, macd_fast, macd_slow, macd_signal, natr_length):
"""
Get the spread and price multipliers for PMM Dynamic
"""
natr = ta.natr(df["high"], df["low"], df["close"], length=natr_length) / 100
macd_output = ta.macd(df["close"], fast=macd_fast,
slow=macd_slow, signal=macd_signal)
macd = macd_output[f"MACD_{macd_fast}_{macd_slow}_{macd_signal}"]
macdh = macd_output[f"MACDh_{macd_fast}_{macd_slow}_{macd_signal}"]
macd_signal = - (macd - macd.mean()) / macd.std()
macdh_signal = macdh.apply(lambda x: 1 if x > 0 else -1)
max_price_shift = natr / 2
price_multiplier = ((0.5 * macd_signal + 0.5 * macdh_signal) * max_price_shift)
return price_multiplier, natr

View File

@@ -0,0 +1,56 @@
import streamlit as st
from frontend.components.market_making_general_inputs import get_market_making_general_inputs
from frontend.components.risk_management import get_risk_management_inputs
def user_inputs():
default_config = st.session_state.get("default_config", {})
macd_fast = default_config.get("macd_fast", 21)
macd_slow = default_config.get("macd_slow", 42)
macd_signal = default_config.get("macd_signal", 9)
natr_length = default_config.get("natr_length", 14)
connector_name, trading_pair, leverage, total_amount_quote, position_mode, cooldown_time, executor_refresh_time, candles_connector, candles_trading_pair, interval = get_market_making_general_inputs(custom_candles=True)
sl, tp, time_limit, ts_ap, ts_delta, take_profit_order_type = get_risk_management_inputs()
with st.expander("PMM Dynamic Configuration", expanded=True):
c1, c2, c3, c4 = st.columns(4)
with c1:
macd_fast = st.number_input("MACD Fast Period", min_value=1, max_value=200, value=macd_fast)
with c2:
macd_slow = st.number_input("MACD Slow Period", min_value=1, max_value=200, value=macd_slow)
with c3:
macd_signal = st.number_input("MACD Signal Period", min_value=1, max_value=200, value=macd_signal)
with c4:
natr_length = st.number_input("NATR Length", min_value=1, max_value=200, value=natr_length)
# Create the config
config = {
"controller_name": "pmm_dynamic",
"controller_type": "market_making",
"manual_kill_switch": None,
"candles_config": [],
"connector_name": connector_name,
"trading_pair": trading_pair,
"total_amount_quote": total_amount_quote,
"executor_refresh_time": executor_refresh_time,
"cooldown_time": cooldown_time,
"leverage": leverage,
"position_mode": position_mode,
"candles_connector": candles_connector,
"candles_trading_pair": candles_trading_pair,
"interval": interval,
"macd_fast": macd_fast,
"macd_slow": macd_slow,
"macd_signal": macd_signal,
"natr_length": natr_length,
"stop_loss": sl,
"take_profit": tp,
"time_limit": time_limit,
"take_profit_order_type": take_profit_order_type.value,
"trailing_stop": {
"activation_price": ts_ap,
"trailing_delta": ts_delta
}
}
return config

View File

@@ -0,0 +1,49 @@
# PMM Simple Configuration Tool
Welcome to the PMM Simple Configuration Tool! This tool allows you to create, modify, visualize, backtest, and save configurations for the PMM Simple trading strategy. Heres 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 PMM Simple 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.
- **Risk Management**: Set parameters for stop loss, take profit, time limit, and trailing stop settings.
### 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. 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 strategys predictions and trades.
- **Understand Close Types**: Review different types of trade closures and their frequencies.
### 5. 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.

View File

View File

@@ -0,0 +1,47 @@
import streamlit as st
from backend.services.backend_api_client import BackendAPIClient
from CONFIG import BACKEND_API_HOST, BACKEND_API_PORT
from frontend.components.config_loader import get_default_config_loader
from frontend.components.save_config import render_save_config
# Import submodules
from frontend.pages.config.pmm_simple.user_inputs import user_inputs
from frontend.components.backtesting import backtesting_section
from frontend.st_utils import initialize_st_page, get_backend_api_client
from frontend.visualization.backtesting import create_backtesting_figure
from frontend.visualization.executors_distribution import create_executors_distribution_traces
from frontend.visualization.backtesting_metrics import render_backtesting_metrics, render_close_types, \
render_accuracy_metrics
# Initialize the Streamlit page
initialize_st_page(title="PMM Simple", icon="👨‍🏫")
backend_api_client = get_backend_api_client()
# Page content
st.text("This tool will let you create a config for PMM Simple, backtest and upload it to the Backend API.")
get_default_config_loader("pmm_simple")
inputs = user_inputs()
st.session_state["default_config"].update(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)
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"])

View File

@@ -0,0 +1,38 @@
import streamlit as st
from frontend.components.executors_distribution import get_executors_distribution_inputs
from frontend.components.market_making_general_inputs import get_market_making_general_inputs
from frontend.components.risk_management import get_risk_management_inputs
def user_inputs():
connector_name, trading_pair, leverage, total_amount_quote, position_mode, cooldown_time, executor_refresh_time, _, _, _ = get_market_making_general_inputs()
buy_spread_distributions, sell_spread_distributions, buy_order_amounts_pct, sell_order_amounts_pct = get_executors_distribution_inputs()
sl, tp, time_limit, ts_ap, ts_delta, take_profit_order_type = get_risk_management_inputs()
# Create the config
config = {
"controller_name": "pmm_simple",
"controller_type": "market_making",
"manual_kill_switch": None,
"candles_config": [],
"connector_name": connector_name,
"trading_pair": trading_pair,
"total_amount_quote": total_amount_quote,
"buy_spreads": buy_spread_distributions,
"sell_spreads": sell_spread_distributions,
"buy_amounts_pct": buy_order_amounts_pct,
"sell_amounts_pct": sell_order_amounts_pct,
"executor_refresh_time": executor_refresh_time,
"cooldown_time": cooldown_time,
"leverage": leverage,
"position_mode": position_mode,
"stop_loss": sl,
"take_profit": tp,
"time_limit": time_limit,
"take_profit_order_type": take_profit_order_type.value,
"trailing_stop": {
"activation_price": ts_ap,
"trailing_delta": ts_delta
}
}
return config

View File

View File

@@ -0,0 +1,207 @@
import streamlit as st
from plotly.subplots import make_subplots
import plotly.graph_objects as go
from decimal import Decimal
import yaml
from frontend.components.st_inputs import normalize, distribution_inputs, get_distribution
from frontend.st_utils import initialize_st_page
# Initialize the Streamlit page
initialize_st_page(title="Position Generator", icon="🔭")
# Page content
st.text("This tool will help you analyze and generate a position config.")
st.write("---")
# Layout in columns
col_quote, col_tp_sl, col_levels, col_spread_dist, col_amount_dist = st.columns([1, 1, 1, 2, 2])
def convert_to_yaml(spreads, order_amounts):
data = {
'dca_spreads': [float(spread)/100 for spread in spreads],
'dca_amounts': [float(amount) for amount in order_amounts]
}
return yaml.dump(data, default_flow_style=False)
with col_quote:
total_amount_quote = st.number_input("Total amount of quote", value=1000)
with col_tp_sl:
tp = st.number_input("Take Profit (%)", min_value=0.0, max_value=100.0, value=2.0, step=0.1)
sl = st.number_input("Stop Loss (%)", min_value=0.0, max_value=100.0, value=8.0, step=0.1)
with col_levels:
n_levels = st.number_input("Number of Levels", min_value=1, value=5)
# Spread and Amount Distributions
spread_dist_type, spread_start, spread_base, spread_scaling, spread_step, spread_ratio, manual_spreads = distribution_inputs(col_spread_dist, "Spread", n_levels)
amount_dist_type, amount_start, amount_base, amount_scaling, amount_step, amount_ratio, manual_amounts = distribution_inputs(col_amount_dist, "Amount", n_levels)
spread_distribution = get_distribution(spread_dist_type, n_levels, spread_start, spread_base, spread_scaling, spread_step, spread_ratio, manual_spreads)
amount_distribution = normalize(get_distribution(amount_dist_type, n_levels, amount_start, amount_base, amount_scaling, amount_step, amount_ratio, manual_amounts))
order_amounts = [Decimal(amount_dist * total_amount_quote) for amount_dist in amount_distribution]
spreads = [Decimal(spread - spread_distribution[0]) for spread in spread_distribution]
# Export Button
if st.button('Export as YAML'):
yaml_data = convert_to_yaml(spreads, order_amounts)
st.download_button(
label="Download YAML",
data=yaml_data,
file_name='config.yaml',
mime='text/yaml'
)
break_even_values = []
take_profit_values = []
for level in range(n_levels):
spreads_normalized = [Decimal(spread) + Decimal(0.01) for spread in spreads[:level+1]]
amounts = order_amounts[:level+1]
break_even = (sum([spread * amount for spread, amount in zip(spreads_normalized, amounts)]) / sum(amounts)) - Decimal(0.01)
break_even_values.append(break_even)
take_profit_values.append(break_even - Decimal(tp))
accumulated_amount = [sum(order_amounts[:i+1]) for i in range(len(order_amounts))]
def calculate_unrealized_pnl(spreads, break_even_values, accumulated_amount):
unrealized_pnl = []
for i in range(len(spreads)):
distance = abs(spreads[i] - break_even_values[i])
pnl = accumulated_amount[i] * distance / 100 # PNL calculation
unrealized_pnl.append(pnl)
return unrealized_pnl
# Calculate unrealized PNL
cum_unrealized_pnl = calculate_unrealized_pnl(spreads, break_even_values, accumulated_amount)
tech_colors = {
'spread': '#00BFFF', # Deep Sky Blue
'break_even': '#FFD700', # Gold
'take_profit': '#32CD32', # Green
'order_amount': '#1E90FF', # Dodger Blue
'cum_amount': '#4682B4', # Steel Blue
'stop_loss': '#FF0000', # Red
}
# Create Plotly figure with secondary y-axis and a dark theme
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.update_layout(template="plotly_dark")
# Update the Scatter Plots and Horizontal Lines
fig.add_trace(go.Scatter(x=list(range(len(spreads))), y=spreads, name='Spread (%)', mode='lines+markers', line=dict(width=3, color=tech_colors['spread'])), secondary_y=False)
fig.add_trace(go.Scatter(x=list(range(len(break_even_values))), y=break_even_values, name='Break Even (%)', mode='lines+markers', line=dict(width=3, color=tech_colors['break_even'])), secondary_y=False)
fig.add_trace(go.Scatter(x=list(range(len(take_profit_values))), y=take_profit_values, name='Take Profit (%)', mode='lines+markers', line=dict(width=3, color=tech_colors['take_profit'])), secondary_y=False)
# Add the new Bar Plot for Cumulative Unrealized PNL
fig.add_trace(go.Bar(
x=list(range(len(cum_unrealized_pnl))),
y=cum_unrealized_pnl,
text=[f"{pnl:.2f}" for pnl in cum_unrealized_pnl],
textposition='auto',
textfont=dict(color='white', size=12),
name='Cum Unrealized PNL',
marker=dict(color='#FFA07A', opacity=0.6) # Light Salmon color, adjust as needed
), secondary_y=True)
fig.add_trace(go.Bar(
x=list(range(len(order_amounts))),
y=order_amounts,
text=[f"{amt:.2f}" for amt in order_amounts], # List comprehension to format text labels
textposition='auto',
textfont=dict(
color='white',
size=12
),
name='Order Amount',
marker=dict(color=tech_colors['order_amount'], opacity=0.5),
), secondary_y=True)
# Modify the Bar Plot for Accumulated Amount
fig.add_trace(go.Bar(
x=list(range(len(accumulated_amount))),
y=accumulated_amount,
text=[f"{amt:.2f}" for amt in accumulated_amount], # List comprehension to format text labels
textposition='auto',
textfont=dict(
color='white',
size=12
),
name='Cum Amount',
marker=dict(color=tech_colors['cum_amount'], opacity=0.5),
), secondary_y=True)
# Add Horizontal Lines for Last Breakeven Price and Stop Loss Level
last_break_even = break_even_values[-1]
stop_loss_value = last_break_even + Decimal(sl)
# Horizontal Lines for Last Breakeven and Stop Loss
fig.add_hline(y=last_break_even, line_dash="dash", annotation_text=f"Global Break Even: {last_break_even:.2f} (%)", annotation_position="top left", line_color=tech_colors['break_even'])
fig.add_hline(y=stop_loss_value, line_dash="dash", annotation_text=f"Stop Loss: {stop_loss_value:.2f} (%)", annotation_position="bottom right", line_color=tech_colors['stop_loss'])
# Update Annotations for Spread and Break Even
for i, (spread, be_value, tp_value) in enumerate(zip(spreads, break_even_values, take_profit_values)):
fig.add_annotation(x=i, y=spread, text=f"{spread:.2f}%", showarrow=True, arrowhead=1, yshift=10, xshift=-2, font=dict(color=tech_colors['spread']))
fig.add_annotation(x=i, y=be_value, text=f"{be_value:.2f}%", showarrow=True, arrowhead=1, yshift=5, xshift=-2, font=dict(color=tech_colors['break_even']))
fig.add_annotation(x=i, y=tp_value, text=f"{tp_value:.2f}%", showarrow=True, arrowhead=1, yshift=10, xshift=-2, font=dict(color=tech_colors['take_profit']))
# Update Layout with a Dark Theme
fig.update_layout(
title="Spread, Accumulated Amount, Break Even, and Take Profit by Order Level",
xaxis_title="Order Level",
yaxis_title="Spread (%)",
yaxis2_title="Amount (Quote)",
height=800,
width=1800,
plot_bgcolor='rgba(0, 0, 0, 0)', # Transparent background
paper_bgcolor='rgba(0, 0, 0, 0.1)', # Lighter shade for the paper
font=dict(color='white') # Font color
)
# Calculate metrics
max_loss = total_amount_quote * Decimal(sl / 100)
profit_per_level = [cum_amount * Decimal(tp / 100) for cum_amount in accumulated_amount]
loots_to_recover = [max_loss / profit for profit in profit_per_level]
# Define a consistent annotation size and maximum value for the secondary y-axis
circle_text = "" # Unicode character for a circle
max_secondary_value = max(max(accumulated_amount), max(order_amounts), max(cum_unrealized_pnl)) # Adjust based on your secondary y-axis data
# Determine an appropriate y-offset for annotations
y_offset_secondary = max_secondary_value * Decimal(0.1) # Adjusts the height relative to the maximum value on the secondary y-axis
# Add annotations to the Plotly figure for the secondary y-axis
for i, loot in enumerate(loots_to_recover):
fig.add_annotation(
x=i,
y=max_secondary_value + y_offset_secondary, # Position above the maximum value using the offset
text=f"{circle_text}<br>LTR: {round(loot, 2)}", # Circle symbol and loot value in separate lines
showarrow=False,
font=dict(size=16, color='purple'),
xanchor="center", # Centers the text above the x coordinate
yanchor="bottom", # Anchors the text at its bottom to avoid overlapping
align="center",
yref="y2" # Reference the secondary y-axis
)
# Add Max Loss Metric as an Annotation
max_loss_annotation_text = f"Max Loss (Quote): {max_loss:.2f}"
fig.add_annotation(
x=max(len(spreads), len(break_even_values)) - 1, # Positioning the annotation to the right
text=max_loss_annotation_text,
showarrow=False,
font=dict(size=20, color='white'),
bgcolor='red', # Red background for emphasis
xanchor="left",
yanchor="top",
yref="y2" # Reference the secondary y-axis
)
st.write("---")
# Display in Streamlit
st.plotly_chart(fig)

View File

@@ -0,0 +1,72 @@
# Super Trend Configuration Tool
Welcome to the Super Trend Configuration Tool! This tool allows you to create, modify, visualize, backtest, and save configurations for the Super Trend directional trading strategy. Heres 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 Super Trend 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.
- **Super Trend Length**: Define the length of the Super Trend indicator.
- **Super Trend Multiplier**: Set the multiplier for the Super Trend indicator.
- **Percentage Threshold**: Set the percentage threshold for signal generation.
- **Risk Management**: Set parameters for stop loss, take profit, time limit, and trailing stop settings.
### 3. Visualize Indicators
Visualize the Super Trend indicator 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 indicators:
- **Super Trend Length**: A larger length will make the Super Trend indicator smoother and less sensitive to short-term price fluctuations, while a smaller length will make it more responsive to recent price changes.
- **Super Trend Multiplier**: Adjusting the multiplier affects the sensitivity of the Super Trend indicator. A higher multiplier makes the trend detection more conservative, while a lower multiplier makes it more aggressive.
- **Percentage Threshold**: This defines how close the price needs to be to the Super Trend band to generate a signal. For example, a 0.5% threshold means the price needs to be within 0.5% of the Super Trend band to consider a trade.
### Combining Super Trend and Percentage Threshold for Trade Signals
The Super Trend V1 strategy uses the Super Trend indicator combined with a percentage threshold to generate trade signals:
- **Long Signal**: The Super Trend indicator must signal a long trend, and the price must be within the percentage threshold of the Super Trend long band. For example, if the threshold is 0.5%, the price must be within 0.5% of the Super Trend long band to trigger a long trade.
- **Short Signal**: The Super Trend indicator must signal a short trend, and the price must be within the percentage threshold of the Super Trend short band. Similarly, if the threshold is 0.5%, the price must be within 0.5% of the Super Trend short band to trigger a short trade.
### 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 strategys 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!

View File

View File

@@ -0,0 +1,62 @@
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.supertrend_v1.user_inputs import user_inputs
from frontend.pages.config.utils import get_candles
from frontend.st_utils import initialize_st_page, get_backend_api_client
from frontend.visualization import theme
from frontend.visualization.backtesting import create_backtesting_figure
from frontend.visualization.backtesting_metrics import render_backtesting_metrics, render_accuracy_metrics, \
render_close_types
from frontend.visualization.candles import get_candlestick_trace
from frontend.visualization.indicators import get_volume_trace, get_supertrend_traces
from frontend.visualization.signals import get_supertrend_v1_signal_traces
from frontend.visualization.utils import add_traces_to_fig
# Initialize the Streamlit page
initialize_st_page(title="SuperTrend V1", icon="📊", initial_sidebar_state="expanded")
backend_api_client = get_backend_api_client()
get_default_config_loader("supertrend_v1")
# User inputs
inputs = user_inputs()
st.session_state["default_config"].update(inputs)
st.write("### Visualizing Supertrend 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', "MACD"),
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_supertrend_traces(candles, inputs["length"], inputs["multiplier"]), row=1, col=1)
add_traces_to_fig(fig, get_supertrend_v1_signal_traces(candles, inputs["length"], inputs["multiplier"], inputs["percentage_threshold"]), row=1, col=1)
add_traces_to_fig(fig, [get_volume_trace(candles)], row=2, col=1)
layout_settings = theme.get_default_layout()
layout_settings["showlegend"] = False
fig.update_layout(**layout_settings)
# 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"])

View File

@@ -0,0 +1,46 @@
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", {})
length = default_config.get("length", 20)
multiplier = default_config.get("multiplier", 3.0)
percentage_threshold = default_config.get("percentage_threshold", 0.5)
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("SuperTrend Configuration", expanded=True):
c1, c2, c3 = st.columns(3)
with c1:
length = st.number_input("Supertrend Length", min_value=1, max_value=200, value=length)
with c2:
multiplier = st.number_input("Supertrend Multiplier", min_value=1.0, max_value=5.0, value=multiplier)
with c3:
percentage_threshold = st.number_input("Percentage Threshold (%)", value=percentage_threshold) / 100
return {
"controller_name": "supertrend_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,
"length": length,
"multiplier": multiplier,
"percentage_threshold": percentage_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
}

28
pages/config/utils.py Normal file
View File

@@ -0,0 +1,28 @@
import datetime
import streamlit as st
import pandas as pd
from CONFIG import BACKEND_API_HOST, BACKEND_API_PORT
from backend.services.backend_api_client import BackendAPIClient
def get_max_records(days_to_download: int, interval: str) -> int:
conversion = {"s": 1 / 60, "m": 1, "h": 60, "d": 1440}
unit = interval[-1]
quantity = int(interval[:-1])
return int(days_to_download * 24 * 60 / (quantity * conversion[unit]))
@st.cache_data
def get_candles(connector_name="binance", trading_pair="BTC-USDT", interval="1m", days=7):
backend_client = BackendAPIClient(BACKEND_API_HOST, BACKEND_API_PORT)
end_time = datetime.datetime.now() - datetime.timedelta(minutes=15)
start_time = end_time - datetime.timedelta(days=days)
df = pd.DataFrame(backend_client.get_historical_candles(connector_name, trading_pair, interval,
start_time=int(start_time.timestamp() * 1000),
end_time=int(end_time.timestamp() * 1000)))
df.index = pd.to_datetime(df.timestamp, unit='s')
return df

View File

@@ -0,0 +1,60 @@
# XEMM Configuration Tool
Welcome to the XEMM Configuration Tool! This tool allows you to create, modify, visualize, backtest, and save configurations for the XEMM (Cross-Exchange Market Making) strategy. Heres 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 XEMM 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:
- **Maker Connector**: Select the maker trading platform or exchange where limit orders will be placed.
- **Maker Trading Pair**: Choose the trading pair on the maker exchange.
- **Taker Connector**: Select the taker trading platform or exchange where market orders will be executed to hedge the imbalance.
- **Taker Trading Pair**: Choose the trading pair on the taker exchange.
- **Min Profitability**: Set the minimum profitability percentage at which orders will be refreshed to avoid risking liquidity.
- **Max Profitability**: Set the maximum profitability percentage at which orders will be refreshed to avoid being too far from the mid-price.
- **Buy Maker Levels**: Specify the number of buy maker levels.
- **Buy Targets and Amounts**: Define the target profitability and amounts for each buy maker level.
- **Sell Maker Levels**: Specify the number of sell maker levels.
- **Sell Targets and Amounts**: Define the target profitability and amounts for each sell maker level.
### 3. Visualize Order Distribution
Visualize the order distribution with profitability targets using Plotly charts. This helps you understand how your buy and sell orders are distributed across different profitability levels.
### Min and Max Profitability
The XEMM strategy uses min and max profitability bounds to manage the placement of limit orders:
- **Min Profitability**: If the expected profitability of a limit order drops below this value, the order will be refreshed to avoid risking liquidity.
- **Max Profitability**: If the expected profitability of a limit order exceeds this value, the order will be refreshed to avoid being too far from the mid-price.
### Combining Profitability Targets and Order Amounts
- **Buy Orders**: Configure the target profitability and amounts for each buy maker level. The orders will be refreshed if they fall outside the min and max profitability bounds.
- **Sell Orders**: Similarly, configure the target profitability and amounts for each sell maker level, with orders being refreshed based on the profitability bounds.
### 4. Save and Download Configuration
Once you have configured your strategy, you can save and download the configuration as a YAML file. This allows you to deploy the strategy later without having to reconfigure it from scratch.
### 5. Upload Configuration to Backend API
You can also upload the configuration directly to the Backend API for immediate deployment. This ensures that your strategy is ready to be executed in real-time.
## Conclusion
By following these steps, you can efficiently configure your XEMM strategy, visualize its potential performance, and deploy it for trading. Feel free to experiment with different configurations to find the optimal setup for your trading needs. Happy trading!

View File

View File

@@ -0,0 +1,134 @@
import streamlit as st
import plotly.graph_objects as go
import yaml
from CONFIG import BACKEND_API_HOST, BACKEND_API_PORT
from backend.services.backend_api_client import BackendAPIClient
from frontend.st_utils import initialize_st_page, get_backend_api_client
# Initialize the Streamlit page
initialize_st_page(title="XEMM Multiple Levels", icon="⚡️")
# Page content
st.text("This tool will let you create a config for XEMM Controller and upload it to the BackendAPI.")
st.write("---")
c1, c2, c3, c4, c5 = st.columns([1, 1, 1, 1, 1])
with c1:
maker_connector = st.text_input("Maker Connector", value="kucoin")
maker_trading_pair = st.text_input("Maker Trading Pair", value="LBR-USDT")
with c2:
taker_connector = st.text_input("Taker Connector", value="okx")
taker_trading_pair = st.text_input("Taker Trading Pair", value="LBR-USDT")
with c3:
min_profitability = st.number_input("Min Profitability (%)", value=0.2, step=0.01) / 100
max_profitability = st.number_input("Max Profitability (%)", value=1.0, step=0.01) / 100
with c4:
buy_maker_levels = st.number_input("Buy Maker Levels", value=1, step=1)
buy_targets_amounts = []
c41, c42 = st.columns([1, 1])
for i in range(buy_maker_levels):
with c41:
target_profitability = st.number_input(f"Target Profitability {i+1} B% ", value=0.3, step=0.01)
with c42:
amount = st.number_input(f"Amount {i+1}B Quote", value=10, step=1)
buy_targets_amounts.append([target_profitability / 100, amount])
with c5:
sell_maker_levels = st.number_input("Sell Maker Levels", value=1, step=1)
sell_targets_amounts = []
c51, c52 = st.columns([1, 1])
for i in range(sell_maker_levels):
with c51:
target_profitability = st.number_input(f"Target Profitability {i+1}S %", value=0.3, step=0.001)
with c52:
amount = st.number_input(f"Amount {i+1} S Quote", value=10, step=1)
sell_targets_amounts.append([target_profitability / 100, amount])
def create_order_graph(order_type, targets, min_profit, max_profit):
# Create a figure
fig = go.Figure()
# Convert profit targets to percentage for x-axis and prepare data for bar chart
x_values = [t[0] * 100 for t in targets] # Convert to percentage
y_values = [t[1] for t in targets]
x_labels = [f"{x:.2f}%" for x in x_values] # Format x labels as strings with percentage sign
# Add bar plot for visualization of targets
fig.add_trace(go.Bar(
x=x_labels,
y=y_values,
width=0.01,
name=f'{order_type.capitalize()} Targets',
marker=dict(color='gold')
))
# Convert min and max profitability to percentages for reference lines
min_profit_percent = min_profit * 100
max_profit_percent = max_profit * 100
# Add vertical lines for min and max profitability
fig.add_shape(type="line",
x0=min_profit_percent, y0=0, x1=min_profit_percent, y1=max(y_values, default=10),
line=dict(color="red", width=2),
name='Min Profitability')
fig.add_shape(type="line",
x0=max_profit_percent, y0=0, x1=max_profit_percent, y1=max(y_values, default=10),
line=dict(color="red", width=2),
name='Max Profitability')
# Update layouts with x-axis starting at 0
fig.update_layout(
title=f"{order_type.capitalize()} Order Distribution with Profitability Targets",
xaxis=dict(
title="Profitability (%)",
range=[0, max(max(x_values + [min_profit_percent, max_profit_percent]) + 0.1, 1)] # Adjust range to include a buffer
),
yaxis=dict(
title="Order Amount"
),
height=400,
width=600
)
return fig
# Use the function for both buy and sell orders
buy_order_fig = create_order_graph('buy', buy_targets_amounts, min_profitability, max_profitability)
sell_order_fig = create_order_graph('sell', sell_targets_amounts, min_profitability, max_profitability)
# Display the Plotly graphs in Streamlit
st.plotly_chart(buy_order_fig, use_container_width=True)
st.plotly_chart(sell_order_fig, use_container_width=True)
# Display in Streamlit
c1, c2, c3 = st.columns([2, 2, 1])
with c1:
config_base = st.text_input("Config Base", value=f"xemm-{maker_connector}-{taker_connector}-{maker_trading_pair.split('-')[0]}")
with c2:
config_tag = st.text_input("Config Tag", value="1.1")
id = f"{config_base}_{config_tag}"
config = {
"id": id.lower(),
"controller_name": "xemm_multiple_levels",
"controller_type": "generic",
"maker_connector": maker_connector,
"maker_trading_pair": maker_trading_pair,
"taker_connector": taker_connector,
"taker_trading_pair": taker_trading_pair,
"min_profitability": min_profitability,
"max_profitability": max_profitability,
"buy_levels_targets_amount": buy_targets_amounts,
"sell_levels_targets_amount": sell_targets_amounts
}
yaml_config = yaml.dump(config, default_flow_style=False)
with c3:
upload_config_to_backend = st.button("Upload Config to BackendAPI")
if upload_config_to_backend:
backend_api_client = get_backend_api_client()
backend_api_client.add_controller_config(config)
st.success("Config uploaded successfully!")

View File

@@ -0,0 +1,46 @@
import streamlit as st
def user_inputs():
c1, c2, c3, c4, c5 = st.columns([1, 1, 1, 1, 1])
with c1:
maker_connector = st.text_input("Maker Connector", value="kucoin")
maker_trading_pair = st.text_input("Maker Trading Pair", value="LBR-USDT")
with c2:
taker_connector = st.text_input("Taker Connector", value="okx")
taker_trading_pair = st.text_input("Taker Trading Pair", value="LBR-USDT")
with c3:
min_profitability = st.number_input("Min Profitability (%)", value=0.2, step=0.01) / 100
max_profitability = st.number_input("Max Profitability (%)", value=1.0, step=0.01) / 100
with c4:
buy_maker_levels = st.number_input("Buy Maker Levels", value=1, step=1)
buy_targets_amounts = []
c41, c42 = st.columns([1, 1])
for i in range(buy_maker_levels):
with c41:
target_profitability = st.number_input(f"Target Profitability {i + 1} B% ", value=0.3, step=0.01)
with c42:
amount = st.number_input(f"Amount {i + 1}B Quote", value=10, step=1)
buy_targets_amounts.append([target_profitability / 100, amount])
with c5:
sell_maker_levels = st.number_input("Sell Maker Levels", value=1, step=1)
sell_targets_amounts = []
c51, c52 = st.columns([1, 1])
for i in range(sell_maker_levels):
with c51:
target_profitability = st.number_input(f"Target Profitability {i + 1}S %", value=0.3, step=0.001)
with c52:
amount = st.number_input(f"Amount {i + 1} S Quote", value=10, step=1)
sell_targets_amounts.append([target_profitability / 100, amount])
return {
"controller_name": "xemm_multiple_levels",
"controller_type": "generic",
"maker_connector": maker_connector,
"maker_trading_pair": maker_trading_pair,
"taker_connector": taker_connector,
"taker_trading_pair": taker_trading_pair,
"min_profitability": min_profitability,
"max_profitability": max_profitability,
"buy_levels_targets_amount": buy_targets_amounts,
"sell_levels_targets_amount": sell_targets_amounts
}