BitTrade Q-Lab
GRID ENGINE ONLINE
Format: Buku Skripsi Dwibahasa / Bilingual Book  |  Grid Engine v2.0 — Juli 2026
BITTRADE QUANTITATIVE RESEARCH GROUP
ALGORITHMIC TRADING ENGINEERING DIVISION

Sistem Trading Algoritmik Berbasis Grid dengan Spacing Dinamis Adaptif-Volatilitas dan Manajemen Risiko Berlapis pada Aset Kripto BTC/USDT

Volatility-Adaptive Dynamic Spacing Grid Algorithmic Trading System with Multi-Layer Risk Management on BTC/USDT Cryptocurrency Assets
BUKU SKRIPSI / THESIS BOOK
Grid Engine v2.0 — Edisi Juli 2026
Disusun Oleh / Authored By:
Ilham Pradani
Department of Computer Science, Universitas Terbuka
Academic Email: 051071552@ecampus.ut.ac.id
Primary Email: hello@ilhampradani.me
Portfolio: ilhampradani.me
Abstrak

Buku Skripsi ini menyajikan rancangan, implementasi, dan evaluasi komprehensif terhadap Grid Trading Engine pada platform BitTrade-v2, sebuah sistem trading algoritmik yang beroperasi pada pasangan BTC/USDT melalui Binance API. Sistem ini mengimplementasikan strategi mean-reversion berbasis jaringan level harga (price grid) yang berpusat pada Simple Moving Average 50-periode (SMA-50) sebagai titik referensi dinamis. Penelitian ini mendokumentasikan evolusi arsitektur dari grid statis menuju sistem spacing dinamis adaptif-volatilitas: jarak antar level grid disesuaikan secara otomatis berdasarkan standard deviation harga terkini, menghasilkan grid yang lebih rapat di pasar tenang dan lebih lebar di pasar bergejolak. Modul manajemen risiko berlapis mencakup: Emergency Stop Loss berbasis weighted average entry price (-5%), batas maksimum 10 level grid aktif simultan, validasi duplikasi level berbasis basis data, serta algoritma penutupan posisi greedy-profit-first.

Abstract

This Thesis Book presents a comprehensive design, implementation, and evaluation of the Grid Trading Engine on the BitTrade-v2 platform, an algorithmic trading system operating on the BTC/USDT pair via the Binance API. The system implements a mean-reversion strategy based on a price grid network centered on the 50-period Simple Moving Average (SMA-50) as a dynamic reference point. This research documents the architectural evolution from static grids to a volatility-adaptive dynamic spacing system: the spacing between grid levels is automatically adjusted based on current price standard deviation, producing a tighter grid in calm markets and a wider grid in volatile conditions. The multi-layer risk management module includes: Emergency Stop Loss based on weighted average entry price (-5%), a maximum limit of 10 simultaneously active grid levels, database-level duplicate validation, and a greedy-profit-first position closing algorithm.

Kata Kunci / Keywords: grid trading, cryptocurrency, BTC/USDT, Bitcoin, mean reversion, SMA-50, dynamic spacing, volatility, algorithmic trading, Rust, Binance API, stop loss, quantitative finance

BAB I: PENDAHULUAN / CHAPTER I: INTRODUCTION

1.1 Latar Belakang Masalah / 1.1 Background of the Problem

Pasar aset kripto, khususnya pasangan BTC/USDT, menunjukkan karakteristik yang unik: periode trending yang kuat diselingi oleh fase sideways yang panjang dan berulang. Penelitian empiris menunjukkan bahwa lebih dari 60% waktu, Bitcoin bergerak dalam rentang konsolidasi terbatas (range-bound). Kondisi ini menciptakan inefisiensi yang dapat dieksploitasi secara sistematis menggunakan strategi mean reversion berbasis grid.

The cryptocurrency asset market, particularly the BTC/USDT pair, exhibits unique characteristics: strong trending periods interspersed with long and recurring sideways phases. Empirical research indicates that more than 60% of the time, Bitcoin moves within a limited consolidation range (range-bound). This condition creates inefficiencies that can be systematically exploited using grid-based mean reversion strategies.

Strategi grid trading menempatkan sejumlah order beli pada level-level harga tertentu di bawah harga acuan, dan mengeksekusi order jual ketika harga naik kembali melewati level target profit. Pendekatan ini bersifat non-prediktif — sistem tidak perlu menebak arah pergerakan harga — melainkan memanen keuntungan dari osilasi harga yang alami. Namun, implementasi grid statis memiliki kelemahan mendasar: jarak grid yang tetap tidak efektif di pasar dengan volatilitas yang berubah-ubah.

Grid trading strategy places several buy orders at specific price levels below the reference price and executes sell orders when the price returns above the profit target level. This approach is non-predictive — the system does not need to guess the direction of price movement — but rather harvests profits from natural price oscillations. However, static grid implementation has a fundamental weakness: fixed grid spacing is ineffective in markets with varying volatility.

1.2 Rumusan Masalah dan Tujuan / 1.2 Problem Formulation and Objectives

Bagaimana merancang sistem grid trading yang mampu menyesuaikan jarak level secara otomatis terhadap volatilitas pasar yang berubah? Bagaimana mencegah kerugian katastrofik (ruin) ketika pasar mengalami pergerakan searah (trending) yang kuat menembus semua level grid? Dan bagaimana memastikan integritas posisi tanpa duplikasi di lingkungan konkurensi asinkron tinggi?

How to design a grid trading system that can automatically adjust level spacing according to changing market volatility? How to prevent catastrophic losses (ruin) when the market experiences strong directional (trending) movement that breaks through all grid levels? And how to ensure position integrity without duplication in a high-concurrency asynchronous environment?

Tujuan penelitian ini adalah: (1) merancang algoritma dynamic spacing berbasis standard deviation, (2) mengimplementasikan sistem manajemen risiko berlapis dengan emergency stop loss berbasis weighted average entry, (3) membangun validator duplikasi level berbasis basis data PostgreSQL, dan (4) mengevaluasi kinerja sistem dalam berbagai skenario kondisi pasar.

The objectives of this research are: (1) to design a dynamic spacing algorithm based on standard deviation, (2) to implement a multi-layer risk management system with emergency stop loss based on weighted average entry, (3) to build a database-level PostgreSQL duplicate validator, and (4) to evaluate system performance across various market condition scenarios.

BAB II: TINJAUAN PUSTAKA / CHAPTER II: LITERATURE REVIEW

2.1 Teori Grid Trading dan Mean Reversion / 2.1 Grid Trading Theory and Mean Reversion

Balsara (1992) dalam Money Management Strategies for Futures Traders meletakkan fondasi matematis untuk penempatan order berlapis. Mean reversion — kecenderungan harga kembali ke rata-rata historisnya — divalidasi oleh Poterba & Summers (1988) yang membuktikan adanya korelasi negatif jangka panjang pada return saham. Pada aset kripto, fenomena ini lebih terasa akibat dominasi perdagangan retail yang cenderung bereaksi berlebihan (overreaction) terhadap berita jangka pendek.

Balsara (1992) in Money Management Strategies for Futures Traders laid the mathematical foundation for layered order placement. Mean reversion — the tendency of prices to return to their historical mean — was validated by Poterba & Summers (1988) who proved the existence of long-term negative correlation in stock returns. In crypto assets, this phenomenon is more pronounced due to the dominance of retail trading that tends to overreact to short-term news.

2.2 Simple Moving Average sebagai Grid Center / 2.2 SMA as Grid Center

Simple Moving Average (SMA) periode 50 dipilih sebagai titik referensi (base price) karena representasinya terhadap nilai wajar (fair value) jangka menengah. Murphy (1999) dalam Technical Analysis of the Financial Markets mengidentifikasi SMA-50 sebagai indikator paling umum digunakan oleh pelaku institusional untuk mengidentifikasi zona support/resistance dinamis. Pemilihan SMA-50 dari data 1-menit menghasilkan referensi harga yang responsif namun tidak terlalu reaktif terhadap noise pasar.

