Skip to content

zukrmn/BlockyMarketMaker

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

87 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

BlockyMarketMaker

An automated Market Maker bot for the BlockyCRAFT Economy Server.

Um bot automatizado de Market Making para o servidor de economia BlockyCRAFT.


English Documentation

Table of Contents


What is Market Making?

Market Making is a trading strategy where you provide liquidity to a market by placing buy and sell orders simultaneously.

Simple Example

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.

Why use a bot?

  • 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

Features

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

Requirements

Minimum Requirements

  • Python 3.11+ (or Docker)
  • Blocky API Key (see below)
  • Stable internet connection (for WebSocket)
  • ~100MB RAM

Obtaining Your Blocky API Key

  1. Access the Blocky web panel: https://craft.blocky.com.br
  2. Log in with your Minecraft account
  3. Navigate to Settings or API
  4. Generate a new API key
  5. Copy and store securely

Important: Never share your API key.

Optional

  • Discord Webhook URL (for alerts)
  • Docker (for containerized deployment)

Quick Start

Option 1: Windows Executable (EXPERIMENTAL DON'T RECOMMENDED)

For Windows users who prefer not to install Python:

  1. Download BlockyMarketMaker.exe from the Releases page
  2. Double-click to run
  3. Complete the setup wizard:
    • Enter your Blocky API key
    • Configure trading settings
    • Select markets
  4. 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 .env and config.yaml files in the same directory as BlockyMarketMaker.exe.


Option 2: Run Locally with Python

Step 1: Install Python

Windows:

  1. Download Python 3.11+ from python.org
  2. Run the installer
  3. Check "Add Python to PATH" during installation
  4. Verify installation: python --version

macOS:

brew install python@3.11

Linux (Ubuntu/Debian):

sudo apt update
sudo apt install python3.11 python3-pip python3-venv

Step 2: Clone and Setup

# 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.py

The setup wizard will prompt for:

  1. Your Blocky API Key
  2. (Optional) Discord Webhook URL for alerts

Step 3: Stopping the Bot

Press Ctrl+C to stop the bot. It will:

  • Cancel all open orders
  • Save metrics to disk
  • Close connections properly

Option 3: Manual Configuration

Create a .env file:

BLOCKY_API_KEY=your-api-key-here
ALERT_WEBHOOK_URL=https://discord.com/api/webhooks/...
ALERT_WEBHOOK_TYPE=discord

Then run:

pip install -r requirements.txt
python run.py

Running with Docker

Build the Image

docker build -f docker/Dockerfile -t blocky-market-maker:prod .

Run the Container

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:prod

Docker Compose (Recommended)

Create 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: 3

Run:

docker-compose up -d

Docker Compose with Persistence (Recommended)

The 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 up

Persistent Volumes:

  • data/metrics/ - Trading metrics
  • data/logs/ - Bot logs
  • models/ - ML trained models

Running as a Linux Service (Background)

For Linux users who want the bot to run in the background and start automatically on boot.

Install the Service

# Make the script executable (first time only)
chmod +x service.sh

# Install the systemd service
./service.sh install

Note: 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.service and reinstall.

Managing the Service

# 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 uninstall

Desktop Notifications

The 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:

  1. Check that notify-send is installed: which notify-send
  2. For sound, ensure paplay (PulseAudio) or aplay (ALSA) is available
  3. The service must be running under your user account (not root)

Configuration Guide

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, and refresh_interval.

Trading Parameters

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)

Examples

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: true

Dynamic Spread

dynamic_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 data

Calculation:

  • spread = base_spread + volatility_adj + inventory_adj
  • High volatility → wider spreads
  • Overstocked → wider buy spread, tighter sell spread

Dynamic Capital Allocation

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 markets

Formula:

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

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.0

Pricing formula:

  • fair_price = base_price × (total_supply / remaining_supply)

Rate Limiting & Circuit Breaker

rate_limit:
  max_requests: 30
  window_seconds: 1.0

circuit_breaker:
  failure_threshold: 5
  recovery_timeout: 30.0

Alerts

alerts:
  enabled: true
  webhook_type: "discord"
  min_level: "warning"
  rate_limit_seconds: 60

Set webhook URL via environment:

ALERT_WEBHOOK_URL=https://discord.com/api/webhooks/...

Health Endpoint

health:
  enabled: true
  port: 8080

Access: http://localhost:8080/health

Stop-Loss Protection

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 seconds

How it works:

  1. Monitors realized + unrealized P&L every 30 seconds
  2. Triggers when losses exceed max_drawdown OR max_drawdown_percent
  3. Also tracks drawdown from peak equity
  4. When triggered: Cancels all open orders immediately
  5. 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

Pricing Strategies

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.3

Available 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

Machine Learning

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.pkl

Backtesting

Run 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

Understanding the Bot

Trading Strategy

  1. Price Calculation: Scarcity model + market data
  2. Spread Calculation: Dynamic based on volatility + inventory
  3. Pennying: Beat competitors by 0.01 within profit margin
  4. Order Diffing: Only update orders when prices change significantly
  5. Inventory Management: Adjust quotes based on holdings

