← back to kyawgyi13122-ship-it__launchpad

Function bodies 1,118 total

All specs Real LLM only Function bodies
renderResponseViewer function · go · L355-L425 (71 LOC)
cmd/tui/views.go
func renderResponseViewer(m Model) string {
	if m.currentResult == nil {
		return "No response data"
	}

	var b strings.Builder

	b.WriteString("TOP OF VIEW\n\n")

	result := m.currentResult

	// Title
	title := titleStyle.Render(fmt.Sprintf("📊 Response: %s", result.EndpointName))
	b.WriteString(title + "\n\n")

	// Status and timing
	statusBadge := renderStatusBadge(result.StatusCode, result.Status)
	timing := infoStyle.Render(fmt.Sprintf("Duration: %v", result.Duration))

	statusLine := lipgloss.JoinHorizontal(lipgloss.Left, statusBadge, "  ", timing)
	b.WriteString(statusLine + "\n\n")

	// Request Details Section
	requestSection := responseHeaderStyle.Render("📤 Request") + "\n"
	requestMethod := responseKeyStyle.Render(string(result.Method))
	requestURL := responseValueStyle.Render(result.RequestURL)
	requestSection += fmt.Sprintf("  %s %s\n", requestMethod, requestURL)

	// Request body (if any)
	if result.RequestBody != "" {
		requestSection += fmt.Sprintf("  %s\n", responseKeySt
renderHistory function · go · L428-L455 (28 LOC)
cmd/tui/views.go
func renderHistory(m Model) string {
	var b strings.Builder

	title := titleStyle.Render("📜 Request History")
	b.WriteString(title + "\n\n")

	if len(m.history) == 0 {
		b.WriteString(helpStyle.Render("No requests in history yet.") + "\n")
	} else {
		for i := len(m.history) - 1; i >= 0 && i > len(m.history)-10; i-- {
			result := m.history[i]
			statusBadge := renderStatusBadge(result.StatusCode, result.Status)
			timestamp := result.RequestTime.Format("15:04:05")
			line := fmt.Sprintf("%s  %s  %s %s",
				helpStyle.Render(timestamp),
				statusBadge,
				responseKeyStyle.Render(string(result.Method)),
				result.EndpointName,
			)
			b.WriteString(line + "\n")
		}
	}

	help := footerStyle.Render("esc/q: back")
	b.WriteString("\n" + help)

	return borderStyle.Render(b.String())
}
renderSettings function · go · L458-L471 (14 LOC)
cmd/tui/views.go
func renderSettings(m Model) string {
	var b strings.Builder

	title := titleStyle.Render("⚙️  Settings")
	b.WriteString(title + "\n\n")

	b.WriteString(inputLabelStyle.Render("Base URL:") + "\n")
	b.WriteString(m.baseURL + "\n\n")

	help := footerStyle.Render("esc/q: back")
	b.WriteString("\n" + help)

	return borderStyle.Render(b.String())
}
renderMakeScreen function · go · L474-L493 (20 LOC)
cmd/tui/views.go
func renderMakeScreen(m Model) string {
	// Fixed width for left panel (command list)
	leftWidth := 60
	rightWidth := m.width - leftWidth

	// Ensure minimum widths
	if leftWidth > m.width-20 {
		leftWidth = m.width / 2
		rightWidth = m.width - leftWidth
	}

	// Left panel: Make command list
	leftPanel := renderMakeCommandList(m, leftWidth)

	// Right panel: Command output
	rightPanel := renderMakeOutput(m, rightWidth)

	// Join horizontally
	return lipgloss.JoinHorizontal(lipgloss.Top, leftPanel, rightPanel)
}
renderMakeCommandList function · go · L496-L518 (23 LOC)
cmd/tui/views.go
func renderMakeCommandList(m Model, width int) string {
	// Command list
	listContent := m.makeCommandList.View()

	// Footer
	help := footerStyle.Render("j/k: navigate • enter: run • esc/q: back")

	// Calculate how many lines we need to fill to push help to bottom
	listHeight := lipgloss.Height(listContent)
	helpHeight := lipgloss.Height(help) + 2                  // +2 for spacing before help
	contentHeight := m.height - 3                            // minus top and bottom borders, and global status bar
	fillLines := contentHeight - listHeight - helpHeight + 1 // +1 to move help one row lower
	if fillLines < 0 {
		fillLines = 0
	}

	var b strings.Builder
	b.WriteString(listContent)
	b.WriteString(strings.Repeat("\n", fillLines))
	b.WriteString("\n\n" + help)

	return renderWithBorderTitleAndHeight(b.String(), "Make Commands", width, m.height-1)
}
renderMakeOutput function · go · L521-L544 (24 LOC)
cmd/tui/views.go
func renderMakeOutput(m Model, width int) string {
	var b strings.Builder

	if m.commandRunning {
		b.WriteString(infoStyle.Render("⏳ Running command...") + "\n\n")
	}

	if m.makeCommandOutput != "" {
		// Calculate viewport height
		viewportHeight := m.height - 8
		if viewportHeight < 5 {
			viewportHeight = 5
		}
		m.makeOutputViewport.Height = viewportHeight
		m.makeOutputViewport.SetContent(m.makeCommandOutput)
		b.WriteString(m.makeOutputViewport.View())
	} else if m.selectedMakeCommand.Name != "" {
		b.WriteString(helpStyle.Render("Press enter to run: make " + m.selectedMakeCommand.Name))
	} else {
		b.WriteString(helpStyle.Render("← Select a make command"))
	}

	return renderWithBorderTitleAndHeight(b.String(), "Output", width, m.height-1)
}
renderResponsePanel function · go · L547-L604 (58 LOC)
cmd/tui/views.go
func renderResponsePanel(m Model, width int, height int) string {
	var b strings.Builder

	if m.currentResult == nil {
		// No response yet
		emptyMsg := helpStyle.Render("No response yet - press enter to send request")
		b.WriteString(emptyMsg)
	} else {
		result := m.currentResult

		// Status, timing, and content type on one line
		statusBadge := renderStatusBadge(result.StatusCode, result.Status)
		timing := infoStyle.Render(fmt.Sprintf("Duration: %v", result.Duration))

		// Build status line with optional content type
		statusLineParts := []string{statusBadge, "  ", timing}
		if contentType, ok := result.Headers["Content-Type"]; ok && len(contentType) > 0 {
			contentTypeText := "  " + responseKeyStyle.Render("Content-Type: ") +
				responseValueStyle.Render(contentType[0])
			statusLineParts = append(statusLineParts, contentTypeText)
		}
		statusLine := lipgloss.JoinHorizontal(lipgloss.Left, statusLineParts...)
		b.WriteString(statusLine + "\n")

		// Request section (compact)
	
Source: Repobility analyzer · https://repobility.com
renderStatsModal function · go · L607-L683 (77 LOC)
cmd/tui/views.go
func renderStatsModal(m Model, bgContent string) string {
	// Modal dimensions
	modalWidth := 50

	// Modal content
	var content strings.Builder

	title := titleStyle.Render("📊 API Stats")
	content.WriteString(title + "\n\n")

	if m.statsLoading {
		content.WriteString(infoStyle.Render("⏳ Loading stats...") + "\n")
	} else {
		// Total counts from API
		templatesLine := lipgloss.JoinHorizontal(lipgloss.Left,
			responseKeyStyle.Render("Templates: "),
			responseValueStyle.Render(fmt.Sprintf("%d", m.templateCount)),
		)
		chainsLine := lipgloss.JoinHorizontal(lipgloss.Left,
			responseKeyStyle.Render("Chains: "),
			responseValueStyle.Render(fmt.Sprintf("%d", m.chainCount)),
		)
		content.WriteString(templatesLine + "\n")
		content.WriteString(chainsLine + "\n")

		// Cached data from background fetch
		content.WriteString("\n" + responseHeaderStyle.Render("Cached Data") + "\n")

		cachedChainsLine := lipgloss.JoinHorizontal(lipgloss.Left,
			responseKeyStyle.Render("Cached Chains: "),
renderGlobalHelp function · go · L686-L751 (66 LOC)
cmd/tui/views.go
func renderGlobalHelp(width int) string {
	// Create styled shortcuts
	f1Key := lipgloss.NewStyle().
		Foreground(lipgloss.Color("#7D56F4")).
		Bold(true).
		Render("(F1)")
	f1Label := lipgloss.NewStyle().
		Foreground(lipgloss.Color("#FAFAFA")).
		Render(" Endpoints")

	f2Key := lipgloss.NewStyle().
		Foreground(lipgloss.Color("#7D56F4")).
		Bold(true).
		Render("(F2)")
	f2Label := lipgloss.NewStyle().
		Foreground(lipgloss.Color("#FAFAFA")).
		Render(" Make")

	dKey := lipgloss.NewStyle().
		Foreground(lipgloss.Color("#7D56F4")).
		Bold(true).
		Render("(d)")
	dLabel := lipgloss.NewStyle().
		Foreground(lipgloss.Color("#FAFAFA")).
		Render(" Stats")

	qKey := lipgloss.NewStyle().
		Foreground(lipgloss.Color("#7D56F4")).
		Bold(true).
		Render("(q)")
	qLabel := lipgloss.NewStyle().
		Foreground(lipgloss.Color("#FAFAFA")).
		Render(" Quit")

	// Join left shortcuts with spacing
	shortcut1 := f1Key + f1Label
	shortcut2 := f2Key + f2Label
	leftShortcuts := lipgloss.JoinHorizontal(lipglos
formatHeaders function · go · L756-L774 (19 LOC)
cmd/tui/views.go
func formatHeaders(headers map[string][]string) string {
	var b strings.Builder
	importantHeaders := []string{"Content-Type", "Content-Length", "Date"}

	for _, key := range importantHeaders {
		if values, ok := headers[key]; ok {
			b.WriteString(fmt.Sprintf("  %s: %s\n",
				responseKeyStyle.Render(key),
				responseValueStyle.Render(strings.Join(values, ", ")),
			))
		}
	}

	if b.Len() == 0 {
		return "  " + responseValueStyle.Render("(none)")
	}

	return b.String()
}
truncateString function · go · L777-L782 (6 LOC)
cmd/tui/views.go
func truncateString(s string, maxLen int) string {
	if len(s) <= maxLen {
		return s
	}
	return s[:maxLen] + "..."
}
String method · go · L19-L34 (16 LOC)
cmd/volume-gen/algorithm_assignment.go
func (s AlgorithmStrategy) String() string {
	switch s {
	case StrategyBalanced:
		return "Balanced"
	case StrategyBullish:
		return "Bullish"
	case StrategyVolatile:
		return "Volatile"
	case StrategySteady:
		return "Steady"
	case StrategyOrganic:
		return "Organic"
	default:
		return "Unknown"
	}
}
DeterministicStrategyAssignment function · go · L127-L161 (35 LOC)
cmd/volume-gen/algorithm_assignment.go
func DeterministicStrategyAssignment(chainID uint64) AlgorithmStrategy {
	// Hash the chain ID
	h := fnv.New32a()
	h.Write([]byte{
		byte(chainID),
		byte(chainID >> 8),
		byte(chainID >> 16),
		byte(chainID >> 24),
		byte(chainID >> 32),
		byte(chainID >> 40),
		byte(chainID >> 48),
		byte(chainID >> 56),
	})
	hash := h.Sum32()

	// Distribute strategies:
	// 30% Organic (most realistic)
	// 25% Balanced
	// 20% Bullish
	// 15% Volatile
	// 10% Steady

	mod := hash % 100

	if mod < 30 {
		return StrategyOrganic
	} else if mod < 55 {
		return StrategyBalanced
	} else if mod < 75 {
		return StrategyBullish
	} else if mod < 90 {
		return StrategyVolatile
	}
	return StrategySteady
}
GetStrategyConfig function · go · L164-L170 (7 LOC)
cmd/volume-gen/algorithm_assignment.go
func GetStrategyConfig(strategy AlgorithmStrategy) StrategyConfig {
	config, exists := StrategyConfigs[strategy]
	if !exists {
		return StrategyConfigs[StrategyOrganic] // Default fallback
	}
	return config
}
ApplyStrategyToConfig function · go · L173-L193 (21 LOC)
cmd/volume-gen/algorithm_assignment.go
func ApplyStrategyToConfig(baseConfig Config, strategy AlgorithmStrategy) Config {
	strategyConfig := GetStrategyConfig(strategy)

	// Clone base config
	config := baseConfig

	// Apply strategy-specific settings
	config.MeanReversionConfig.Enabled = true
	config.MeanReversionConfig.Strength = strategyConfig.MeanReversionStrength
	config.MeanReversionConfig.OverboughtLevel = strategyConfig.OverboughtThreshold
	config.MeanReversionConfig.OversoldLevel = strategyConfig.OversoldThreshold

	config.EnableMarketPhases = strategyConfig.EnablePhases
	if strategyConfig.EnablePhases {
		config.PhaseDuration = strategyConfig.PhaseDuration
	}

	config.TimePatternConfig.BurstIntensity = strategyConfig.BurstIntensity

	return config
}
Repobility · code-quality intelligence platform · https://repobility.com
GetStrategyDescription function · go · L196-L199 (4 LOC)
cmd/volume-gen/algorithm_assignment.go
func GetStrategyDescription(strategy AlgorithmStrategy) string {
	config := GetStrategyConfig(strategy)
	return config.Description
}
Sample method · go · L17-L20 (4 LOC)
cmd/volume-gen/distributions.go
func (p *PowerLawDistribution) Sample() float64 {
	u := rand.Float64() // Uniform random [0, 1)
	return p.MinSize / math.Pow(u, 1.0/p.Alpha)
}
SampleCapped method · go · L23-L29 (7 LOC)
cmd/volume-gen/distributions.go
func (p *PowerLawDistribution) SampleCapped(maxSize float64) float64 {
	value := p.Sample()
	if value > maxSize {
		return maxSize
	}
	return value
}
GenerateTradeSize function · go · L32-L64 (33 LOC)
cmd/volume-gen/distributions.go
func GenerateTradeSize(archetype UserArchetype, rng *rand.Rand) float64 {
	var dist PowerLawDistribution
	var maxSize float64

	switch archetype {
	case ArchetypeWhale:
		// Whales: large trades, less extreme power law
		dist = PowerLawDistribution{MinSize: 50.0, Alpha: 1.2}
		maxSize = 500.0

	case ArchetypeDayTrader:
		// Day traders: medium trades, moderate distribution
		dist = PowerLawDistribution{MinSize: 10.0, Alpha: 1.5}
		maxSize = 100.0

	case ArchetypeHodler:
		// Hodlers: small-medium trades when they do trade
		dist = PowerLawDistribution{MinSize: 5.0, Alpha: 1.4}
		maxSize = 50.0

	case ArchetypeRetail:
		// Retail: mostly tiny trades, very skewed distribution
		dist = PowerLawDistribution{MinSize: 0.1, Alpha: 1.8}
		maxSize = 10.0

	default:
		// Default to retail distribution
		dist = PowerLawDistribution{MinSize: 0.1, Alpha: 1.5}
		maxSize = 100.0
	}

	return dist.SampleCapped(maxSize)
}
ExponentialWaitTime function · go · L68-L72 (5 LOC)
cmd/volume-gen/distributions.go
func ExponentialWaitTime(meanSeconds float64, rng *rand.Rand) float64 {
	// Exponential distribution: -ln(U) * mean
	u := rng.Float64()
	return -math.Log(u) * meanSeconds
}
PoissonCount function · go · L75-L87 (13 LOC)
cmd/volume-gen/distributions.go
func PoissonCount(lambda float64, rng *rand.Rand) int {
	// Knuth algorithm for Poisson random variable
	L := math.Exp(-lambda)
	k := 0
	p := 1.0

	for p > L {
		k++
		p *= rng.Float64()
	}

	return k - 1
}
LogNormalTradeSize function · go · L91-L99 (9 LOC)
cmd/volume-gen/distributions.go
func LogNormalTradeSize(median, sigma float64, rng *rand.Rand) float64 {
	// Box-Muller transform for normal distribution
	u1 := rng.Float64()
	u2 := rng.Float64()
	z := math.Sqrt(-2*math.Log(u1)) * math.Cos(2*math.Pi*u2)

	// Convert to log-normal
	return median * math.Exp(sigma*z)
}
Sample method · go · L109-L117 (9 LOC)
cmd/volume-gen/distributions.go
func (t *TriangularDistribution) Sample(rng *rand.Rand) float64 {
	u := rng.Float64()
	fc := (t.Mode - t.Min) / (t.Max - t.Min)

	if u < fc {
		return t.Min + math.Sqrt(u*(t.Max-t.Min)*(t.Mode-t.Min))
	}
	return t.Max - math.Sqrt((1-u)*(t.Max-t.Min)*(t.Max-t.Mode))
}
Repobility · MCP-ready · https://repobility.com
GenerateCluster function · go · L127-L148 (22 LOC)
cmd/volume-gen/distributions.go
func GenerateCluster(baseIntensity float64, rng *rand.Rand) VolumeCluster {
	// Number of trades in cluster follows Poisson
	numTrades := PoissonCount(baseIntensity, rng)
	if numTrades < 1 {
		numTrades = 1
	}

	// Within cluster, trades are more frequent
	avgWaitTime := 5.0 + rng.Float64()*15.0 // 5-20 seconds

	// Sometimes clusters have larger trades (volatility spikes)
	intensityBoost := 1.0
	if rng.Float64() < 0.2 { // 20% chance of volatile cluster
		intensityBoost = 1.5 + rng.Float64()*1.0 // 1.5x to 2.5x normal size
	}

	return VolumeCluster{
		NumTrades:      numTrades,
		AvgWaitTime:    avgWaitTime,
		IntensityBoost: intensityBoost,
	}
}
main function · go · L20-L189 (170 LOC)
cmd/volume-gen/main.go
func main() {
	// Parse command-line flags
	var (
		interval           = flag.Duration("interval", 30*time.Second, "How often to generate fake transactions")
		numUsers           = flag.Int("num-users", 10, "Number of fake users to create and rotate through")
		generateHistorical = flag.Bool("historical", false, "Generate one year of historical data (1,460 events, one every 6 hours) on startup for all active chains")
		showHelp           = flag.Bool("help", false, "Show usage information")

		// Market phase configuration
		enableMarketPhases = flag.Bool("market-phases", true, "Enable realistic market phases (accumulation, markup, distribution, markdown)")
		phaseDuration      = flag.Duration("phase-duration", 7*24*time.Hour, "Average duration of each market phase")

		// Mean reversion configuration
		enableMeanReversion   = flag.Bool("mean-reversion", true, "Enable mean reversion to maintain steady prices")
		meanReversionStrength = flag.Float64("mean-reversion-strength", 20.0, "How 
initLogger function · go · L192-L207 (16 LOC)
cmd/volume-gen/main.go
func initLogger(cfg *config.Config) *zap.Logger {
	var logger *zap.Logger
	var err error

	if cfg.Environment == "production" {
		logger, err = zap.NewProduction()
	} else {
		logger, err = zap.NewDevelopment()
	}

	if err != nil {
		panic(fmt.Sprintf("failed to initialize logger: %v", err))
	}

	return logger
}
String method · go · L19-L32 (14 LOC)
cmd/volume-gen/market_phases.go
func (mp MarketPhase) String() string {
	switch mp {
	case PhaseAccumulation:
		return "Accumulation"
	case PhaseMarkup:
		return "Markup"
	case PhaseDistribution:
		return "Distribution"
	case PhaseMarkdown:
		return "Markdown"
	default:
		return "Unknown"
	}
}
NewMarketCycleManager function · go · L119-L137 (19 LOC)
cmd/volume-gen/market_phases.go
func NewMarketCycleManager(chainID uint64, phaseDuration time.Duration, rng *rand.Rand) *MarketCycleManager {
	// Start in accumulation phase
	now := time.Now()

	initialPhase := PhaseAccumulation
	config := PhaseConfigs[initialPhase]

	// Add randomness to duration (±30%)
	actualDuration := time.Duration(float64(config.Duration) * (0.7 + rng.Float64()*0.6))

	return &MarketCycleManager{
		currentPhase:   initialPhase,
		phaseStartTime: now,
		phaseEndTime:   now.Add(actualDuration),
		chainID:        chainID,
		rng:            rng,
		phaseDuration:  phaseDuration,
	}
}
GetCurrentPhase method · go · L140-L142 (3 LOC)
cmd/volume-gen/market_phases.go
func (mcm *MarketCycleManager) GetCurrentPhase() MarketPhase {
	return mcm.currentPhase
}
GetPhaseCharacteristics method · go · L145-L147 (3 LOC)
cmd/volume-gen/market_phases.go
func (mcm *MarketCycleManager) GetPhaseCharacteristics() PhaseCharacteristics {
	return PhaseConfigs[mcm.currentPhase]
}
GetTimeInPhase method · go · L150-L152 (3 LOC)
cmd/volume-gen/market_phases.go
func (mcm *MarketCycleManager) GetTimeInPhase() time.Duration {
	return time.Since(mcm.phaseStartTime)
}
Repobility · severity-and-effort ranking · https://repobility.com
GetTimeRemainingInPhase method · go · L155-L161 (7 LOC)
cmd/volume-gen/market_phases.go
func (mcm *MarketCycleManager) GetTimeRemainingInPhase() time.Duration {
	remaining := mcm.phaseEndTime.Sub(time.Now())
	if remaining < 0 {
		return 0
	}
	return remaining
}
GetPhaseProgress method · go · L164-L177 (14 LOC)
cmd/volume-gen/market_phases.go
func (mcm *MarketCycleManager) GetPhaseProgress() float64 {
	totalDuration := mcm.phaseEndTime.Sub(mcm.phaseStartTime)
	elapsed := time.Since(mcm.phaseStartTime)

	if totalDuration <= 0 {
		return 1.0
	}

	progress := float64(elapsed) / float64(totalDuration)
	if progress > 1.0 {
		return 1.0
	}
	return progress
}
ShouldTransitionPhase method · go · L180-L182 (3 LOC)
cmd/volume-gen/market_phases.go
func (mcm *MarketCycleManager) ShouldTransitionPhase() bool {
	return time.Now().After(mcm.phaseEndTime)
}
TransitionToNextPhase method · go · L185-L207 (23 LOC)
cmd/volume-gen/market_phases.go
func (mcm *MarketCycleManager) TransitionToNextPhase() {
	currentConfig := PhaseConfigs[mcm.currentPhase]

	// Select next phase based on transition weights
	nextPhase := mcm.selectNextPhase(currentConfig.TransitionWeights)

	// Update phase
	mcm.currentPhase = nextPhase
	mcm.phaseStartTime = time.Now()

	// Calculate duration for new phase (with randomness)
	nextConfig := PhaseConfigs[nextPhase]
	baseDuration := nextConfig.Duration

	// If custom phase duration is set, use it
	if mcm.phaseDuration > 0 {
		baseDuration = mcm.phaseDuration
	}

	// Add ±30% randomness to duration
	actualDuration := time.Duration(float64(baseDuration) * (0.7 + mcm.rng.Float64()*0.6))
	mcm.phaseEndTime = mcm.phaseStartTime.Add(actualDuration)
}
selectNextPhase method · go · L210-L230 (21 LOC)
cmd/volume-gen/market_phases.go
func (mcm *MarketCycleManager) selectNextPhase(weights map[MarketPhase]float64) MarketPhase {
	// Calculate total weight
	totalWeight := 0.0
	for _, weight := range weights {
		totalWeight += weight
	}

	// Random selection
	r := mcm.rng.Float64() * totalWeight
	cumulative := 0.0

	for phase, weight := range weights {
		cumulative += weight
		if r <= cumulative {
			return phase
		}
	}

	// Fallback (shouldn't happen)
	return PhaseAccumulation
}
AdjustBuyProbability method · go · L233-L270 (38 LOC)
cmd/volume-gen/market_phases.go
func (mcm *MarketCycleManager) AdjustBuyProbability(baseProbability float64) float64 {
	config := PhaseConfigs[mcm.currentPhase]

	// Blend base probability with phase characteristics
	// 70% from phase, 30% from base
	adjusted := (config.BuyProbability * 0.7) + (baseProbability * 0.3)

	// Add phase progression influence
	progress := mcm.GetPhaseProgress()

	switch mcm.currentPhase {
	case PhaseAccumulation:
		// As accumulation progresses, more buying (preparing for markup)
		adjusted += progress * 0.05

	case PhaseMarkup:
		// As markup progresses, buying pressure increases (FOMO)
		adjusted += progress * 0.10

	case PhaseDistribution:
		// As distribution progresses, more selling (smart money exits)
		adjusted -= progress * 0.15

	case PhaseMarkdown:
		// As markdown progresses, selling pressure eases (capitulation)
		adjusted += progress * 0.08
	}

	// Clamp to reasonable range
	if adjusted < 0.1 {
		adjusted = 0.1
	}
	if adjusted > 0.9 {
		adjusted = 0.9
	}

	return adjusted
}
GetVolumeMultiplier method · go · L273-L300 (28 LOC)
cmd/volume-gen/market_phases.go
func (mcm *MarketCycleManager) GetVolumeMultiplier() float64 {
	config := PhaseConfigs[mcm.currentPhase]
	progress := mcm.GetPhaseProgress()

	baseMultiplier := config.VolumeMultiplier

	// Volume patterns within phases
	switch mcm.currentPhase {
	case PhaseAccumulation:
		// Volume gradually increases as accumulation completes
		return baseMultiplier * (1.0 + progress*0.3)

	case PhaseMarkup:
		// Volume peaks in middle of markup
		peakFactor := 1.0 - math.Abs(progress-0.5)*2.0 // Peaks at 50%
		return baseMultiplier * (1.0 + peakFactor*0.5)

	case PhaseDistribution:
		// High volume throughout, spikes near end
		return baseMultiplier * (1.0 + progress*0.3)

	case PhaseMarkdown:
		// Volume declines as markdown progresses
		return baseMultiplier * (1.0 - progress*0.3)
	}

	return baseMultiplier
}
GetTradeSizeBias method · go · L303-L306 (4 LOC)
cmd/volume-gen/market_phases.go
func (mcm *MarketCycleManager) GetTradeSizeBias() float64 {
	config := PhaseConfigs[mcm.currentPhase]
	return config.TradeSizeBias
}
Source: Repobility analyzer · https://repobility.com
GetVolatilityLevel method · go · L309-L335 (27 LOC)
cmd/volume-gen/market_phases.go
func (mcm *MarketCycleManager) GetVolatilityLevel() float64 {
	config := PhaseConfigs[mcm.currentPhase]
	progress := mcm.GetPhaseProgress()

	baseVolatility := config.VolatilityLevel

	// Volatility patterns
	switch mcm.currentPhase {
	case PhaseAccumulation:
		// Low volatility throughout
		return baseVolatility

	case PhaseMarkup:
		// Volatility increases as markup progresses
		return baseVolatility * (1.0 + progress*0.5)

	case PhaseDistribution:
		// High volatility with spikes
		return baseVolatility * (1.0 + mcm.rng.Float64()*0.3)

	case PhaseMarkdown:
		// Volatility spikes then calms
		return baseVolatility * (1.5 - progress*0.5)
	}

	return baseVolatility
}
GetPhaseStatus method · go · L349-L362 (14 LOC)
cmd/volume-gen/market_phases.go
func (mcm *MarketCycleManager) GetPhaseStatus(baseBuyProbability float64) PhaseStatus {
	config := PhaseConfigs[mcm.currentPhase]

	return PhaseStatus{
		Phase:            mcm.currentPhase.String(),
		Duration:         mcm.GetTimeInPhase(),
		TimeRemaining:    mcm.GetTimeRemainingInPhase(),
		Progress:         mcm.GetPhaseProgress(),
		BuyProbability:   mcm.AdjustBuyProbability(baseBuyProbability),
		VolumeMultiplier: mcm.GetVolumeMultiplier(),
		VolatilityLevel:  mcm.GetVolatilityLevel(),
		Description:      config.Description,
	}
}
ForcePhaseTransition method · go · L365-L377 (13 LOC)
cmd/volume-gen/market_phases.go
func (mcm *MarketCycleManager) ForcePhaseTransition(phase MarketPhase) {
	mcm.currentPhase = phase
	mcm.phaseStartTime = time.Now()

	config := PhaseConfigs[phase]
	baseDuration := config.Duration
	if mcm.phaseDuration > 0 {
		baseDuration = mcm.phaseDuration
	}

	actualDuration := time.Duration(float64(baseDuration) * (0.7 + mcm.rng.Float64()*0.6))
	mcm.phaseEndTime = mcm.phaseStartTime.Add(actualDuration)
}
DefaultMeanReversionConfig function · go · L18-L27 (10 LOC)
cmd/volume-gen/mean_reversion.go
func DefaultMeanReversionConfig() MeanReversionConfig {
	return MeanReversionConfig{
		Enabled:         true,
		Strength:        20.0, // Default strength
		SMAPeriod:       20,   // 20-period SMA
		OverboughtLevel: 0.15, // 15% above SMA
		OversoldLevel:   0.15, // 15% below SMA
		MaxAdjustment:   30.0, // Max 30% probability adjustment
	}
}
NewMeanReversionCalculator function · go · L35-L39 (5 LOC)
cmd/volume-gen/mean_reversion.go
func NewMeanReversionCalculator(config MeanReversionConfig) *MeanReversionCalculator {
	return &MeanReversionCalculator{
		config: config,
	}
}
CalculateBuyBias method · go · L44-L92 (49 LOC)
cmd/volume-gen/mean_reversion.go
func (mrc *MeanReversionCalculator) CalculateBuyBias(
	currentPrice float64,
	sma float64,
) float64 {
	if !mrc.config.Enabled || sma == 0 || currentPrice == 0 {
		return 0
	}

	// Calculate deviation from SMA
	deviation := (currentPrice - sma) / sma

	// No adjustment if within normal range
	if math.Abs(deviation) < 0.05 { // Within 5% of SMA
		return 0
	}

	// Calculate adjustment based on deviation and strength
	var adjustment float64

	if deviation > mrc.config.OverboughtLevel {
		// Price too high -> encourage selling (negative adjustment)
		excessDeviation := deviation - mrc.config.OverboughtLevel
		adjustment = -excessDeviation * mrc.config.Strength * 100

	} else if deviation < -mrc.config.OversoldLevel {
		// Price too low -> encourage buying (positive adjustment)
		excessDeviation := math.Abs(deviation) - mrc.config.OversoldLevel
		adjustment = excessDeviation * mrc.config.Strength * 100

	} else {
		// Gradual adjustment in the buffer zone
		if deviation > 0 {
			// Slightly
GetReversionStrength method · go · L95-L112 (18 LOC)
cmd/volume-gen/mean_reversion.go
func (mrc *MeanReversionCalculator) GetReversionStrength(
	currentPrice float64,
	sma float64,
) float64 {
	if sma == 0 || currentPrice == 0 {
		return 0
	}

	deviation := math.Abs((currentPrice - sma) / sma)

	// Normalize to 0-1 scale (30% deviation = 1.0)
	strength := deviation / 0.30
	if strength > 1.0 {
		strength = 1.0
	}

	return strength
}
ShouldReduceVolume method · go · L116-L127 (12 LOC)
cmd/volume-gen/mean_reversion.go
func (mrc *MeanReversionCalculator) ShouldReduceVolume(
	currentPrice float64,
	sma float64,
	threshold float64,
) bool {
	if !mrc.config.Enabled || sma == 0 {
		return false
	}

	deviation := math.Abs((currentPrice - sma) / sma)
	return deviation > threshold
}
Repobility · code-quality intelligence platform · https://repobility.com
GetMarketCondition method · go · L130-L153 (24 LOC)
cmd/volume-gen/mean_reversion.go
func (mrc *MeanReversionCalculator) GetMarketCondition(
	currentPrice float64,
	sma float64,
) string {
	if sma == 0 || currentPrice == 0 {
		return "unknown"
	}

	deviation := (currentPrice - sma) / sma

	if deviation > mrc.config.OverboughtLevel*2 {
		return "extremely_overbought"
	} else if deviation > mrc.config.OverboughtLevel {
		return "overbought"
	} else if deviation < -mrc.config.OversoldLevel*2 {
		return "extremely_oversold"
	} else if deviation < -mrc.config.OversoldLevel {
		return "oversold"
	} else if math.Abs(deviation) < 0.03 {
		return "at_mean"
	}

	return "normal"
}
CalculateVolatilityAdjustment method · go · L156-L171 (16 LOC)
cmd/volume-gen/mean_reversion.go
func (mrc *MeanReversionCalculator) CalculateVolatilityAdjustment(
	volatility float64,
) float64 {
	// High volatility -> reduce aggressive trades
	// Low volatility -> allow more aggressive trades

	if volatility > 5.0 { // Very volatile
		return 0.7 // Reduce trade sizes to 70%
	} else if volatility > 2.0 { // Moderately volatile
		return 0.85 // Reduce to 85%
	} else if volatility < 0.5 { // Very stable
		return 1.2 // Increase sizes by 20%
	}

	return 1.0 // Normal
}
CalculateBollingerBands function · go · L181-L211 (31 LOC)
cmd/volume-gen/mean_reversion.go
func CalculateBollingerBands(
	prices []PricePoint,
	period int,
	numStdDev float64,
) BollingerBands {
	if len(prices) < period {
		return BollingerBands{}
	}

	// Calculate SMA
	sum := 0.0
	startIdx := len(prices) - period
	for i := startIdx; i < len(prices); i++ {
		sum += prices[i].Price
	}
	sma := sum / float64(period)

	// Calculate standard deviation
	varianceSum := 0.0
	for i := startIdx; i < len(prices); i++ {
		diff := prices[i].Price - sma
		varianceSum += diff * diff
	}
	stdDev := math.Sqrt(varianceSum / float64(period))

	return BollingerBands{
		Upper:  sma + (numStdDev * stdDev),
		Middle: sma,
		Lower:  sma - (numStdDev * stdDev),
	}
}
‹ prevpage 2 / 23next ›