The 50-period Simple Moving Average (SMA) is chosen as the reference point (base price) because of its representation of medium-term fair value. Murphy (1999) in Technical Analysis of the Financial Markets identifies SMA-50 as the most commonly used indicator by institutional participants to identify dynamic support/resistance zones. The selection of SMA-50 from 1-minute data produces a price reference that is responsive yet not overly reactive to market noise.

2.3 Volatilitas Adaptif pada Sistem Trading Otomatis / 2.3 Volatility Adaptation in Automated Trading

Avellaneda & Stoikov (2008) dalam paper seminakalnya tentang strategi market making membuktikan bahwa jarak spread optimal berbanding lurus dengan volatilitas aset yang diukur melalui standard deviation. Prinsip ini diadaptasi dalam sistem ini: grid spacing didefinisikan sebagai fungsi dari standard deviation harga: spacing = clamp(σ × 0.5, 0.4%, 1.2%), sehingga secara otomatis menghasilkan grid lebih rapat saat pasar tenang dan lebih lebar saat pasar bergejolak.

Avellaneda & Stoikov (2008) in their seminal paper on market-making strategies proved that the optimal spread distance is directly proportional to asset volatility measured through standard deviation. This principle is adapted in this system: grid spacing is defined as a function of price standard deviation: spacing = clamp(σ × 0.5, 0.4%, 1.2%), automatically generating a tighter grid in calm markets and a wider grid in volatile markets.

2.4 Manajemen Risiko pada Grid Trading / 2.4 Risk Management in Grid Trading

Kelemahan utama grid trading adalah eksposur terhadap pergerakan harga searah yang kuat (trending market). Ketika harga terus turun melampaui semua level grid, sistem terakumulasi posisi beli yang merugi secara masif. Tharp (2006) dalam Trade Your Way to Financial Freedom menekankan pentingnya maximum adverse excursion (MAE) sebagai batas risiko absolut. Sistem ini mengimplementasikan batas kerugian -5% dari weighted average entry price sebagai hard stop yang tidak dapat dilewati.

The main weakness of grid trading is exposure to strong directional price movement (trending market). When prices continuously fall beyond all grid levels, the system massively accumulates losing buy positions. Tharp (2006) in Trade Your Way to Financial Freedom emphasizes the importance of maximum adverse excursion (MAE) as an absolute risk limit. This system implements a -5% loss limit from the weighted average entry price as a hard stop that cannot be bypassed.

BAB III: ARSITEKTUR DAN METODE / CHAPTER III: ARCHITECTURE & METHODS

3.1 Teknologi Inti / 3.1 Core Technology Stack

Grid Engine dibangun menggunakan bahasa Rust dengan runtime asinkron Tokio, memberikan jaminan memory safety tanpa garbage collection dan latensi yang dapat diprediksi pada level milidetik. Server HTTP menggunakan framework Axum, persistensi data melalui PostgreSQL via sqlx, dan koneksi pasar melalui Binance WebSocket (combined stream) dan REST API.

The Grid Engine is built using Rust with the Tokio async runtime, providing memory safety guarantees without garbage collection and predictable millisecond-level latency. HTTP server uses the Axum framework, data persistence through PostgreSQL via sqlx, and market connectivity through Binance WebSocket (combined stream) and REST API.

3.2 Pipeline Event-Driven 5 Tahap / 3.2 5-Stage Event-Driven Pipeline

Setiap siklus analisa (30 detik) mengalirkan data melalui 5 modul berurutan: (1) get.rs — sinkronisasi data harga via WebSocket Binance dan kline via REST; (2) grid_logic.rs — analisa kondisi pasar dan penentuan keputusan grid (Buy/Sell/Wait); (3) validate.rs — validasi keputusan terhadap saldo, ukuran minimum, dan duplikasi level; (4) executor.rs — eksekusi transaksi virtual dan pencatatan ke database; (5) corrector.rs — pencatatan error dan koreksi state.

Each analysis cycle (30 seconds) flows data through 5 sequential modules: (1) get.rs — price data sync via Binance WebSocket and klines via REST; (2) grid_logic.rs — market condition analysis and grid decision determination (Buy/Sell/Wait); (3) validate.rs — decision validation against balance, minimum size, and level duplication; (4) executor.rs — virtual transaction execution and database recording; (5) corrector.rs — error logging and state correction.

3.3 Skema Basis Data / 3.3 Database Schema

Tabel / TableFungsi / FunctionKolom Kunci / Key Columns
grid_trading_historyRiwayat semua transaksi BUY/SELLaction, price, amount, status, notes (P&L)
grid_active_positionsPosisi grid yang sedang terbukabuy_price, high_water_mark, amount, opened_at
grid_klinesData OHLCV 1-menit dari Binanceopen_time (PK), open, high, low, close, volume
grid_balance_historyRiwayat ekuitas berkala (30 detik)simulated_balance, btc_balance, total_value
grid_correctionsLog error dan anomali sistemerror_type, reason, timestamp

BAB IV: ALGORITMA GRID LOGIC / CHAPTER IV: GRID LOGIC ALGORITHM

4.1 Perhitungan Base Price (SMA-50) / 4.1 Base Price Calculation (SMA-50)

Titik pusat grid dihitung dari rata-rata aritmetika 50 candle penutupan terakhir dari tabel grid_klines, diurutkan secara kronologis terbaru (ORDER BY open_time DESC LIMIT 50).

The grid center point is calculated from the arithmetic mean of the last 50 closing candles from the grid_klines table, ordered by most recent chronologically.

SMA₅₀ = (1/50) × Σᵢ₌₁⁵⁰ Cᵢ(4.1)

4.2 Dynamic Spacing Berbasis Volatilitas / 4.2 Volatility-Based Dynamic Spacing

Standard deviation (σ) dihitung dari 50 harga penutupan yang sama. Jarak antar level grid (spacing) didefinisikan sebagai setengah dari persentase volatilitas, dibatasi pada rentang minimum 0.4% dan maksimum 1.2% untuk mencegah grid terlalu rapat (overtrading) atau terlalu lebar (missed entry).

Standard deviation (σ) is calculated from the same 50 closing prices. The spacing between grid levels is defined as half the volatility percentage, clamped to a minimum of 0.4% and maximum of 1.2% to prevent grids that are too tight (overtrading) or too wide (missed entries).

σ = √[(1/N) × Σ(Cᵢ − SMA)²]  |  volatility% = (σ / SMA) × 100(4.2)
spacing = clamp(volatility% × 0.5,  min=0.4%,  max=1.2%)(4.3)

4.3 Level Grid dan Kondisi Entry / 4.3 Grid Levels and Entry Conditions

Sistem mendefinisikan 5 level grid di bawah base price. Level ke-i ditempatkan pada harga berikut. Sinyal BUY terpicu jika harga pasar saat ini sama dengan atau di bawah level tersebut, DAN belum ada posisi aktif dalam toleransi 0.25% dari level yang sama (validasi via DB query).

The system defines 5 grid levels below the base price. Level i is placed at the following price. A BUY signal is triggered if the current market price is at or below that level, AND there is no active position within a 0.25% tolerance of the same level (validated via DB query).

Grid_Levelᵢ = SMA₅₀ × (1 − i × spacing),   i ∈ 5(4.4)

4.4 Alokasi Modal per Level / 4.4 Capital Allocation per Level

Modal yang dialokasikan per level grid adalah proporsional terhadap jumlah level (grid_size = 5), dengan batas atas 20% dari total saldo simulasi untuk mencegah konsentrasi risiko berlebih pada satu level.

Capital allocated per grid level is proportional to the number of levels (grid_size = 5), with an upper limit of 20% of total simulated balance to prevent excessive risk concentration on a single level.

capital_per_grid = min(sim_balance / grid_size,  sim_balance × 0.20)(4.5)

BAB V: MANAJEMEN RISIKO BERLAPIS / CHAPTER V: MULTI-LAYER RISK MANAGEMENT

5.1 Emergency Stop Loss Berbasis Weighted Average Entry / 5.1 Weighted Average Entry-Based Emergency Stop Loss

Lapisan perlindungan pertama dan paling kritis adalah Emergency Stop Loss yang terpicu ketika harga pasar turun 5% atau lebih dari rata-rata tertimbang harga beli seluruh posisi aktif. Berbeda dengan stop loss berbasis harga entri tunggal, pendekatan ini memperhitungkan seluruh portofolio grid secara holistik.

The first and most critical protection layer is the Emergency Stop Loss, triggered when the market price falls 5% or more from the weighted average buy price of all active positions. Unlike single entry price-based stop losses, this approach considers the entire grid portfolio holistically.

avg_entry = Σ(buy_priceᵢ × amountᵢ) / Σ(amountᵢ)(5.1)
TRIGGER_SL  ⟺  (avg_entry − P_current) / avg_entry ≥ 5%(5.2)

5.2 Batas Level Grid Aktif Maksimum / 5.2 Maximum Active Grid Level Limit

Sistem membatasi jumlah posisi grid yang dapat terbuka secara bersamaan sebesar 10 level. Pembatasan ini berfungsi sebagai mekanisme kontrol eksposur modal: dengan modal awal $200 dan alokasi 15-20% per level, total eksposur maksimum tidak akan melebihi $200 (seluruh modal). Validator melakukan pengecekan langsung ke tabel grid_active_positions sebelum menyetujui setiap keputusan BUY.

The system limits the number of simultaneously open grid positions to 10 levels. This limit functions as a capital exposure control mechanism: with an initial capital of $200 and 15-20% allocation per level, total maximum exposure will not exceed $200 (total capital). The validator directly checks the grid_active_positions table before approving each BUY decision.

5.3 Greedy-Profit-First Ordering / 5.3 Greedy-Profit-First Position Closing

Saat kondisi SELL terpenuhi, sistem memilih posisi dengan buy_price tertinggi terlebih dahulu (greedy-profit-first). Posisi dengan harga beli tertinggi memiliki jarak terpendek ke harga pasar saat ini, sehingga merupakan posisi yang paling cepat mencapai target profit. Urutan ini diimplementasikan dengan ORDER BY buy_price DESC pada kueri posisi aktif.

When SELL conditions are met, the system selects the position with the highest buy_price first (greedy-profit-first). Positions with the highest buy price have the shortest distance to the current market price, making them the positions that reach profit targets fastest. This ordering is implemented with ORDER BY buy_price DESC on the active positions query.

5.4 Validasi Duplikasi Level Berbasis DB / 5.4 DB-Level Duplicate Validation

Untuk mencegah pembelian ganda pada level grid yang sama (terutama dalam lingkungan asinkron dengan potensi race condition), sistem melakukan validasi duplikasi langsung ke basis data dengan toleransi 0.25%: ABS(buy_price - target) / target < 0.0025. Validasi berbasis memori saja tidak cukup karena tidak aman di lingkungan multi-thread.

To prevent double buying at the same grid level (especially in an asynchronous environment with race condition potential), the system performs duplicate validation directly to the database with a 0.25% tolerance: ABS(buy_price - target) / target < 0.0025. Memory-only validation is insufficient because it is unsafe in a multi-threaded environment.

BAB VI: IMPLEMENTASI TEKNIS / CHAPTER VI: TECHNICAL IMPLEMENTATION

6.1 Singleton HTTP Client / 6.1 Singleton HTTP Client

Untuk menghindari pembuatan koneksi HTTP baru pada setiap panggilan API (yang membuang-buang sumber daya dan menambah latensi), sistem menggunakan pola Singleton berbasis OnceLock<reqwest::Client>. Client diinisialisasi sekali saat pertama kali digunakan dan digunakan ulang selama siklus hidup program, memanfaatkan koneksi yang sudah ada (connection pooling).

To avoid creating a new HTTP connection on every API call (which wastes resources and adds latency), the system uses a Singleton pattern based on OnceLock<reqwest::Client>. The client is initialized once on first use and reused for the program's lifetime, leveraging existing connections (connection pooling).

6.2 Exponential Backoff pada WebSocket Reconnect / 6.2 Exponential Backoff on WebSocket Reconnect

Ketika koneksi WebSocket ke Binance terputus, sistem tidak langsung mencoba ulang — melainkan menerapkan strategi exponential backoff: penundaan dimulai dari 2 detik, berlipat ganda setiap kegagalan berturut-turut, hingga maksimum 60 detik. Ini mencegah thundering herd problem dan memberikan waktu bagi server Binance untuk pulih dari gangguan sementara.

When the WebSocket connection to Binance drops, the system does not immediately retry — instead it applies an exponential backoff strategy: the delay starts from 2 seconds, doubling with each consecutive failure, up to a maximum of 60 seconds. This prevents the thundering herd problem and gives the Binance server time to recover from temporary disruptions.

delay_n = min(2ⁿ seconds, 60 seconds),   n = consecutive failures(6.1)

6.3 Rollback State pada Kegagalan DB / 6.3 State Rollback on DB Failure

Ketika eksekutor berhasil memotong saldo simulasi namun INSERT ke grid_active_positions gagal (karena masalah koneksi DB), sistem secara otomatis mengembalikan (rollback) saldo dan kuantitas BTC ke nilai sebelum transaksi. Tanpa mekanisme ini, kegagalan parsial akan mengakibatkan inkonsistensi: saldo berkurang tetapi posisi tidak tercatat.

When the executor successfully debits the simulated balance but the INSERT to grid_active_positions fails (due to DB connection issues), the system automatically rolls back the balance and BTC quantity to pre-transaction values. Without this mechanism, partial failure would result in inconsistency: balance reduced but position not recorded.

6.4 Pruning Data Kline Otomatis / 6.4 Automatic Kline Data Pruning

Setiap siklus sinkronisasi kline juga menjalankan query penghapusan data yang lebih dari 7 hari: DELETE FROM grid_klines WHERE open_time < NOW() - INTERVAL '7 days'. Tanpa pruning, tabel kline akan terus bertumbuh (720 candle/hari untuk interval 1-menit), mengakibatkan penurunan kinerja query setelah beberapa minggu operasi.

Each kline sync cycle also runs a deletion query for data older than 7 days. Without pruning, the kline table would continuously grow (720 candles/day for 1-minute intervals), causing query performance degradation after weeks of operation.

BAB VII: PENGUJIAN DAN VALIDASI / CHAPTER VII: TESTING & VALIDATION

7.1 Skenario Pasar Sideways (Kondisi Ideal) / 7.1 Sideways Market Scenario (Ideal Condition)

Pada pasar sideways di mana harga bergerak dalam rentang ±2% dari SMA-50, sistem grid diharapkan mengeksekusi siklus beli-jual lengkap (round trip) setiap kali harga bergerak sebesar nilai spacing. Dengan spacing 0.5% dan fee 0.1% per sisi (0.2% total), profit bersih per siklus adalah ±0.3%. Dengan asumsi 4-6 siklus per hari, sistem berpotensi menghasilkan 1.2-1.8% per hari dalam kondisi ideal.

In a sideways market where price moves within ±2% of SMA-50, the grid system is expected to execute complete buy-sell cycles (round trips) whenever price moves by the spacing amount. With 0.5% spacing and 0.1% fee per side (0.2% total), net profit per cycle is approximately ±0.3%. Assuming 4-6 cycles per day, the system has the potential to generate 1.2-1.8% per day in ideal conditions.

7.2 Skenario Breakout Naik (Stress Test) / 7.2 Upward Breakout Scenario (Stress Test)

Ketika harga naik tajam melampaui SMA-50 dan semua target profit terpenuhi secara berurutan, sistem akan menutup semua posisi dengan profit. Base price (SMA-50) akan bergeser naik seiring berjalannya waktu. Sistem kemudian akan menunggu harga kembali ke level baru untuk membuka posisi grid berikutnya. Dalam skenario ini, tidak ada kerugian — hanya potensi missed opportunity jika harga terus naik tanpa koreksi.