Order Flow

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

Dashboard

The bot includes a real-time web dashboard.

Access

With the bot running:

http://localhost:8081/dashboard

Features

  • Live candlestick charts
  • Order book display
  • P&L tracking
  • Strategy visualization
  • Market navigation
  • Drawing tools for chart analysis

Ports

Port Service
8080 Health endpoint
8081 Web Dashboard

Monitoring

Health Check

curl http://localhost:8080/health

Response:

{
  "status": "healthy",
  "markets_count": 11,
  "circuit_breaker": "CLOSED",
  "websocket_connected": true,
  "realized_pnl": 12.54,
  "orders_placed": 156,
  "total_trades": 23
}

Logs

Logs are output to console and saved to logs/bot.log:

  • Green = INFO
  • Yellow = WARNING
  • Red = ERROR
  • [DRY-RUN] = Simulated actions

Metrics Persistence

Metrics saved to src/metrics_data.json every 60 seconds and on shutdown.


Project Structure

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

Understanding Log Messages

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

Troubleshooting

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

Before First Run

  1. Ensure you have Iron in your Blocky wallet
  2. Start with dry_run: true to test
  3. Use single market first: enabled_markets: [diam_iron]
  4. Monitor via dashboard

Dry Run Testing

trading:
  dry_run: true

Logs show [DRY-RUN] prefix for simulated actions.


Building the Windows Executable

For developers who want to build the .exe themselves.

Prerequisites

  1. Python 3.11+ installed

    • Download from python.org
    • During installation, check "Add Python to PATH"
    • Verify: python --version
  2. Git installed

Build Steps

# 1. Clone the repository
git clone https://github.com/zukrmn/BlockyMarketMaker.git
cd BlockyMarketMaker

# 2. Run the build script (installs dependencies automatically)
build_exe.bat

The script will:

  • Install all project dependencies
  • Install PyInstaller if not present
  • Build the executable

Or build manually:

pyinstaller blocky.spec --clean

Build Output

  • Executable: dist/BlockyMarketMaker.exe
  • Expected size: ~50-80MB
  • Build time: 1-3 minutes

Testing the Build

  1. Create a new empty folder (e.g., C:\BlockyTest\)
  2. Copy dist/BlockyMarketMaker.exe to this folder
  3. Copy config.yaml to the same folder (as template)
  4. Double-click BlockyMarketMaker.exe
  5. The setup wizard should open

Distributing

To share with other users, they only need:

  • BlockyMarketMaker.exe
  • config.yaml (optional, will use defaults if missing)

Users do NOT need Python installed.

Troubleshooting Build Issues

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

Adding an Icon (Optional)

  1. Create or download a .ico file
  2. Save as img/icon.ico
  3. Uncomment the icon line in blocky.spec:
    icon='img/icon.ico',
  4. Rebuild


Documentação em Português

Índice


O que é Market Making?

Market Making é uma estratégia de trading onde você fornece liquidez ao mercado colocando ordens de compra e venda simultaneamente.

Exemplo Simples

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.

Por que usar um bot?

  • 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

Recursos

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

Requisitos

Requisitos Mínimos

  • Python 3.11+ (ou Docker)
  • Chave de API da Blocky (veja abaixo)
  • Conexão estável com internet (para WebSocket)
  • ~100MB RAM

Obtendo a Chave de API

  1. Acesse o painel: https://craft.blocky.com.br
  2. Faça login com sua conta Minecraft
  3. Navegue até Configurações ou API
  4. Gere uma nova chave
  5. Copie e guarde com segurança

Importante: Nunca compartilhe sua chave de API.

Opcional

  • URL de Webhook do Discord (para alertas)
  • Docker (para deploy containerizado)

Início Rápido

Opção 1: Executável Windows (EXPERIMENTAL NÃO RECOMENDADO)

Para usuários Windows que preferem não instalar Python:

  1. Baixe BlockyMarketMaker.exe da página de Releases
  2. Dê duplo clique para executar
  3. Complete o assistente de configuração:
    • Digite sua chave API da Blocky
    • Configure parâmetros de trading
    • Selecione mercados
  4. 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 .env e config.yaml no mesmo diretório do BlockyMarketMaker.exe.


Opção 2: Rodar Localmente com Python

Passo 1: Instalar Python

Windows:

  1. Baixe Python 3.11+ em python.org
  2. Execute o instalador
  3. Marque "Add Python to PATH"
  4. Verifique: python --version

macOS:

brew install python@3.11

Linux (Ubuntu/Debian):

sudo apt update
sudo apt install python3.11 python3-pip python3-venv

Passo 2: Clonar e Configurar

# 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.py

O assistente pedirá:

  1. Sua Chave de API da Blocky
  2. (Opcional) URL do Webhook do Discord

Passo 3: Parando o Bot

Pressione Ctrl+C para parar. O bot irá:

  • Cancelar ordens abertas
  • Salvar métricas
  • Fechar conexões

Opção 3: Configuração Manual

Crie um arquivo .env:

BLOCKY_API_KEY=sua-api-key-aqui
ALERT_WEBHOOK_URL=https://discord.com/api/webhooks/...
ALERT_WEBHOOK_TYPE=discord

Execute:

pip install -r requirements.txt
python run.py

Rodando com Docker

Construir a Imagem

docker build -f docker/Dockerfile -t blocky-market-maker:prod .

Rodar o Container

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:prod

Docker Compose (Recomendado)

Crie 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: 3

Execute:

docker-compose up -d

Guia de Configuração

Configuraçõ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_value e refresh_interval.

Parâmetros de Trading

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)

Exemplos

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: true

Spread Dinâmico

dynamic_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: 24

Cálculo:

  • spread = base + volatilidade + inventário
  • Alta volatilidade → spreads maiores
  • Excesso de estoque → spread de compra maior

Alocação Dinâmica de Capital

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ários

Fó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

Modelo de Preço

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.0

Fórmula:

  • preço_justo = preço_base × (supply_total / supply_restante)

Rate Limiting & Circuit Breaker

rate_limit:
  max_requests: 30
  window_seconds: 1.0

circuit_breaker:
  failure_threshold: 5
  recovery_timeout: 30.0

Alertas

alerts:
  enabled: true
  webhook_type: "discord"
  min_level: "warning"
  rate_limit_seconds: 60

Webhook via ambiente:

ALERT_WEBHOOK_URL=https://discord.com/api/webhooks/...

Endpoint de Saúde

health:
  enabled: true
  port: 8080

Acesse: http://localhost:8080/health

Proteção Stop-Loss

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 segundos

Como funciona:

  1. Monitora P&L realizado + não realizado a cada 30 segundos
  2. Dispara quando perdas excedem max_drawdown OU max_drawdown_percent
  3. Também monitora drawdown do pico de equity
  4. Quando dispara: Cancela todas as ordens imediatamente
  5. 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

Estratégias de Preço

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.3

Estraté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

Machine Learning

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.pkl

Backtesting

Execute 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

Entendendo o Bot

Estratégia de Trading

  1. Cálculo de Preço: Modelo de escassez + dados de mercado
  2. Cálculo de Spread: Dinâmico (volatilidade + inventário)
  3. Pennying: Superar concorrentes por 0.01
  4. Order Diffing: Atualizar apenas quando necessário
  5. Gestão de Inventário: Ajustar quotes por holdings

Fluxo de Ordens

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

Dashboard web em tempo real incluído.

Acesso

Com o bot rodando:

http://localhost:8081/dashboard

Recursos

  • 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

Portas

Porta Serviço
8080 Endpoint de saúde
8081 Dashboard Web

Monitoramento

Health Check

curl http://localhost:8080/health

Resposta:

{
  "status": "healthy",
  "markets_count": 11,
  "circuit_breaker": "CLOSED",
  "websocket_connected": true,
  "realized_pnl": 12.54,
  "orders_placed": 156,
  "total_trades": 23
}

Logs

Logs no console e em logs/bot.log:

  • Verde = INFO
  • Amarelo = WARNING
  • Vermelho = ERROR
  • [DRY-RUN] = Ações simuladas

Persistência

Métricas salvas em src/metrics_data.json a cada 60s e no shutdown.


Estrutura do Projeto

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

Entendendo as Mensagens de Log

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

Solução de Problemas

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

Antes da Primeira Execução

  1. Tenha Iron na carteira Blocky
  2. Comece com dry_run: true
  3. Use um mercado: enabled_markets: [diam_iron]
  4. Monitore via dashboard

Teste Dry Run

trading:
  dry_run: true

Logs mostram [DRY-RUN] para ações simuladas.


Compilando o Executável Windows

Para desenvolvedores que desejam compilar o .exe.

Pré-requisitos

  1. Python 3.11+ instalado

    • Baixe em python.org
    • Durante a instalação, marque "Add Python to PATH"
    • Verifique: python --version
  2. Git instalado

Passos para Compilar

# 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.bat

O 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

Resultado da Compilação

  • Executável: dist/BlockyMarketMaker.exe
  • Tamanho esperado: ~50-80MB
  • Tempo de build: 1-3 minutos

Testando o Build

  1. Crie uma pasta vazia (ex: C:\BlockyTest\)
  2. Copie dist/BlockyMarketMaker.exe para esta pasta
  3. Copie config.yaml para a mesma pasta (como template)
  4. Dê duplo clique em BlockyMarketMaker.exe
  5. O assistente de configuração deve abrir

Distribuindo

Para compartilhar com outros usuários, eles precisam apenas de:

  • BlockyMarketMaker.exe
  • config.yaml (opcional, usa padrões se ausente)

Usuários NÃO precisam ter Python instalado.

Solução de Problemas de Build

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

Adicionando um Ícone (Opcional)

  1. Crie ou baixe um arquivo .ico
  2. Salve como img/icon.ico
  3. Descomente a linha do ícone em blocky.spec:
    icon='img/icon.ico',
  4. Recompile


License

This project is licensed under the MIT License - see the LICENSE file for details.

Contributing

Pull requests welcome. For major changes, open an issue first.


Made for the Blocky community

About

Base of a Market Marker bot for BlockyCRAFT

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors