API for Trading Bot Management
A trading bot without management API is a monolith: to change a parameter, you must SSH into server, edit config, restart. Management API solves this: bot is managed remotely via HTTP or WebSocket, parameters change on-the-fly without restart.
Management API Architecture
Main Endpoints
// Bot lifecycle
POST /api/v1/bot/start - start bot
POST /api/v1/bot/stop - stop
POST /api/v1/bot/pause - pause (no new positions)
GET /api/v1/bot/status - current status
// Configuration
GET /api/v1/bot/config - current parameters
PUT /api/v1/bot/config - update parameters (hot reload)
// Monitoring
GET /api/v1/bot/stats - P&L, metrics
GET /api/v1/bot/positions - open positions
GET /api/v1/bot/trades?from=&to= - trade history
GET /api/v1/bot/logs?level=&limit= - logs real-time
// Manual Operations
POST /api/v1/bot/close-all - force close all positions
POST /api/v1/bot/cancel-pending - cancel pending orders
Hot Reload Configuration
type BotConfig struct {
mu sync.RWMutex
Symbol string `json:"symbol"`
Timeframe string `json:"timeframe"`
PositionSizePct float64 `json:"position_size_pct"`
StopLossPct float64 `json:"stop_loss_pct"`
TakeProfitPct float64 `json:"take_profit_pct"`
MaxPositions int `json:"max_positions"`
Enabled bool `json:"enabled"`
}
func (c *BotConfig) Update(newConfig map[string]interface{}) error {
c.mu.Lock()
defer c.mu.Unlock()
// Validation
if sl, ok := newConfig["stop_loss_pct"].(float64); ok {
if sl < 0.1 || sl > 50 {
return errors.New("stop_loss_pct must be between 0.1 and 50")
}
c.StopLossPct = sl
}
if pct, ok := newConfig["position_size_pct"].(float64); ok {
if pct < 1 || pct > 100 {
return errors.New("position_size_pct must be between 1 and 100")
}
c.PositionSizePct = pct
}
// Bot will pick up new parameters on next cycle
return nil
}
// Handler for PUT /config
func (h *Handler) UpdateConfig(w http.ResponseWriter, r *http.Request) {
var updates map[string]interface{}
json.NewDecoder(r.Body).Decode(&updates)
if err := h.bot.Config.Update(updates); err != nil {
writeError(w, 400, err.Error())
return
}
writeJSON(w, map[string]interface{}{
"success": true,
"config": h.bot.Config.Get(),
})
}
WebSocket for Real-time Monitoring
// Bot publishes events to channel, API streams via WebSocket
type BotEvent struct {
Type string `json:"type"` // trade, signal, error, status_change
Timestamp int64 `json:"ts"`
Data interface{} `json:"data"`
}
func (api *ManagementAPI) StreamEvents(w http.ResponseWriter, r *http.Request) {
conn, _ := upgrader.Upgrade(w, r, nil)
defer conn.Close()
subscription := api.bot.EventBus.Subscribe()
defer api.bot.EventBus.Unsubscribe(subscription)
for {
select {
case event := <-subscription:
conn.WriteJSON(event)
case <-r.Context().Done():
return
}
}
}
Management API Authentication
Management API controls real money — access must be strictly limited:
func authMiddleware(secret string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
if !strings.HasPrefix(token, "Bearer ") {
writeError(w, 401, "Unauthorized")
return
}
if token[7:] != secret {
writeError(w, 401, "Invalid token")
return
}
next.ServeHTTP(w, r)
})
}
}
Bind only to localhost or through VPN — Management API should not be exposed directly to the internet.
Dashboard (Optional UI)
Simple web interface for bot management:
// React component for bot control
function BotDashboard() {
const [status, setStatus] = useState<BotStatus | null>(null);
// WebSocket for real-time updates
useEffect(() => {
const ws = new WebSocket(`ws://localhost:8080/ws/events`);
ws.onmessage = (e) => {
const event = JSON.parse(e.data);
if (event.type === 'status_change') setStatus(event.data);
if (event.type === 'trade') addTrade(event.data);
};
return () => ws.close();
}, []);
const toggleBot = async () => {
await fetch(`/api/v1/bot/${status?.running ? 'stop' : 'start'}`, { method: 'POST' });
};
return (
<div>
<StatusCard status={status} onToggle={toggleBot} />
<PnLChart />
<OpenPositions />
<ConfigEditor onSave={(config) => updateConfig(config)} />
</div>
);
}
Management API for trading bot with hot reload, WebSocket streaming, and basic dashboard is developed in 2–3 weeks.