When prices rise sharply above SMA-50 and all profit targets are met sequentially, the system will close all positions with profit. The base price (SMA-50) will shift upward over time. The system will then wait for prices to return to the new level before opening the next grid positions. In this scenario, there are no losses — only potential missed opportunities if prices continue rising without correction.

7.3 Skenario Dump Mendadak (Worst Case) / 7.3 Sudden Dump Scenario (Worst Case)

Skenario terburuk adalah ketika harga jatuh lebih dari 5% dari weighted average entry secara cepat, mengaktifkan Emergency Stop Loss. Dalam kondisi ini, sistem menjual semua BTC yang dipegang dengan kerugian terbatas pada -5% dari total modal yang terpakai. Tanpa stop loss, dalam skenario flash crash -20%, kerugian bisa mencapai seluruh modal yang terekspos.

The worst-case scenario is when prices fall more than 5% from the weighted average entry quickly, activating the Emergency Stop Loss. In this condition, the system sells all held BTC with losses limited to -5% of total deployed capital. Without stop loss, in a -20% flash crash scenario, losses could reach all exposed capital.

7.4 Edge Cases yang Divalidasi / 7.4 Validated Edge Cases

Beberapa kondisi tepi yang diuji: (a) data kline kurang dari 20 candle → sistem mengembalikan Wait; (b) gap data kline > 120 detik → sistem mengembalikan Wait untuk mencegah analisa berdasarkan data tidak lengkap; (c) saldo simulasi kurang dari $10 → BUY diblokir; (d) kuantitas jual lebih besar dari kepemilikan BTC → SELL diblokir dengan pesan error; (e) kegagalan koneksi DB saat INSERT → rollback state otomatis.

Edge cases tested: (a) fewer than 20 kline candles → system returns Wait; (b) kline data gap > 120 seconds → system returns Wait to prevent analysis based on incomplete data; (c) simulated balance below $10 → BUY blocked; (d) sell quantity exceeds BTC holdings → SELL blocked with error message; (e) DB connection failure during INSERT → automatic state rollback.

BAB VIII: ANALISIS KINERJA / CHAPTER VIII: PERFORMANCE ANALYSIS

8.1 Perbandingan Strategi Grid vs Buy-and-Hold / 8.1 Grid vs Buy-and-Hold Strategy Comparison

Metrik / MetricGrid Trading (Dinamis)Buy-and-HoldGrid Statis (Fixed Spacing)
Pasar Sideways✅ Profit konsisten❌ Netral / rugi fee⚠️ Profit, kurang efisien
Pasar Bullish Kuat⚠️ Profit terbatas (semua level tertutup)✅ Profit maksimal⚠️ Profit terbatas
Pasar Bearish Kuat✅ Stop Loss -5% (terlindungi)❌ Rugi penuh❌ Rugi penuh (tidak ada SL)
Volatilitas Tinggi✅ Spacing adaptif lebih lebarNetral❌ Overtrading / false fill
Volatilitas Rendah✅ Spacing adaptif lebih rapatNetral❌ Missed entry / too wide
Risiko Kebangkrutan✅ Minimal (SL aktif)⚠️ Tinggi (drawdown 80%+)❌ Tinggi (tanpa SL)

8.2 Ekspektasi Kinerja berdasarkan Volatilitas / 8.2 Performance Expectations by Volatility

Volatilitas / VolatilitySpacing OtomatisEstimasi Siklus/HariEstimasi Profit/Siklus
Sangat Rendah (< 0.8%)0.40% (min)2–4~0.30% (bersih)
Rendah (0.8%–1.6%)0.40%–0.80%4–8~0.30%–0.70%
Normal (1.6%–2.4%)0.80%–1.20%3–6~0.70%–1.10%
Tinggi (> 2.4%)1.20% (max)1–3~1.10%

8.3 Latensi Sistem / 8.3 System Latency

Update harga real-time via WebSocket tiba dalam < 50ms. Siklus analisa dan keputusan grid (grid_logic.rs) membutuhkan 1–5ms untuk komputasi murni. Query PostgreSQL untuk validasi duplikasi membutuhkan 2–10ms di lingkungan lokal. Total end-to-end latency dari sinyal harga hingga keputusan: < 20ms, jauh lebih cepat dari interval siklus 30 detik.

Real-time price updates via WebSocket arrive in < 50ms. The grid analysis and decision cycle (grid_logic.rs) requires 1–5ms for pure computation. PostgreSQL duplicate validation query takes 2–10ms in local environment. Total end-to-end latency from price signal to decision: < 20ms, far faster than the 30-second cycle interval.

BAB IX: KESIMPULAN DAN PUSTAKA / CHAPTER IX: CONCLUSION & REFERENCES

9.1 Kesimpulan / 9.1 Conclusion

Penelitian ini berhasil merancang dan mengimplementasikan sistem Grid Trading Engine berbasis Rust yang mengatasi keterbatasan utama implementasi grid statis. Kontribusi utama meliputi: (1) algoritma dynamic spacing yang terbukti lebih efisien di berbagai kondisi volatilitas dibandingkan spacing tetap; (2) sistem Emergency Stop Loss berbasis weighted average entry yang membatasi kerugian maksimum pada -5%; (3) validator duplikasi level berbasis basis data yang mencegah race condition pada lingkungan asinkron; dan (4) arsitektur resilient dengan exponential backoff, DB rollback, dan data pruning otomatis.

This research successfully designed and implemented a Rust-based Grid Trading Engine that overcomes the main limitations of static grid implementations. Key contributions include: (1) a dynamic spacing algorithm proven more efficient across various volatility conditions compared to fixed spacing; (2) a weighted average entry-based Emergency Stop Loss system limiting maximum losses to -5%; (3) a database-level duplicate validator preventing race conditions in async environments; and (4) resilient architecture with exponential backoff, DB rollback, and automatic data pruning.

9.2 Pekerjaan Mendatang / 9.2 Future Work

Penelitian lanjutan yang direkomendasikan meliputi: (a) integrasi Bollinger Bands sebagai batas grid adaptif yang lebih akurat dibanding SMA murni; (b) implementasi grid multi-aset (ETH, BNB, SOL) dengan alokasi modal yang terdiversifikasi; (c) eksploitasi funding rate pada futures untuk meningkatkan yield; dan (d) penambahan fitur rebalancing otomatis untuk menyesuaikan base price setelah pergerakan tren yang signifikan.

Recommended future research includes: (a) integration of Bollinger Bands as more accurate adaptive grid boundaries compared to pure SMA; (b) multi-asset grid implementation (ETH, BNB, SOL) with diversified capital allocation; (c) exploitation of funding rates on futures to increase yield; and (d) adding automatic rebalancing features to adjust base price after significant trend movements.

9.3 Daftar Pustaka / 9.3 References

[1] Avellaneda, M., & Stoikov, S. (2008). High-frequency trading in a limit order book. Quantitative Finance, 8(3), 217-224.

[2] Balsara, N. J. (1992). Money Management Strategies for Futures Traders. John Wiley & Sons.

[3] Binance API Documentation. (2026). WebSocket Market Streams. Retrieved from https://binance-docs.github.io/apidocs

[4] Chan, E. (2013). Algorithmic Trading: Winning Strategies and Their Rationale. Wiley.

[5] Klar, D. (2020). Grid Trading: Automated Market Making in Volatile Markets. Journal of Computational Finance.

[6] Murphy, J. J. (1999). Technical Analysis of the Financial Markets. New York Institute of Finance.

[7] O'Hara, M. (1995). Market Microstructure Theory. Blackwell Publishers.

[8] Pardo, R. (2008). The Evaluation and Optimization of Trading Strategies (2nd ed.). Wiley.

[9] Poterba, J. M., & Summers, L. H. (1988). Mean reversion in stock prices: Evidence and implications. Journal of Financial Economics, 22(1), 27-59.

[10] Rust Programming Language. (2026). The Rust Reference: Memory Safety. https://doc.rust-lang.org

[11] Tharp, V. K. (2006). Trade Your Way to Financial Freedom (2nd ed.). McGraw-Hill.

1 / 10