An automated Market Maker bot for the BlockyCRAFT Economy Server.
Um bot automatizado de Market Making para o servidor de economia BlockyCRAFT.
English Documentation
- What is Market Making?
- Features
- Requirements
- Quick Start
- Running with Docker
- Configuration Guide
- Understanding the Bot
- Dashboard
- Monitoring
- Project Structure
- Understanding Log Messages
- Troubleshooting
Market Making is a trading strategy where you provide liquidity to a market by placing buy and sell orders simultaneously.
Imagine you want to trade diamonds:
- You place a BUY order at 49 Iron (you're willing to buy diamonds for 49)
- You place a SELL order at 51 Iron (you're willing to sell diamonds for 51)
When someone sells you a diamond for 49 and later someone buys it for 51, you profit 2 Iron.
The "spread" (51 - 49 = 2 Iron, or ~4%) is your profit margin.
- Markets operate 24/7 - manual monitoring is impractical
- Automatic price adjustments based on supply/demand
- Simultaneous management of dozens of markets
- Millisecond response to market changes
| Feature | Description |
|---|---|
| Dynamic Spread | Automatically adjusts spreads based on volatility and inventory |
| Dynamic Capital Allocation | Automatically calculates order sizes based on your Iron inventory |
| Smart Order Diffing | Only updates orders when necessary (reduces API calls) |
| Pennying Strategy | Automatically beats competitors by 0.01 while maintaining margins |
| Scarcity-Based Pricing | Prices items based on remaining world supply |
| Multiple Pricing Strategies | TWAP, Momentum, Mean Reversion, VWAP, Composite |
| Machine Learning | Volatility prediction using Random Forest for proactive spread adjustment |
| Advanced Backtesting | Parameter optimization, walk-forward analysis, HTML reports |
| Circuit Breaker | Protects against API failures with automatic recovery |
| Rate Limiting | Respects API limits (30 req/sec) |
| Discord/Slack Alerts | Notifications for errors and important events |
| Web Dashboard | Real-time trading dashboard with charts and strategy visualization |
| Health Endpoint | HTTP /health for monitoring systems |
| Dry Run Mode | Test strategies without real orders |
| Metrics & P&L | Track trading performance |
| Docker Compose | Production-ready deployment with persistent volumes |
- Python 3.11+ (or Docker)
- Blocky API Key (see below)
- Stable internet connection (for WebSocket)
- ~100MB RAM
- Access the Blocky web panel:
https://craft.blocky.com.br - Log in with your Minecraft account
- Navigate to Settings or API
- Generate a new API key
- Copy and store securely
Important: Never share your API key.
- Discord Webhook URL (for alerts)
- Docker (for containerized deployment)
For Windows users who prefer not to install Python:
- Download
BlockyMarketMaker.exefrom the Releases page - Double-click to run
- Complete the setup wizard:
- Enter your Blocky API key
- Configure trading settings
- Select markets
- The bot will start automatically
The setup wizard explains each setting and helps you configure unique values to avoid conflicts with other users.
Note: If you prefer manual configuration, place
.envandconfig.yamlfiles in the same directory asBlockyMarketMaker.exe.
Windows:
- Download Python 3.11+ from python.org
- Run the installer
- Check "Add Python to PATH" during installation
- Verify installation:
python --version
macOS:
brew install python@3.11Linux (Ubuntu/Debian):
sudo apt update
sudo apt install python3.11 python3-pip python3-venv# Clone the repository
git clone https://github.com/zukrmn/BlockyMarketMaker.git
cd BlockyMarketMaker
# Create a virtual environment (recommended)
python -m venv venv
# Activate the virtual environment
# Windows:
venv\Scripts\activate
# macOS/Linux:
source venv/bin/activate
# Install dependencies
pip install -r requirements.txt
# Run the interactive setup (creates .env file)
python scripts/setup.py
# Start the bot
python run.pyThe setup wizard will prompt for:
- Your Blocky API Key
- (Optional) Discord Webhook URL for alerts
Press Ctrl+C to stop the bot. It will:
- Cancel all open orders
- Save metrics to disk
- Close connections properly
Create a .env file:
BLOCKY_API_KEY=your-api-key-here
ALERT_WEBHOOK_URL=https://discord.com/api/webhooks/...
ALERT_WEBHOOK_TYPE=discordThen run:
pip install -r requirements.txt
python run.pydocker build -f docker/Dockerfile -t blocky-market-maker:prod .Create your .env file first via python scripts/setup.py or manually.
docker run --rm \
-v $(pwd)/.env:/app/.env \
-v $(pwd)/config.yaml:/app/config.yaml \
-p 8080:8080 \
-p 8081:8081 \
blocky-market-maker:prodCreate docker-compose.yml:
version: '3.8'
services:
market-maker:
build:
context: .
dockerfile: docker/Dockerfile
restart: unless-stopped
ports:
- "8080:8080"
- "8081:8081"
volumes:
- ./.env:/app/.env:ro
- ./config.yaml:/app/config.yaml:ro
- ./src/metrics_data.json:/app/src/metrics_data.json
- ./logs:/app/logs
healthcheck:
test: ["CMD", "wget", "-q", "--spider", "http://localhost:8080/health"]
interval: 30s
timeout: 10s
retries: 3Run:
docker-compose up -dThe project includes docker-compose.yml with persistent volumes:
# Production deployment with persistence
docker-compose up -d
# Follow logs
docker-compose logs -f
# Development mode (source code mounted)
docker-compose -f docker-compose.yml -f docker/docker-compose.dev.yml upPersistent Volumes:
data/metrics/- Trading metricsdata/logs/- Bot logsmodels/- ML trained models
For Linux users who want the bot to run in the background and start automatically on boot.
# Make the script executable (first time only)
chmod +x service.sh
# Install the systemd service
./service.sh installNote: The install command will ask for your sudo password. The service file contains paths specific to your installation - if you move the project folder, you'll need to update
blocky-market-maker.serviceand reinstall.
# Start the bot
./service.sh start
# Stop the bot
./service.sh stop
# Restart the bot
./service.sh restart
# Check status
./service.sh status
# View logs (live, Ctrl+C to exit)
./service.sh logs
# View full log history
./service.sh logs-full
# Uninstall the service
./service.sh uninstallThe service is configured to send desktop notifications when trades are executed. If you're using Wayland (default on Ubuntu 22.04+, Fedora, ZorinOS 17+), notifications should work automatically.
If notifications aren't working:
- Check that
notify-sendis installed:which notify-send - For sound, ensure
paplay(PulseAudio) oraplay(ALSA) is available - The service must be running under your user account (not root)
All settings are in config.yaml. Environment variables override YAML values.
[!CAUTION] You MUST customize your trading parameters! Using default values will cause market instability if multiple users run identical configurations. Choose unique values for
spread,target_value, andrefresh_interval.
trading:
dry_run: false # true = simulate only, no real orders
enabled_markets: [] # Whitelist: empty = all markets
disabled_markets: [] # Blacklist: never trade these
spread: <YOUR_VALUE> # Your spread (e.g., 0.03 to 0.15)
min_spread_ticks: 0.01 # Minimum price difference between buy/sell
target_value: <YOUR_VALUE> # Your target order value in Iron
max_quantity: 6400 # Maximum order quantity
refresh_interval: <YOUR_VALUE> # Seconds between checks (e.g., 30 to 120)Trade specific markets only:
trading:
enabled_markets: [diam_iron, gold_iron, lapi_iron]Exclude markets:
trading:
disabled_markets: [sand_iron, dirt_iron]Test without real orders:
trading:
dry_run: truedynamic_spread:
enabled: true
base_spread: 0.03 # 3% base spread
volatility_multiplier: 2.0
inventory_impact: 0.02
min_spread: 0.01 # 1% minimum
max_spread: 0.15 # 15% maximum
volatility_window: 24 # Hours of OHLCV dataCalculation:
spread = base_spread + volatility_adj + inventory_adj- High volatility → wider spreads
- Overstocked → wider buy spread, tighter sell spread
Automatically calculates order sizes based on your Iron inventory:
capital_allocation:
enabled: true # Enable dynamic allocation
base_reserve_ratio: 0.10 # Minimum 10% reserve
max_reserve_ratio: 0.30 # Maximum 30% reserve
min_order_value: 0.10 # Minimum order value
priority_markets: [diam_iron, gold_iron, slme_iron] # Higher allocation
priority_boost: 1.5 # 50% more for priority marketsFormula:
Reserve Ratio = 10% + (number_of_markets / 100)
Reserve = Total Iron × Reserve Ratio
Per Market = (Total Iron - Reserve) / number_of_markets
Example with 500 Iron and 37 markets:
- Reserve Ratio: 10% + 37% = 30% (capped)
- Reserve: 150 Iron (kept safe)
- Deployable: 350 Iron
- Per Market: ~9.5 Iron
price_model:
cache_ttl: 60
base_prices:
diam_iron: 50.0
gold_iron: 5.0
lapi_iron: 2.0
coal_iron: 0.5
ston_iron: 0.1
cobl_iron: 0.05
dirt_iron: 0.01
sand_iron: 0.05
olog_iron: 0.45
obsn_iron: 2.5
slme_iron: 5.0Pricing formula:
fair_price = base_price × (total_supply / remaining_supply)
rate_limit:
max_requests: 30
window_seconds: 1.0
circuit_breaker:
failure_threshold: 5
recovery_timeout: 30.0alerts:
enabled: true
webhook_type: "discord"
min_level: "warning"
rate_limit_seconds: 60Set webhook URL via environment:
ALERT_WEBHOOK_URL=https://discord.com/api/webhooks/...health:
enabled: true
port: 8080Access: http://localhost:8080/health
Automatically pauses trading when losses exceed configurable thresholds:
stop_loss:
enabled: true # Enable/disable stop-loss system
max_drawdown: 100.0 # Maximum loss in Iron before triggering
max_drawdown_percent: 0.10 # Maximum loss as % of capital (10%)
cooldown_seconds: 300 # 5 minutes cooldown after trigger
check_interval: 30 # Check P&L every 30 secondsHow it works:
- Monitors realized + unrealized P&L every 30 seconds
- Triggers when losses exceed
max_drawdownORmax_drawdown_percent - Also tracks drawdown from peak equity
- When triggered: Cancels all open orders immediately
- Enters cooldown period before resuming
States:
| State | Description |
|---|---|
active |
Trading normally |
triggered |
Stop-loss fired, orders cancelled |
cooldown |
Waiting before resuming |
disabled |
System disabled via config |
Configure which strategy to use for price calculation:
strategy:
type: "composite" # Options: composite, scarcity, ticker, vwap, twap, momentum, mean_reversion
# TWAP (Time-Weighted Average Price)
twap_lookback_hours: 4
# Momentum (trend following)
momentum_lookback_periods: 12
momentum_factor: 0.05 # Max adjustment (5%)
# Mean Reversion (Z-score based)
mean_reversion_ma_period: 24
mean_reversion_zscore_threshold: 1.5
mean_reversion_blend_factor: 0.3Available Strategies:
| Strategy | Description |
|---|---|
composite |
Combines multiple signals (default) |
scarcity |
Prices based on remaining world supply |
ticker |
Uses current market price |
vwap |
Volume-weighted average price |
twap |
Time-weighted average price |
momentum |
Trend-following with ROC |
mean_reversion |
Z-score based reversion to mean |
Train volatility prediction models:
# Generate synthetic data and train
python scripts/train_model.py --generate-synthetic --samples 1000 --output models/volatility.pkl
# Train with real data
python scripts/train_model.py --data-dir data/historical --output models/volatility.pklRun backtests with parameter optimization:
# Simple backtest with HTML report
python scripts/backtest_runner.py --generate-data --spread 0.05 --report report.html
# Parameter optimization
python scripts/backtest_runner.py --generate-data --optimize --spread-range 0.02,0.10
# Walk-forward analysis
python scripts/backtest_runner.py --generate-data --walk-forward 5- Price Calculation: Scarcity model + market data
- Spread Calculation: Dynamic based on volatility + inventory
- Pennying: Beat competitors by 0.01 within profit margin
- Order Diffing: Only update orders when prices change significantly
- Inventory Management: Adjust quotes based on holdings
Every 60 seconds:
├── Update wallet balances
├── Fetch market tickers (batch)
├── For each market:
│ ├── Calculate fair price
│ ├── Calculate dynamic spread
│ ├── Apply pennying strategy
│ ├── Check inventory/capital
│ ├── Diff with existing orders
│ ├── Cancel stale orders
│ └── Place new orders
└── Poll trades for P&L
WebSocket events (real-time):
├── Trade → immediate requote
└── Orderbook change → immediate requote
The bot includes a real-time web dashboard.
With the bot running:
http://localhost:8081/dashboard
- Live candlestick charts
- Order book display
- P&L tracking
- Strategy visualization
- Market navigation
- Drawing tools for chart analysis
| Port | Service |
|---|---|
| 8080 | Health endpoint |
| 8081 | Web Dashboard |
curl http://localhost:8080/healthResponse:
{
"status": "healthy",
"markets_count": 11,
"circuit_breaker": "CLOSED",
"websocket_connected": true,
"realized_pnl": 12.54,
"orders_placed": 156,
"total_trades": 23
}Logs are output to console and saved to logs/bot.log:
- Green = INFO
- Yellow = WARNING
- Red = ERROR
[DRY-RUN]= Simulated actions
Metrics saved to src/metrics_data.json every 60 seconds and on shutdown.
BlockyMarketMaker/
├── run.py # Entry point
├── config.yaml # Configuration
├── docker-compose.yml # Production deployment
├── requirements.txt # Dependencies
├── .env # API keys (create this)
│
├── src/ # Source code
│ ├── main.py # Bot logic
│ ├── blocky/ # API client
│ ├── dashboard/ # Web dashboard
│ ├── strategies/ # Pricing strategies (TWAP, Momentum, etc.)
│ ├── ml/ # Machine learning (volatility predictor)
│ ├── backtesting/ # Backtest engine + optimizer
│ ├── price_model.py # Scarcity pricing
│ ├── spread_calculator.py
│ └── ...
│
├── scripts/ # Utilities
│ ├── setup.py # Setup wizard
│ ├── train_model.py # ML training script
│ └── backtest_runner.py # Backtest CLI
│
├── docker/ # Docker config
│ ├── Dockerfile
│ └── docker-compose.dev.yml
│
├── models/ # Trained ML models
├── logs/ # Log files
├── data/ # Market data├── tests/ # Unit tests
| Message | Meaning |
|---|---|
Placed buy order |
Buy order placed successfully |
Placed sell order |
Sell order placed successfully |
Cancelling order (Diff Mismatch) |
Price changed, replacing order |
Insufficient funds |
Not enough Iron for order |
Circuit breaker OPEN |
API errors, pausing requests |
WS Event: Trade on X |
Trade occurred on market X |
Integrity Check |
Periodic order verification |
[DRY-RUN] |
Simulated action |
| Problem | Solution |
|---|---|
BLOCKY_API_KEY not set |
Run python scripts/setup.py or create .env |
502 Bad Gateway |
API down, auto-retry in 5s |
Circuit breaker OPEN |
Too many errors, auto-recovery in 30s |
Insufficient funds |
Add Iron or reduce target_value |
Rate limit reached |
Auto-throttle active |
| No orders placed | Check enabled_markets/disabled_markets |
| Dashboard not loading | Verify port 8081 is available |
ModuleNotFoundError |
Activate venv: source venv/bin/activate |
- Ensure you have Iron in your Blocky wallet
- Start with
dry_run: trueto test - Use single market first:
enabled_markets: [diam_iron] - Monitor via dashboard
trading:
dry_run: trueLogs show [DRY-RUN] prefix for simulated actions.
For developers who want to build the .exe themselves.
-
Python 3.11+ installed
- Download from python.org
- During installation, check "Add Python to PATH"
- Verify:
python --version
-
Git installed
- Download from git-scm.com
# 1. Clone the repository
git clone https://github.com/zukrmn/BlockyMarketMaker.git
cd BlockyMarketMaker
# 2. Run the build script (installs dependencies automatically)
build_exe.batThe script will:
- Install all project dependencies
- Install PyInstaller if not present
- Build the executable
Or build manually:
pyinstaller blocky.spec --clean- Executable:
dist/BlockyMarketMaker.exe - Expected size: ~50-80MB
- Build time: 1-3 minutes
- Create a new empty folder (e.g.,
C:\BlockyTest\) - Copy
dist/BlockyMarketMaker.exeto this folder - Copy
config.yamlto the same folder (as template) - Double-click
BlockyMarketMaker.exe - The setup wizard should open
To share with other users, they only need:
BlockyMarketMaker.execonfig.yaml(optional, will use defaults if missing)
Users do NOT need Python installed.
| Problem | Solution |
|---|---|
python not found |
Reinstall Python with "Add to PATH" checked |
pip not found |
Run python -m pip install --upgrade pip |
ModuleNotFoundError during build |
Run pip install <module_name> and rebuild |
| Build succeeds but exe crashes | Check for missing hidden imports in blocky.spec |
| Antivirus blocks/deletes exe | Add exception for dist/ folder (false positive) |
| Windows SmartScreen warning | Click "More info" → "Run anyway" |
| Exe size is 200MB+ | Something wrong with spec, rebuild with --clean |
- Create or download a
.icofile - Save as
img/icon.ico - Uncomment the icon line in
blocky.spec:icon='img/icon.ico',
- Rebuild
Documentação em Português
- O que é Market Making?
- Recursos
- Requisitos
- Início Rápido
- Rodando com Docker
- Guia de Configuração
- Entendendo o Bot
- Dashboard
- Monitoramento
- Estrutura do Projeto
- Entendendo as Mensagens de Log
- Solução de Problemas
Market Making é uma estratégia de trading onde você fornece liquidez ao mercado colocando ordens de compra e venda simultaneamente.
Imagine que você quer negociar diamantes:
- Você coloca uma ordem de COMPRA a 49 Iron
- Você coloca uma ordem de VENDA a 51 Iron
Quando alguém te vende um diamante por 49 e depois alguém compra por 51, você lucra 2 Iron.
O "spread" (51 - 49 = 2 Iron, ou ~4%) é sua margem de lucro.
- Mercados funcionam 24/7 - monitoramento manual é impraticável
- Ajuste automático de preços baseado em oferta/demanda
- Gerenciamento simultâneo de dezenas de mercados
- Resposta em milissegundos a mudanças de mercado
| Recurso | Descrição |
|---|---|
| Spread Dinâmico | Ajusta spreads baseado em volatilidade e inventário |
| Alocação Dinâmica de Capital | Calcula tamanho das ordens baseado no seu inventário de Iron |
| Smart Order Diffing | Atualiza ordens apenas quando necessário |
| Estratégia de Pennying | Supera concorrentes por 0.01 mantendo margem |
| Precificação por Escassez | Preços baseados na oferta restante |
| Múltiplas Estratégias de Preço | TWAP, Momentum, Reversão à Média, VWAP, Composto |
| Machine Learning | Predição de volatilidade com Random Forest para ajuste proativo de spread |
| Backtesting Avançado | Otimização de parâmetros, análise walk-forward, relatórios HTML |
| Circuit Breaker | Proteção contra falhas com recuperação automática |
| Rate Limiting | Respeita limites da API (30 req/seg) |
| Alertas Discord/Slack | Notificações de erros e eventos |
| Dashboard Web | Dashboard em tempo real com gráficos e visualização de estratégias |
| Endpoint de Saúde | HTTP /health para monitoramento |
| Modo Dry Run | Teste sem ordens reais |
| Métricas & P&L | Acompanhamento de performance |
| Docker Compose | Deploy com volumes persistentes |
- Python 3.11+ (ou Docker)
- Chave de API da Blocky (veja abaixo)
- Conexão estável com internet (para WebSocket)
- ~100MB RAM
- Acesse o painel:
https://craft.blocky.com.br - Faça login com sua conta Minecraft
- Navegue até Configurações ou API
- Gere uma nova chave
- Copie e guarde com segurança
Importante: Nunca compartilhe sua chave de API.
- URL de Webhook do Discord (para alertas)
- Docker (para deploy containerizado)
Para usuários Windows que preferem não instalar Python:
- Baixe
BlockyMarketMaker.exeda página de Releases - Dê duplo clique para executar
- Complete o assistente de configuração:
- Digite sua chave API da Blocky
- Configure parâmetros de trading
- Selecione mercados
- O bot iniciará automaticamente
O assistente explica cada configuração e ajuda a definir valores únicos para evitar conflitos com outros usuários.
Nota: Se preferir configuração manual, coloque os arquivos
.enveconfig.yamlno mesmo diretório doBlockyMarketMaker.exe.
Windows:
- Baixe Python 3.11+ em python.org
- Execute o instalador
- Marque "Add Python to PATH"
- Verifique:
python --version
macOS:
brew install python@3.11Linux (Ubuntu/Debian):
sudo apt update
sudo apt install python3.11 python3-pip python3-venv# Clone o repositório
git clone https://github.com/zukrmn/BlockyMarketMaker.git
cd BlockyMarketMaker
# Crie ambiente virtual (recomendado)
python -m venv venv
# Ative o ambiente virtual
# Windows:
venv\Scripts\activate
# macOS/Linux:
source venv/bin/activate
# Instale dependências
pip install -r requirements.txt
# Execute o setup interativo
python scripts/setup.py
# Inicie o bot
python run.pyO assistente pedirá:
- Sua Chave de API da Blocky
- (Opcional) URL do Webhook do Discord
Pressione Ctrl+C para parar. O bot irá:
- Cancelar ordens abertas
- Salvar métricas
- Fechar conexões
Crie um arquivo .env:
BLOCKY_API_KEY=sua-api-key-aqui
ALERT_WEBHOOK_URL=https://discord.com/api/webhooks/...
ALERT_WEBHOOK_TYPE=discordExecute:
pip install -r requirements.txt
python run.pydocker build -f docker/Dockerfile -t blocky-market-maker:prod .Crie o arquivo .env primeiro.
docker run --rm \
-v $(pwd)/.env:/app/.env \
-v $(pwd)/config.yaml:/app/config.yaml \
-p 8080:8080 \
-p 8081:8081 \
blocky-market-maker:prodCrie docker-compose.yml:
version: '3.8'
services:
market-maker:
build:
context: .
dockerfile: docker/Dockerfile
restart: unless-stopped
ports:
- "8080:8080"
- "8081:8081"
volumes:
- ./.env:/app/.env:ro
- ./config.yaml:/app/config.yaml:ro
- ./src/metrics_data.json:/app/src/metrics_data.json
- ./logs:/app/logs
healthcheck:
test: ["CMD", "wget", "-q", "--spider", "http://localhost:8080/health"]
interval: 30s
timeout: 10s
retries: 3Execute:
docker-compose up -dConfigurações em config.yaml. Variáveis de ambiente sobrescrevem o YAML.
[!CAUTION] Você DEVE personalizar seus parâmetros de trading! Usar valores padrão causará instabilidade no mercado se múltiplos usuários rodarem configurações idênticas. Escolha valores únicos para
spread,target_valueerefresh_interval.
trading:
dry_run: false # true = apenas simula
enabled_markets: [] # Whitelist: vazio = todos
disabled_markets: [] # Blacklist
spread: <SEU_VALOR> # Seu spread (ex: 0.03 a 0.15)
min_spread_ticks: 0.01
target_value: <SEU_VALOR> # Seu valor alvo em Iron
max_quantity: 6400
refresh_interval: <SEU_VALOR> # Segundos entre verificações (ex: 30 a 120)Mercados específicos:
trading:
enabled_markets: [diam_iron, gold_iron, lapi_iron]Excluir mercados:
trading:
disabled_markets: [sand_iron, dirt_iron]Testar sem ordens:
trading:
dry_run: truedynamic_spread:
enabled: true
base_spread: 0.03
volatility_multiplier: 2.0
inventory_impact: 0.02
min_spread: 0.01
max_spread: 0.15
volatility_window: 24Cálculo:
spread = base + volatilidade + inventário- Alta volatilidade → spreads maiores
- Excesso de estoque → spread de compra maior
Calcula automaticamente o tamanho das ordens baseado no seu Iron:
capital_allocation:
enabled: true # Habilitar alocação dinâmica
base_reserve_ratio: 0.10 # Mínimo 10% de reserva
max_reserve_ratio: 0.30 # Máximo 30% de reserva
min_order_value: 0.10 # Valor mínimo de ordem
priority_markets: [diam_iron, gold_iron, slme_iron] # Maior alocação
priority_boost: 1.5 # 50% a mais para mercados prioritáriosFórmula:
Reserva = 10% + (número_de_mercados / 100)
Reserva em Iron = Total × Reserva
Por Mercado = (Total - Reserva) / número_de_mercados
Exemplo com 500 Iron e 37 mercados:
- Reserva: 30% (cap) = 150 Iron guardados
- Disponível: 350 Iron
- Por Mercado: ~9.5 Iron
price_model:
cache_ttl: 60
base_prices:
diam_iron: 50.0
gold_iron: 5.0
lapi_iron: 2.0
coal_iron: 0.5
ston_iron: 0.1
cobl_iron: 0.05
dirt_iron: 0.01
sand_iron: 0.05
olog_iron: 0.45
obsn_iron: 2.5
slme_iron: 5.0Fórmula:
preço_justo = preço_base × (supply_total / supply_restante)
rate_limit:
max_requests: 30
window_seconds: 1.0
circuit_breaker:
failure_threshold: 5
recovery_timeout: 30.0alerts:
enabled: true
webhook_type: "discord"
min_level: "warning"
rate_limit_seconds: 60Webhook via ambiente:
ALERT_WEBHOOK_URL=https://discord.com/api/webhooks/...health:
enabled: true
port: 8080Acesse: http://localhost:8080/health
Pausa automaticamente o trading quando perdas excedem limites configuráveis:
stop_loss:
enabled: true # Habilitar/desabilitar stop-loss
max_drawdown: 100.0 # Perda máxima em Iron
max_drawdown_percent: 0.10 # Perda máxima como % do capital (10%)
cooldown_seconds: 300 # 5 minutos de cooldown após trigger
check_interval: 30 # Verificar P&L a cada 30 segundosComo funciona:
- Monitora P&L realizado + não realizado a cada 30 segundos
- Dispara quando perdas excedem
max_drawdownOUmax_drawdown_percent - Também monitora drawdown do pico de equity
- Quando dispara: Cancela todas as ordens imediatamente
- Entra em período de cooldown antes de retomar
Estados:
| Estado | Descrição |
|---|---|
active |
Operando normalmente |
triggered |
Stop-loss disparado, ordens canceladas |
cooldown |
Aguardando antes de retomar |
disabled |
Sistema desabilitado via config |
Configure qual estratégia usar para cálculo de preço:
strategy:
type: "composite" # Opções: composite, scarcity, ticker, vwap, twap, momentum, mean_reversion
# TWAP (Time-Weighted Average Price)
twap_lookback_hours: 4
# Momentum (seguir tendência)
momentum_lookback_periods: 12
momentum_factor: 0.05 # Ajuste máximo (5%)
# Reversão à Média (baseado em Z-score)
mean_reversion_ma_period: 24
mean_reversion_zscore_threshold: 1.5
mean_reversion_blend_factor: 0.3Estratégias Disponíveis:
| Estratégia | Descrição |
|---|---|
composite |
Combina múltiplos sinais (padrão) |
scarcity |
Preços baseados na oferta restante |
ticker |
Usa preço atual de mercado |
vwap |
Preço médio ponderado por volume |
twap |
Preço médio ponderado por tempo |
momentum |
Seguidor de tendência com ROC |
mean_reversion |
Reversão à média baseada em Z-score |
Treine modelos de predição de volatilidade:
# Gerar dados sintéticos e treinar
python scripts/train_model.py --generate-synthetic --samples 1000 --output models/volatility.pkl
# Treinar com dados reais
python scripts/train_model.py --data-dir data/historical --output models/volatility.pklExecute backtests com otimização de parâmetros:
# Backtest simples com relatório HTML
python scripts/backtest_runner.py --generate-data --spread 0.05 --report relatorio.html
# Otimização de parâmetros
python scripts/backtest_runner.py --generate-data --optimize --spread-range 0.02,0.10
# Análise walk-forward
python scripts/backtest_runner.py --generate-data --walk-forward 5- Cálculo de Preço: Modelo de escassez + dados de mercado
- Cálculo de Spread: Dinâmico (volatilidade + inventário)
- Pennying: Superar concorrentes por 0.01
- Order Diffing: Atualizar apenas quando necessário
- Gestão de Inventário: Ajustar quotes por holdings
A cada 60 segundos:
├── Atualiza saldos
├── Busca tickers (lote)
├── Para cada mercado:
│ ├── Calcula preço justo
│ ├── Calcula spread
│ ├── Aplica pennying
│ ├── Verifica capital
│ ├── Compara ordens
│ ├── Cancela obsoletas
│ └── Coloca novas
└── Consulta trades para P&L
WebSocket (tempo real):
├── Trade → recotação imediata
└── Mudança orderbook → recotação
Dashboard web em tempo real incluído.
Com o bot rodando:
http://localhost:8081/dashboard
- Gráficos candlestick ao vivo
- Exibição do order book
- Acompanhamento P&L
- Visualização de estratégias
- Navegação entre mercados
- Ferramentas de desenho
| Porta | Serviço |
|---|---|
| 8080 | Endpoint de saúde |
| 8081 | Dashboard Web |
curl http://localhost:8080/healthResposta:
{
"status": "healthy",
"markets_count": 11,
"circuit_breaker": "CLOSED",
"websocket_connected": true,
"realized_pnl": 12.54,
"orders_placed": 156,
"total_trades": 23
}Logs no console e em logs/bot.log:
- Verde = INFO
- Amarelo = WARNING
- Vermelho = ERROR
[DRY-RUN]= Ações simuladas
Métricas salvas em src/metrics_data.json a cada 60s e no shutdown.
BlockyMarketMaker/
├── run.py # Ponto de entrada
├── config.yaml # Configuração
├── requirements.txt # Dependências
├── .env # Chaves (criar)
│
├── src/ # Código fonte
│ ├── main.py # Lógica do bot
│ ├── blocky/ # Cliente API
│ ├── dashboard/ # Dashboard web
│ ├── price_model.py # Precificação
│ ├── spread_calculator.py
│ ├── trading_helpers.py
│ └── ...
│
├── scripts/ # Utilitários
│ └── setup.py # Assistente
│
├── docker/ # Config Docker
│ └── Dockerfile
│
├── logs/ # Logs
├── data/ # Dados de mercado
└── tests/ # Testes
| Mensagem | Significado |
|---|---|
Placed buy order |
Compra colocada com sucesso |
Placed sell order |
Venda colocada com sucesso |
Cancelling order (Diff Mismatch) |
Preço mudou, substituindo |
Insufficient funds |
Iron insuficiente |
Circuit breaker OPEN |
Erros na API, pausando |
WS Event: Trade on X |
Trade no mercado X |
Integrity Check |
Verificação periódica |
[DRY-RUN] |
Ação simulada |
| Problema | Solução |
|---|---|
BLOCKY_API_KEY not set |
Execute python scripts/setup.py ou crie .env |
502 Bad Gateway |
API fora, retry em 5s |
Circuit breaker OPEN |
Muitos erros, recovery em 30s |
Insufficient funds |
Adicione Iron ou reduza target_value |
Rate limit reached |
Auto-throttle ativo |
| Sem ordens | Verifique enabled_markets/disabled_markets |
| Dashboard não carrega | Verifique porta 8081 |
ModuleNotFoundError |
Ative venv: source venv/bin/activate |
- Tenha Iron na carteira Blocky
- Comece com
dry_run: true - Use um mercado:
enabled_markets: [diam_iron] - Monitore via dashboard
trading:
dry_run: trueLogs mostram [DRY-RUN] para ações simuladas.
Para desenvolvedores que desejam compilar o .exe.
-
Python 3.11+ instalado
- Baixe em python.org
- Durante a instalação, marque "Add Python to PATH"
- Verifique:
python --version
-
Git instalado
- Baixe em git-scm.com
# 1. Clone o repositório
git clone https://github.com/zukrmn/BlockyMarketMaker.git
cd BlockyMarketMaker
# 2. Execute o script de build (instala dependências automaticamente)
build_exe.batO script irá:
- Instalar todas as dependências do projeto
- Instalar o PyInstaller se não estiver presente
- Compilar o executável
Ou compile manualmente:
pyinstaller blocky.spec --clean- Executável:
dist/BlockyMarketMaker.exe - Tamanho esperado: ~50-80MB
- Tempo de build: 1-3 minutos
- Crie uma pasta vazia (ex:
C:\BlockyTest\) - Copie
dist/BlockyMarketMaker.exepara esta pasta - Copie
config.yamlpara a mesma pasta (como template) - Dê duplo clique em
BlockyMarketMaker.exe - O assistente de configuração deve abrir
Para compartilhar com outros usuários, eles precisam apenas de:
BlockyMarketMaker.execonfig.yaml(opcional, usa padrões se ausente)
Usuários NÃO precisam ter Python instalado.
| Problema | Solução |
|---|---|
python not found |
Reinstale Python marcando "Add to PATH" |
pip not found |
Execute python -m pip install --upgrade pip |
ModuleNotFoundError durante build |
Execute pip install <modulo> e recompile |
| Build funciona mas exe trava | Verifique hidden imports em blocky.spec |
| Antivírus bloqueia/deleta exe | Adicione exceção para pasta dist/ (falso positivo) |
| Aviso do Windows SmartScreen | Clique "Mais informações" → "Executar assim mesmo" |
| Exe com 200MB+ | Algo errado no spec, recompile com --clean |
- Crie ou baixe um arquivo
.ico - Salve como
img/icon.ico - Descomente a linha do ícone em
blocky.spec:icon='img/icon.ico',
- Recompile
This project is licensed under the MIT License - see the LICENSE file for details.
Pull requests welcome. For major changes, open an issue first.
Made for the Blocky community