arb

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 15, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CalculateEffectivePrices

func CalculateEffectivePrices(bids, asks []PriceLevel, size float64) float64

CalculateEffectivePrices is a helper for more advanced depth calculation (Future use)

Types

type ArbitrageService

type ArbitrageService struct {
	// contains filtered or unexported fields
}

ArbitrageService coordinates monitoring and execution of prediction market arbitrage.

It monitors YES/NO token orderbooks via RTDS and detects opportunities where:

  • Long arb: Buy YES + Buy NO costs < 1 USDC (profit on merge)
  • Short arb: Sell YES + Sell NO revenue > 1 USDC (profit on pre-held tokens)

func NewArbitrageService

func NewArbitrageService(ctx context.Context, cfg Config, trading *trading.TradingService, ctfClient *ctf.CTFClient, rtds *rtds.RTDSClient, logger *zap.SugaredLogger) *ArbitrageService

NewArbitrageService creates a new service instance. The ctx parameter is the lifecycle context: when cancelled, all background goroutines will exit.

func (*ArbitrageService) CheckAndRebalance

func (s *ArbitrageService) CheckAndRebalance()

CheckAndRebalance checks if rebalance is needed and executes it

func (*ArbitrageService) CheckOpportunity

func (s *ArbitrageService) CheckOpportunity() *Opportunity

CheckOpportunity evaluates the current orderbook for arbitrage opportunities. It returns an opportunity if profitability exceeds the configured threshold.

func (*ArbitrageService) Execute

Execute handles the arbitrage opportunity

func (*ArbitrageService) Start

func (s *ArbitrageService) Start(market MarketConfig) error

Start begins monitoring the market for arbitrage opportunities.

func (*ArbitrageService) Stop

func (s *ArbitrageService) Stop()

Stop halts the service and waits for monitorLoop to fully exit. This prevents goroutine races when a new service is started on the same RTDS channel.

func (*ArbitrageService) UpdateBalance

func (s *ArbitrageService) UpdateBalance(ctx context.Context)

UpdateBalance fetches current USDC and token position balances from on-chain.

func (*ArbitrageService) WithRecorder

WithRecorder sets the optional orderbook CSV recorder.

type BalanceState

type BalanceState struct {
	USDC       float64
	YESTokens  float64
	NOTokens   float64
	LastUpdate time.Time
}

BalanceState tracks current portfolio state

type Config

type Config struct {
	// Trading Config
	MinProfitThreshold float64       `json:"minProfitThreshold"` // e.g. 0.005 for 0.5%
	MinTradeSizeSDK    float64       `json:"minTradeSize"`       // in USDC
	MaxTradeSizeSDK    float64       `json:"maxTradeSize"`       // in USDC
	MinTokenReserve    float64       `json:"minTokenReserve"`    // Min tokens to keep for short arb
	AutoExecute        bool          `json:"autoExecute"`
	ExecutionCooldown  time.Duration `json:"executionCooldown"`

	// Rebalancer Config
	EnableRebalancer   bool          `json:"enableRebalancer"`
	MinUSDCRatio       float64       `json:"minUsdcRatio"`    // e.g. 0.2
	MaxUSDCRatio       float64       `json:"maxUsdcRatio"`    // e.g. 0.8
	TargetUSDCRatio    float64       `json:"targetUsdcRatio"` // e.g. 0.5
	ImbalanceThreshold float64       `json:"imbalanceThreshold"`
	RebalanceInterval  time.Duration `json:"rebalanceInterval"`
	RebalanceCooldown  time.Duration `json:"rebalanceCooldown"`
	SizeSafetyFactor   float64       `json:"sizeSafetyFactor"` // e.g. 0.8
	AutoFixImbalance   bool          `json:"autoFixImbalance"`
}

Config holds service configuration

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns safe defaults

type EffectivePrices

type EffectivePrices struct {
	BuyYES   float64
	BuyNO    float64
	SellYES  float64
	SellNO   float64
	LongCost float64
	ShortRev float64
}

EffectivePrices holds calculated effective prices

type ExecutionResult

type ExecutionResult struct {
	Success       bool
	Type          OpportunityType
	Size          float64
	Profit        float64
	TxHashes      []string
	Error         error
	ExecutionTime time.Duration
}

ExecutionResult tracks the outcome of an arb execution

type MarketConfig

type MarketConfig struct {
	Name        string    `json:"name"`
	ConditionID string    `json:"conditionId"`
	YESTokenID  string    `json:"yesTokenId"`
	NOTokenID   string    `json:"noTokenId"`
	Outcomes    [2]string `json:"outcomes"` // ["YES", "NO"]
}

MarketConfig defines the market to monitor for arbitrage

type Opportunity

type Opportunity struct {
	Type            OpportunityType
	ProfitRate      float64
	ProfitPercent   float64
	EffectivePrices EffectivePrices

	MaxOrderbookSize float64
	MaxBalanceSize   float64
	RecommendedSize  float64
	EstimatedProfit  float64

	Description string
	Timestamp   time.Time
}

Opportunity represents a detected arbitrage chance

type OpportunityType

type OpportunityType string

OpportunityType defines the arb strategy

const (
	OpportunityLong  OpportunityType = "long"  // Buy YES + NO -> Merge
	OpportunityShort OpportunityType = "short" // Sell YES + NO (pre-held)
)

type OrderbookRecorder

type OrderbookRecorder struct {
	// contains filtered or unexported fields
}

OrderbookRecorder writes orderbook snapshots to CSV files for backtesting/review. Each market gets its own CSV file in the configured output directory.

func NewOrderbookRecorder

func NewOrderbookRecorder(dir string, logger *zap.SugaredLogger) *OrderbookRecorder

NewOrderbookRecorder creates a recorder that writes to the given directory.

func (*OrderbookRecorder) Record

func (r *OrderbookRecorder) Record(ob *OrderbookState)

Record writes a single orderbook snapshot to CSV.

func (*OrderbookRecorder) StartMarket

func (r *OrderbookRecorder) StartMarket(market string) error

StartMarket begins recording for a new market, creating a new CSV file.

func (*OrderbookRecorder) StopMarket

func (r *OrderbookRecorder) StopMarket()

StopMarket flushes and closes the current CSV file.

type OrderbookState

type OrderbookState struct {
	YESBids    []PriceLevel
	YESAsks    []PriceLevel
	NOBids     []PriceLevel
	NOAsks     []PriceLevel
	LastUpdate time.Time
}

OrderbookState tracks current orderbook

type PriceLevel

type PriceLevel struct {
	Price float64
	Size  float64
}

PriceLevel represents a single price level in the orderbook (internal)

type RebalanceAction

type RebalanceAction struct {
	Type     RebalanceActionType
	Amount   float64
	Reason   string
	Priority int
}

type RebalanceActionType

type RebalanceActionType string

RebalanceActionType defines action

const (
	ActionSplit   RebalanceActionType = "split"
	ActionMerge   RebalanceActionType = "merge"
	ActionSellYES RebalanceActionType = "sell_yes"
	ActionSellNO  RebalanceActionType = "sell_no"
	ActionNone    RebalanceActionType = "none"
)

type RebalanceResult

type RebalanceResult struct {
	Success bool
	Action  RebalanceAction
	TxHash  string
	Error   error
}

type Stats

type Stats struct {
	OpportunitiesDetected int64
	ExecutionsAttempted   int64
	ExecutionsSucceeded   int64
	TotalProfit           float64
	StartTime             time.Time
}

Stats holds runtime statistics

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL