Skip to content

gopher-lab/tools-go

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

tools-go

A reusable trading tools framework for AI agent runtimes.

Overview

This package provides a clean, interface-based implementation of trading tools for AI agents. It is designed to be implementation-agnostic, allowing consumers to provide their own wallet, state, and market data implementations.

Installation

go get github.com/gopher-lab/tools-go

Quick Start

package main

import (
    "context"

    tools "github.com/gopher-lab/tools-go"
    tradingtools "github.com/gopher-lab/tools-go/tools"
)

func main() {
    // Create your implementations of the interfaces
    wallet := NewMyWallet()           // implements tools.Wallet
    state := NewMyState()             // implements tools.State
    config := NewMyConfig()           // implements tools.Config
    marketClient := NewMyMarket()     // implements tools.MarketDataProvider

    // Create the tool context
    ctx := tools.NewContext(wallet, marketClient, state, config)

    // Optionally add persistence and callbacks
    ctx.WithPersistence(myPersistence).
        WithCallbacks(
            onStateUpdate,
            onPositionOpened,
            onPositionClosed,
            onPairRemoved,
            getCurrentPrice,
        )

    // Create a registry with all default tools
    registry := tradingtools.NewDefaultRegistry(ctx)

    // Get tools for use with an LLM framework (e.g., cogito)
    enabledTools := registry.GetEnabled([]string{"long", "short", "close_long", "close_short", "wait"})

    // Execute a tool
    tool, _ := registry.Get("long")
    result, err := tool.Execute(context.Background(), map[string]interface{}{
        "pair":        "BINANCE:BTCUSDT.P",
        "price":       100000.0,
        "risk_percent": 5.0,
        "stop_loss":   95000.0,
        "exit_price":  110000.0,
    })
}

Package Structure

tools-go/
├── go.mod                    # Module definition
├── README.md                 # This file
├── types.go                  # Core types (Position, Action, Side, etc.)
├── interfaces.go             # Interfaces (Wallet, State, Config, etc.)
├── tool.go                   # Tool interface and utilities
├── registry.go               # Tool registry
├── context.go                # Tool context with dependencies
├── exports.go                # Public API exports
├── helpers/                  # Helper functions
│   ├── format.go             # Price/Size/USD formatting
│   ├── sizing.go             # Position sizing calculations
│   ├── validate.go           # Validation helpers
│   ├── config.go             # Config helpers
│   ├── positions.go          # Position helpers
│   ├── orders.go             # Order execution helpers
│   ├── tpsl.go               # TP/SL helpers
│   ├── state.go              # State sync helpers
│   ├── persistence.go        # Persistence helpers
│   ├── lifecycle.go          # Position lifecycle hooks
│   └── parse.go              # Argument parsing
└── tools/                    # Tool implementations
    ├── registry.go           # Default tool factory
    ├── long.go               # Open long position
    ├── short.go              # Open short position
    ├── close_long.go         # Close long position
    ├── close_short.go        # Close short position
    ├── wait.go               # Wait/no-trade decision
    ├── add_pair.go           # Add trading pair
    ├── list_pairs.go         # List trading pairs
    ├── remove_pair.go        # Remove trading pair
    ├── adjust_stop_loss.go   # Adjust stop loss
    └── analyze.go            # Market analysis

Interfaces

Wallet

type Wallet interface {
    GetBalance(currency string) (float64, error)
    GetPosition(pair string) (*WalletPosition, error)
    GetAllPositions() map[string]*WalletPosition
    PlaceBuyOrder(ctx context.Context, pair string, amount, price float64) (string, error)
    PlaceSellOrder(ctx context.Context, pair string, amount, price float64) (string, error)
    PlaceBuyOrderWithTPSL(ctx context.Context, pair string, amount, price, sl, tp float64) (string, error)
    PlaceSellOrderWithTPSL(ctx context.Context, pair string, amount, price, sl, tp float64) (string, error)
}

State

type State interface {
    GetAgentName() string
    GetActivePositionsCopy() []Position
    SetActivePositions(positions []Position)
    SetPositionTPSL(pair string, stopLoss, takeProfit float64) error
    AddAction(action Action)
    AddActionWithPersistence(action Action, walletValue float64)
    GetPerformanceMetrics() PerformanceMetrics
    GetTradingPairs() []string
    SetTradingPairs(pairs []string)
    GetScalingState(pair string) *ScalingState
    CleanupScaling(pair string)
}

Config

type Config interface {
    GetName() string
    GetMaxLeverage() float64
    GetMaxMarginUsage() float64
    GetRiskPerTrade() float64
    GetRiskMode() string
    GetAllowManualSize() bool
    GetTimeWindow() string
    GetDefaultStopPercent() float64
    GetDefaultTargetRR() float64
    GetIntervals() []string
    GetToolPrompts() map[string]string
}

Available Tools

Tool Category Description
analyze_market analysis Analyze market conditions and technical indicators
add_pair pairs Add trading pair to watchlist
list_current_pairs pairs List all trading pairs
remove_pair pairs Remove trading pair (closes positions)
long perps Open leveraged long position
close_long perps Close long position
short perps Open leveraged short position
close_short perps Close short position
adjust_stop_loss risk_management Adjust stop loss on open position
wait strategy Wait for better market conditions

Position Sizing

The package supports two position sizing modes:

Equity Mode (Default)

Risk is calculated as a percentage of equity that would be lost if stop loss is hit:

// With 5% equity risk, $10,000 balance, entry $100, stop $95:
// Max loss = $500 (5% of $10,000)
// Position size = $500 / (5% price risk) = $10,000 notional = 100 units

Legacy Mode

Risk is calculated as a percentage of balance to allocate as margin:

// With 5% risk, $10,000 balance, 10x leverage:
// Margin = $500 (5% of $10,000)
// Position = $5,000 notional

Integration with agent-runtime

When migrating from agent-runtime/internal/tools, implement the interfaces using your existing types:

// Adapter for agent-runtime's storage.AgentState
type StateAdapter struct {
    state *storage.AgentState
}

func (s *StateAdapter) GetActivePositionsCopy() []tools.Position {
    positions := s.state.GetActivePositionsCopy()
    result := make([]tools.Position, len(positions))
    for i, p := range positions {
        result[i] = tools.Position{
            Pair:          p.Pair,
            Side:          p.Side,
            EntryPrice:    p.EntryPrice,
            CurrentPrice:  p.CurrentPrice,
            // ... map other fields
        }
    }
    return result
}

// ... implement other methods

License

MIT

About

A reusable trading tools framework for AI agent runtimes

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages