store

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Overview

Package store keeps the settings and the data of xtrader in PostgreSQL: the users of the dashboard, the prompts, the agents with their accounts and language models, Telegram, and the orders, decisions and journal of each agent. Only the controller uses it, the agents going through its API.

The schema is the one of sql/migrations, applied by cmd/migrator, never by GORM: the store only checks its version (see CheckSchema). The secrets, the API keys and the tokens, are encrypted with the key of config.yml, each one sealed for its place (see seal).

Index

Constants

View Source
const (
	ParamUpdated   = "updated"   // its value changed
	ParamAdded     = "added"     // added, the agent without it
	ParamUnchanged = "unchanged" // the value it had already, nothing written
	ParamSkipped   = "skipped"   // left as it was, see ParamSet.Detail
	ParamRemoved   = "removed"   // removed, see RemoveAgentParams
)

The outcomes of SetAgentParam on an agent.

View Source
const (
	BacktestQueued          = "queued"
	BacktestRunning         = "running"
	BacktestSucceeded       = "succeeded"
	BacktestFailed          = "failed"
	BacktestCanceled        = "canceled"
	BacktestInterrupted     = "interrupted"
	BacktestBudgetExhausted = "budget_exhausted"
)

The statuses of a run of a backtest, see BacktestRun.

View Source
const (
	SegmentFit        = "fit"
	SegmentValidation = "validation"
)

The segments of the period of a batch a run trades, see BacktestRun.

View Source
const (
	GuardLimit      = "limit"      // a limit of the day reached: positions closed, entries blocked
	GuardIncomplete = "incomplete" // the result of the day unknown: entries blocked
	GuardMargin     = "margin"     // a guard of the margin (daily_margin_guards, see MarginGuard): entries blocked, nothing closed
)

The kinds of a daily guard, see DailyGuard.

View Source
const (
	TriggerLoss = "loss"
	TriggerGain = "gain"
)

The triggers of a daily guard of a limit.

View Source
const (
	GuardTripped  = "tripped"
	GuardReleased = "released"
)

The states of a daily guard.

View Source
const (
	FlattenRunning = "running"
	FlattenDone    = "done"
	FlattenPartial = "partial"
	FlattenFailed  = "failed"
)

The statuses of the close of the positions of a daily guard of a limit.

View Source
const (
	EventLimitChanged = "limit_changed"
	EventTripped      = "tripped"
	EventReleased     = "released"
	EventIncomplete   = "incomplete"
	EventFlatten      = "flatten"
	EventDayRollover  = "day_rollover"
)

The kinds of the events of the daily limits, see DailyLimitEvent.

View Source
const (
	ViaSystem   = "system"
	ViaSettings = "settings"
	ViaChat     = "chat"
)

Where a change of the daily limits came from, see DailyChange.

View Source
const (
	StopViaAgent  = "agent"  // the agent running moved it, see ui.SupervisionDailyStopsRequest
	StopViaBridge = "bridge" // the controller moved it on the bridge of the agent stopped
)

The ways a stop loss of the daily loss limits reaches the broker, see DailyStop.

View Source
const (
	MT5Created     = "created"
	MT5Changed     = "changed"
	MT5Activated   = "activated"
	MT5Deactivated = "deactivated"
	MT5Deleted     = "deleted"
	MT5Imported    = "imported"
	MT5Linked      = "linked"
	MT5Unlinked    = "unlinked"
	MT5Tested      = "tested"
	MT5Session     = "session"
)

The kinds of the events of the accounts of MT5, see MT5AccountEvent.

View Source
const (
	MT5KindDemo    = "demo"
	MT5KindReal    = "real"
	MT5KindContest = "contest"
)

The kinds of an account, as the bridge confirmed them (its trade_mode).

View Source
const (
	ArmRequested = "requested" // sent to the agent, its answer awaited
	ArmArmed     = "armed"     // waiting for its trigger
	ArmActive    = "active"    // applied
	ArmRefused   = "refused"   // not armed by the agent
	ArmEnded     = "ended"     // its position closed
)

The statuses of an arm of the protection of a position, see PositionProtection.

View Source
const (
	MoveConfirmed = "confirmed"
	MoveRejected  = "rejected"
	MoveUnknown   = "unknown"
)

The outcomes of the last move of an arm, see PositionProtection.

View Source
const (
	SupervisorMinInterval     = 300   // seconds between two analyses, at least
	SupervisorMaxInterval     = 86400 // and at most
	SupervisorMinTimeout      = 10    // seconds an answer of the model takes, at most, at least
	SupervisorMaxTimeout      = 600   // and at most
	SupervisorMaxInstructions = 20000 // characters of the instructions
	SupervisorMaxActions      = 10    // actions alone in an analysis, at most
)

The bounds of the settings of the supervisor, the ones of its table.

View Source
const (
	RunSchedule = "schedule"
	RunManual   = "manual"

	RunRunning = "running"
	RunOK      = "ok"
	RunFailed  = "failed"
	RunSkipped = "skipped"
)

The origins and the statuses of the analyses of the supervisor.

View Source
const (
	SourceSupervisor = "supervisor"
	SourceUser       = "user"

	ActionBlockEntries   = "block_entries"
	ActionAllowEntries   = "allow_entries"
	ActionStopAgent      = "stop_agent"
	ActionCancelPending  = "cancel_pending"
	ActionClosePositions = "close_positions"

	ModeWhenFlat = "when_flat"
	ModeNow      = "now"

	CategoryOperational = "operational"
	CategoryRisk        = "risk"
	CategoryPerformance = "performance"

	ActionProposed  = "proposed"
	ActionExecuting = "executing"
	ActionSucceeded = "succeeded"
	ActionPartial   = "partial"
	ActionFailed    = "failed"
	ActionUnknown   = "unknown"
	ActionRejected  = "rejected"
	ActionExpired   = "expired"
)

The sources, the actions, the modes, the categories and the statuses of the actions of the supervision.

View Source
const (
	RoleUser      = "user"
	RoleAssistant = "assistant"

	MessageQuestion = "question"
	MessageAnswer   = "answer"
	MessageProposal = "proposal"
	MessageResult   = "result"
	MessageError    = "error"
)

The roles and the kinds of the messages of the conversations with the supervisor.

View Source
const (
	StopNone        = "none"
	StopPendingFlat = "pending_flat"
	StopStopped     = "stopped"
)

The states of the stop of an agent by the supervisor.

View Source
const (
	HoursChanged   = "changed"    // the hours changed
	HoursClosed    = "closed"     // the window closed: the entries of the agents blocked
	HoursOpened    = "opened"     // the window opened: the entries free
	HoursReleased  = "released"   // the hours off: the entries free
	HoursEndAction = "end_action" // the positions closed or the pending orders canceled at the end
)

The kinds of the events of the trading hours, see TradingHoursEvent.

View Source
const DailyLimitMax = 1e9

DailyLimitMax bounds a daily limit, in its currency.

View Source
const ImportedBy = "importação"

ImportedBy is who the accounts imported from the bridges are created by.

View Source
const NoCurrency = "XXX"

NoCurrency is the ISO 4217 code of no currency, kept in the unused currency of the daily limits of all the agents, see DailyLimit.

View Source
const ProtectionMaxDistance = 50

ProtectionMaxDistance bounds every distance of the protection of the positions, in its unit (see ui.ProtectionUnitATR), as the database checks.

View Source
const RoleAdmin = "admin"

RoleAdmin is the system of the fixed role of the administrators: every permission of the dashboard, the ones added later too, never changed nor deleted (created by sql/seeds).

View Source
const SchemaVersion = 52

SchemaVersion is the version of sql/migrations the store needs.

Variables

View Source
var (
	// ErrNotFound is the error of a record that doesn't exist.
	ErrNotFound = errors.New("store: not found")
	// ErrConflict is the error of a record whose name is taken.
	ErrConflict = errors.New("store: already exists")
	// ErrInvalid is the error of a record refused, eg: a name out of the rules.
	ErrInvalid = errors.New("store: invalid")
	// ErrSchema is the error of a database without the schema of the store.
	ErrSchema = errors.New("store: schema out of date")
)
View Source
var ErrBacktestBusy = errors.New("store: the batch has runs queued or running")

ErrBacktestBusy is the error of a batch deleted while some of its runs are queued or running.

View Source
var ErrCredentials = errors.New("store: invalid username or password")

ErrCredentials is the error of a login refused: an unknown or disabled user, or a wrong password, told apart nowhere.

View Source
var ErrDecided = errors.New("store: the action was decided already")

ErrDecided is the error of a proposal confirmed or rejected again, eg: two clicks: the first one decides it.

View Source
var ErrExpired = errors.New("store: the proposal expired")

ErrExpired is the error of a proposal confirmed once it expired: the data it rested on is old.

Functions

func CheckParam

func CheckParam(name, value string) error

CheckParam checks the param name of value as the params of every agent are checked (see checkParams), the rules of the kind of an agent apart: the name of a flag, none of a field, the value a line of text.

func ColumnFlag

func ColumnFlag(name string) bool

ColumnFlag reports whether the flag name of an agent is one of its fields, of its account or of its language model, or of a file the database replaces, see columnFlags: never a param, eg: of an import (cmd/migrator).

func LLMParam

func LLMParam(name string) bool

LLMParam reports whether the flag name is one of the language model of an LLM agent, kept with it rather than with the params of the agent, see llmParamPrefixes.

Types

type Account

type Account struct {
	AgentID     int64     `gorm:"primaryKey;autoIncrement:false" json:"-"`
	Exchange    string    `json:"exchange"`
	BridgeURL   string    `gorm:"column:bridge_url" json:"bridge_url"`
	BridgeToken []byte    `json:"-"` // encrypted
	Magic       *int64    `json:"magic,omitempty"`
	Comment     *string   `json:"comment,omitempty"`
	RealAllowed bool      `json:"real_allowed"`
	CreatedAt   time.Time `json:"-"`
	UpdatedAt   time.Time `json:"-"`
}

Account is the trading account of an agent: the terminal of MT5 through its bridge, and what tells the orders of the agent apart there.

func (Account) TableName

func (Account) TableName() string

type AccountUpdate

type AccountUpdate struct {
	BridgeURL   *string
	Magic       *int64
	Comment     *string
	RealAllowed *bool
}

AccountUpdate is a change of the account of an agent, of the fields set: a Magic of 0 and an empty Comment remove them, their defaults applying (a hash of the comment, and the comment of the kind of the agent).

type Agent

type Agent struct {
	Model
	Name            string            `json:"name"`
	Kind            string            `json:"kind"`
	Enabled         bool              `json:"enabled"`
	Mode            string            `json:"mode"`
	APIAddress      string            `gorm:"column:api_address" json:"api_address"`
	Launched        bool              `json:"launched"`
	Restart         bool              `json:"restart"`
	TradePanel      bool              `json:"trade_panel"`
	TelegramControl bool              `json:"telegram_control"`
	Reanalysis      *AgentReanalysis  `gorm:"foreignKey:AgentID" json:"reanalysis,omitempty"`
	Params          Params            `gorm:"type:jsonb" json:"params"`
	Position        int               `json:"position"`
	OrderIDNext     int64             `gorm:"column:order_id_next" json:"-"`
	Account         *Account          `gorm:"foreignKey:AgentID" json:"account,omitempty"`
	MT5Link         *AgentMT5Account  `gorm:"foreignKey:AgentID" json:"mt5_link,omitempty"` // the account of MT5 it trades, see MT5AccountOf
	LLM             *LLMSettings      `gorm:"foreignKey:AgentID" json:"llm,omitempty"`
	Supervision     *AgentSupervision `gorm:"foreignKey:AgentID" json:"supervision,omitempty"`  // see SupervisionOf
	Protection      *AgentProtection  `gorm:"foreignKey:AgentID" json:"protection,omitempty"`   // see ProtectionOf
	DailyLimit      *AgentDailyLimit  `gorm:"foreignKey:AgentID" json:"daily_limit,omitempty"`  // see DailyLimitOf
	DailyStops      *DailyLimitStop   `gorm:"foreignKey:AgentID" json:"daily_stops,omitempty"`  // see DailyLimitOf
	DailyMargin     *DailyLimitMargin `gorm:"foreignKey:AgentID" json:"daily_margin,omitempty"` // see DailyLimitOf
	BotControl      *AgentBotControl  `gorm:"foreignKey:AgentID" json:"bot_control,omitempty"`  // see BotStopped
}

Agent is an agent of the controller, the bot of a binary of its Kind: its Params are its other settings by the name of their flag, only the ones set.

func (Agent) AllParams

func (a Agent) AllParams() Params

AllParams returns the params of the agent and of its language model, merged: the flags of its settings that no field holds, by name.

func (Agent) BotStopped

func (a Agent) BotStopped() (stopped bool, by string, at time.Time)

BotStopped reports whether a user stopped the bot of the agent a, and by whom and when: so it starts stopped (see AgentBotControl).

func (Agent) DailyLimitOf

func (a Agent) DailyLimitOf() ui.DailyLimitSettings

DailyLimitOf returns the daily limits of a, off without its row, with the switch of its stops at the broker (see DailyLimitStop).

func (Agent) MT5AccountOf

func (a Agent) MT5AccountOf() *MT5Account

MT5AccountOf returns the account of MT5 the agent a trades, as read, nil when it isn't linked to one (its own bridge then, see Account).

func (Agent) MT5Book

func (a Agent) MT5Book() agentapi.MT5Book

MT5Book returns what the agent a trades on MT5, as it computes it from its settings: its bridge, its magic number and its pairs, see agentapi.NewMT5Book.

func (Agent) ProtectionOf

func (a Agent) ProtectionOf() ui.ProtectionSettings

ProtectionOf returns the protection of the positions of a, all off without its row, see ui.ProtectionSettings.

func (Agent) ReanalysisAllowed

func (a Agent) ReanalysisAllowed() bool

ReanalysisAllowed reports whether the language model of the agent a may be asked again between its closes, see AgentReanalysis: of an LLM agent only.

func (Agent) SupervisionOf

func (a Agent) SupervisionOf() AgentSupervision

SupervisionOf returns the supervision of the agent a, the one of an agent never supervised when it has none.

type AgentBotControl

type AgentBotControl struct {
	AgentID   int64     `gorm:"primaryKey;autoIncrement:false" json:"-"`
	Stopped   bool      `json:"stopped"`
	ChangedBy string    `json:"changed_by"`
	ChangedAt time.Time `json:"changed_at"`
}

AgentBotControl is the bot of an agent stopped by a user, from the dashboard (Parar bot) or from Telegram (/stop): kept so that the agent starts with its bot stopped again, whatever restarts its process, until a user starts it (Iniciar bot, /start). ChangedBy and ChangedAt tell the last change.

func (AgentBotControl) TableName

func (AgentBotControl) TableName() string

type AgentDailyLimit

type AgentDailyLimit struct {
	AgentID   int64     `gorm:"primaryKey;autoIncrement:false" json:"agent_id"`
	Enabled   bool      `json:"enabled"`
	MaxLoss   *float64  `json:"max_loss,omitempty"`
	MaxGain   *float64  `json:"max_gain,omitempty"`
	UpdatedBy string    `json:"updated_by"`
	UpdatedAt time.Time `json:"updated_at"`
}

AgentDailyLimit is the daily limits of an agent, in the currency of its account, see ui.DailyLimitSettings: a row once set, none without limits.

func (AgentDailyLimit) Settings

func (l AgentDailyLimit) Settings() ui.DailyLimitSettings

Settings returns the limits as the dashboard takes them.

func (AgentDailyLimit) TableName

func (AgentDailyLimit) TableName() string

type AgentMT5Account

type AgentMT5Account struct {
	AgentID   int64       `gorm:"primaryKey;autoIncrement:false" json:"-"`
	AccountID int64       `json:"account_id"`
	Account   *MT5Account `gorm:"foreignKey:AccountID" json:"-"`
	UpdatedBy string      `json:"updated_by"`
	UpdatedAt time.Time   `json:"updated_at"`
}

AgentMT5Account is the account of MT5 an agent trades (agent_mt5_accounts), the bridge and its token of it, see Agent.MT5Link.

func (AgentMT5Account) TableName

func (AgentMT5Account) TableName() string

type AgentProtection

type AgentProtection struct {
	AgentID             int64     `gorm:"primaryKey" json:"agent_id"`
	Unit                string    `json:"unit"`
	BreakevenEnabled    bool      `json:"breakeven_enabled"`
	BreakevenSupervisor bool      `json:"breakeven_supervisor"`
	BreakevenTrigger    float64   `json:"breakeven_trigger"`
	BreakevenMargin     float64   `json:"breakeven_margin"`
	TrailingEnabled     bool      `json:"trailing_enabled"`
	TrailingSupervisor  bool      `json:"trailing_supervisor"`
	TrailingTrigger     float64   `json:"trailing_trigger"`
	TrailingDistance    float64   `json:"trailing_distance"`
	TrailingStep        float64   `json:"trailing_step"`
	UpdatedBy           string    `json:"updated_by"`
	UpdatedAt           time.Time `json:"updated_at"`
}

AgentProtection is the protection of the open positions of an agent, see ui.ProtectionSettings: a row once set, none for an agent without one.

func (AgentProtection) Settings

func (p AgentProtection) Settings() ui.ProtectionSettings

Settings returns the protection as the agents and the dashboard take it.

func (AgentProtection) TableName

func (AgentProtection) TableName() string

type AgentReanalysis

type AgentReanalysis struct {
	AgentID int64 `gorm:"primaryKey;autoIncrement:false" json:"-"`
	Allowed bool  `json:"allowed"`
}

AgentReanalysis is the switch of the reanalysis of an LLM agent, "Permitir reanálise" on the dashboard: whether its language model may be asked again between its closes, from the dashboard or from Telegram (its controls on there), whatever its trade panel. A table of its own, the one of the agents not altered, a row for each LLM agent: an agent without one may not be asked, as the ones of the other kinds, without a language model.

func (AgentReanalysis) TableName

func (AgentReanalysis) TableName() string

type AgentSecretValues

type AgentSecretValues struct {
	LLMAPIKey   string
	BridgeToken string
}

AgentSecretValues are the secrets of an agent, decrypted: "" for none.

type AgentSecrets

type AgentSecrets struct {
	LLMAPIKey   Secret
	BridgeToken Secret
}

AgentSecrets are the secrets of an agent to write, of the ones set, see Secret: the key of its language model and the token of the bridge of its account. The token of the MCP server of the calendar is the one of the news of all the agents, see NewsSettings.

type AgentSupervision

type AgentSupervision struct {
	AgentID         int64      `gorm:"primaryKey;autoIncrement:false" json:"-"`
	EntriesBlocked  bool       `json:"entries_blocked"`
	EntriesRevision int64      `json:"entries_revision"`
	EntriesReason   string     `json:"entries_reason"`
	EntriesBy       string     `json:"entries_by"`
	EntriesActionID *int64     `json:"entries_action_id,omitempty"`
	EntriesAt       *time.Time `json:"entries_at,omitempty"`
	StopState       string     `json:"stop_state"`
	StopReason      string     `json:"stop_reason"`
	StopCategory    *string    `json:"stop_category,omitempty"`
	StopBy          string     `json:"stop_by"`
	StopActionID    *int64     `json:"stop_action_id,omitempty"`
	StopAt          *time.Time `json:"stop_at,omitempty"`
	UpdatedAt       time.Time  `json:"updated_at"`
}

AgentSupervision is the supervision of an agent: its entries blocked, why, by whom and by which action, at a revision growing with every change (see agentapi.Entries), and its stop by the supervisor.

func (AgentSupervision) TableName

func (AgentSupervision) TableName() string

type AgentUpdate

type AgentUpdate struct {
	Enabled         *bool
	TradePanel      *bool
	TelegramControl *bool
	Reanalysis      *bool
	Mode            *string
	APIAddress      *string
	Launched        *bool
	Restart         *bool
	Params          Params
	Account         *AccountUpdate
	LLM             *LLMUpdate
}

AgentUpdate is a change of an agent, of the fields set: its name and its kind never change, the name naming its outbox and its routes on the dashboard. Reanalysis switches the reanalysis of an LLM agent (see AgentReanalysis): on refused for another kind, off nothing for it. Params, when not nil, replace the params of the agent and of its language model, merged (see Agent.AllParams). Account and LLM change its account and its language model, created when it has none.

type AssetAgents

type AssetAgents struct {
	ID        int16           `gorm:"primaryKey;autoIncrement:false"`
	Rules     json.RawMessage `gorm:"type:jsonb"`
	Revision  int64
	UpdatedBy string
	UpdatedAt time.Time
}

AssetAgents are the agents allowed on assets, of all the agents, a single record, see ui.AssetAgentsSettings: none while never set (every agent on every asset). Revision grows with every change, see Revised.

func (AssetAgents) AgentsOf

func (a AssetAgents) AgentsOf(pair string) ([]string, bool)

AgentsOf returns the agents of the rule of pair, false without a rule.

func (AssetAgents) Allowed

func (a AssetAgents) Allowed(name string, pairs []string) (allowed, excluded []string)

Allowed returns the pairs of pairs the agent of name may open positions on by the rules, in their order, and the others (excluded): a pair of a rule not naming it.

func (AssetAgents) Settings

func (a AssetAgents) Settings() ui.AssetAgentsSettings

Settings returns the rules as the dashboard takes them.

func (AssetAgents) TableName

func (AssetAgents) TableName() string

type Attachment

type Attachment struct {
	MediaType string
	Data      []byte
}

Attachment is a file of a decision to keep, eg: an image the model answered with.

type Autonomy

type Autonomy struct {
	BlockEntries     bool `json:"block_entries"`
	StopWhenFlat     bool `json:"stop_when_flat"`
	CancelPending    bool `json:"cancel_pending"`
	MaxActionsPerRun int  `json:"max_actions_per_run"`
}

Autonomy is what the supervisor of the agents does alone, in its periodic analyses: block the entries of an agent, stop it once it holds nothing, cancel its pending entries, MaxActionsPerRun actions an analysis at most; the rest it proposes to the users. Closing positions is never one of them.

func (*Autonomy) Scan

func (a *Autonomy) Scan(src interface{}) error

Scan reads the autonomy of its JSON object.

func (Autonomy) Value

func (a Autonomy) Value() (driver.Value, error)

Value writes the autonomy as a JSON object.

type BacktestBatch

type BacktestBatch struct {
	ID              int64           `json:"id"`
	Name            string          `json:"name"`
	From            time.Time       `json:"from"`
	To              time.Time       `json:"to"`
	ValidationShare float64         `json:"validation_share"`
	Assumptions     json.RawMessage `json:"assumptions"`
	CreatedBy       string          `json:"created_by"`
	CreatedAt       time.Time       `json:"created_at"`
}

BacktestBatch is a batch of backtests asked on the dashboard: its period (From until before To), the share of it kept for the validation, its assumptions, who asked and when. See backtest_batches.

type BacktestRun

type BacktestRun struct {
	ID         int64           `json:"id"`
	BatchID    int64           `json:"batch_id"`
	Agent      string          `json:"agent"`
	Kind       string          `json:"kind"`
	Segment    string          `json:"segment"`
	From       time.Time       `json:"from"`
	To         time.Time       `json:"to"`
	Status     string          `json:"status"`
	Processed  int64           `json:"processed"`
	Total      int64           `json:"total"`
	Error      string          `json:"error"`
	Config     json.RawMessage `json:"config"`
	Summary    json.RawMessage `json:"summary,omitempty"`
	Result     json.RawMessage `json:"result,omitempty"`
	CreatedAt  time.Time       `json:"created_at"`
	StartedAt  *time.Time      `json:"started_at,omitempty"`
	FinishedAt *time.Time      `json:"finished_at,omitempty"`
}

BacktestRun is a run of a batch: an agent on a segment of the period, its status, progress and error, the config it ran with (copied), its summary and its result. See backtest_runs.

func (BacktestRun) Final

func (r BacktestRun) Final() bool

Final reports whether the run ended, whatever its outcome.

type DailyChange

type DailyChange struct {
	Day    string
	Via    string
	By     string
	UserID *int64
	Reason string
}

DailyChange is who changes the daily limits and why, for their record: the day of the change (eg: 2026-10-29, of the zone of the limits), through where (see ViaSettings), by whom, the user if one.

type DailyGuard

type DailyGuard struct {
	ID              int64      `gorm:"primaryKey" json:"id"`
	Day             time.Time  `gorm:"type:date" json:"day"`
	AgentID         *int64     `json:"agent_id,omitempty"`
	Kind            string     `json:"kind"`
	Trigger         *string    `json:"trigger,omitempty"`
	State           string     `json:"state"`
	Result          float64    `json:"result"`
	LimitAmount     float64    `json:"limit_amount"`
	Currency        string     `json:"currency"`
	Reason          string     `json:"reason"`
	Trips           int        `json:"trips"`
	TrippedAt       time.Time  `json:"tripped_at"`
	ReleasedAt      *time.Time `json:"released_at,omitempty"`
	ReleasedBy      string     `json:"released_by"`
	ReleaseReason   string     `json:"release_reason"`
	FlattenStatus   string     `json:"flatten_status"`
	FlattenActionID *int64     `json:"flatten_action_id,omitempty"`
	FlattenAttempts int        `json:"flatten_attempts"`
	UpdatedAt       time.Time  `json:"updated_at"`
}

DailyGuard is a daily guard (daily_guards): a limit of Day reached (Kind GuardLimit, Trigger loss or gain, Result and LimitAmount in Currency) or the result of the day unknown (GuardIncomplete), of an agent or of all the agents (AgentID nil); tripped, the entries of its agents are blocked until it is released; the close of its positions (FlattenStatus).

func (DailyGuard) DayOf

func (g DailyGuard) DayOf() string

DayOf returns the day of the guard, eg: 2026-10-29.

func (DailyGuard) Info

func (g DailyGuard) Info() ui.DailyGuardInfo

Info returns the guard as the dashboard takes it.

func (DailyGuard) TableName

func (DailyGuard) TableName() string

func (DailyGuard) TriggerOf

func (g DailyGuard) TriggerOf() string

TriggerOf returns the trigger of the guard, empty for none.

type DailyLimit

type DailyLimit struct {
	ID        int16     `gorm:"primaryKey;autoIncrement:false" json:"-"`
	Enabled   bool      `json:"enabled"`
	Currency  string    `json:"currency"`
	MaxLoss   *float64  `json:"max_loss,omitempty"`
	MaxGain   *float64  `json:"max_gain,omitempty"`
	UpdatedBy string    `json:"updated_by"`
	UpdatedAt time.Time `json:"updated_at"`
	// Stops is whether its loss limit moves the stop losses at the broker, of
	// daily_limit_stops (see DailyLimitStop): nil while never set, on
	Stops *bool `gorm:"-" json:"broker_stops,omitempty"`
	// Margin is the least margin of its loss limit for new entries, in percent,
	// of daily_limit_margins (see DailyLimitMargin): nil while never set
	Margin *float64 `gorm:"-" json:"min_margin_pct,omitempty"`
}

DailyLimit is the daily limits of all the agents together, a single record, see ui.DailyLimitSettings: none while never set (no limit). Its amounts apply to the result of the agents in each currency of their accounts apart, none converted: Currency is unused, NoCurrency once set (the column, of migration 27, needs one while enabled).

func (DailyLimit) Settings

func (l DailyLimit) Settings() ui.DailyLimitSettings

Settings returns the limits as the dashboard takes them, without a currency: they apply in the one of each account.

func (DailyLimit) TableName

func (DailyLimit) TableName() string

type DailyLimitEvent

type DailyLimitEvent struct {
	ID          int64           `gorm:"primaryKey" json:"id"`
	At          time.Time       `gorm:"default:now()" json:"at"`
	Day         string          `gorm:"type:date" json:"day"`
	AgentID     *int64          `json:"agent_id,omitempty"`
	GuardID     *int64          `json:"guard_id,omitempty"`
	Kind        string          `json:"kind"`
	Via         string          `json:"via"`
	RequestedBy string          `json:"requested_by"`
	UserID      *int64          `json:"user_id,omitempty"`
	Reason      string          `json:"reason"`
	Previous    json.RawMessage `gorm:"type:jsonb" json:"previous,omitempty"`
	Next        json.RawMessage `gorm:"type:jsonb" json:"next,omitempty"`
	Metric      json.RawMessage `gorm:"type:jsonb" json:"metric,omitempty"`
	ActionID    *int64          `json:"action_id,omitempty"`
}

DailyLimitEvent is a record of the daily limits (daily_limit_events): a limit changed (Previous and Next settings), a guard tripped or released, the positions closed (ActionID); Metric the result of the day then; of an agent or of all the agents (AgentID nil). Its ID is the revision of the entries of the agents it concerns.

func (DailyLimitEvent) TableName

func (DailyLimitEvent) TableName() string

type DailyLimitMargin

type DailyLimitMargin struct {
	ID           int64     `gorm:"primaryKey" json:"-"`
	AgentID      *int64    `json:"agent_id,omitempty"`
	MinMarginPct float64   `json:"min_margin_pct"`
	UpdatedBy    string    `json:"updated_by"`
	UpdatedAt    time.Time `json:"updated_at"`
}

DailyLimitMargin is the least margin of the loss limit of all the agents (AgentID nil) or of an agent for new entries (daily_limit_margins), in percent of the loss limit, see ui.DailyLimitSettings.MinMarginPct: a row once changed, ui.DefaultMinMarginPct without one.

func (DailyLimitMargin) TableName

func (DailyLimitMargin) TableName() string

type DailyLimitStop

type DailyLimitStop struct {
	ID        int64     `gorm:"primaryKey" json:"-"`
	AgentID   *int64    `json:"agent_id,omitempty"`
	Enabled   bool      `json:"enabled"`
	UpdatedBy string    `json:"updated_by"`
	UpdatedAt time.Time `json:"updated_at"`
}

DailyLimitStop is the switch of the stops at the broker of the loss limit of all the agents (AgentID nil) or of an agent (daily_limit_stops), see ui.DailyLimitSettings.BrokerStops: a row once changed, on without one.

func (DailyLimitStop) TableName

func (DailyLimitStop) TableName() string

type DailyStop

type DailyStop struct {
	ID        int64           `gorm:"primaryKey" json:"id"`
	Day       time.Time       `gorm:"type:date" json:"day"`
	AgentID   int64           `json:"agent_id"`
	Account   string          `json:"account"`
	Pair      string          `json:"pair"`
	Side      string          `json:"side"`
	Tickets   json.RawMessage `gorm:"type:jsonb" json:"tickets"`
	Scope     string          `json:"scope"`
	Currency  string          `json:"currency"`
	Level     float64         `json:"level"`
	Via       string          `json:"via"`
	Move      string          `json:"move"`
	Previous  float64         `json:"previous"`
	Requested float64         `json:"requested"`
	Confirmed float64         `json:"confirmed"`
	Detail    string          `json:"detail"`
	Budget    json.RawMessage `gorm:"type:jsonb" json:"budget"`
	Attempts  int             `json:"attempts"`
	CreatedAt time.Time       `json:"created_at"`
	UpdatedAt time.Time       `json:"updated_at"`
	EndedAt   *time.Time      `json:"ended_at,omitempty"`
}

DailyStop is a stop loss the daily loss limits ask of an open position (daily_stops): the position of an agent on Pair of an account (its tickets moving together under one stop), on Side, a day; the level within the loss left of the limit of Scope (empty for all the agents) in Currency, the loss left and the share of the position then (Budget); its last move at the broker (see ui.DailyStopConfirmed): the stop before, the one asked, the one confirmed, why it wasn't moved, through the agent or the bridge; Attempts, the moves sent; ended once its position closed, its limit turned off or its day over.

func (DailyStop) BudgetOf

func (d DailyStop) BudgetOf() DailyStopBudget

BudgetOf returns the budget of the stop, zero when unreadable.

func (DailyStop) DayOf

func (d DailyStop) DayOf() string

DayOf returns the day of the stop, eg: 2026-11-16.

func (DailyStop) Info

func (d DailyStop) Info(name string) ui.DailyStopInfo

Info returns the stop as the dashboard takes it, its agent named name.

func (DailyStop) Request

func (d DailyStop) Request() ui.DailyStop

Request returns the stop as its agent takes it, see ui.DailyStop.

func (DailyStop) TableName

func (DailyStop) TableName() string

func (DailyStop) TicketsOf

func (d DailyStop) TicketsOf() []int64

TicketsOf returns the tickets of the stop.

type DailyStopBudget

type DailyStopBudget struct {
	Limit    float64  `json:"limit"`
	Realized float64  `json:"realized"`
	Open     float64  `json:"open"`
	Costs    float64  `json:"costs"`
	Headroom float64  `json:"headroom"`
	Share    float64  `json:"share"`
	Risk     *float64 `json:"risk,omitempty"`
}

DailyStopBudget is the loss left of the limit of a stop and the share of its position, in the currency of the stop: the limit, the result of the day of its scope (realized and open), the exit costs set aside, the loss left (Headroom) and the share of the position of it; the loss to its stop before (Risk, absent for none).

type DailyStopMove

type DailyStopMove struct {
	Via       string // see StopViaAgent
	Move      string // see ui.DailyStopConfirmed
	Previous  float64
	Requested float64
	Confirmed float64
	Detail    string
	Sent      bool // sent to the broker, counted in Attempts
}

DailyStopMove is a move of a stop loss of the daily loss limits at the broker, see SetDailyStopMove.

type DailyStopTarget

type DailyStopTarget struct {
	Day      string // eg: 2026-11-16, of the zone of the limits
	AgentID  int64
	Account  string
	Pair     string
	Side     string // BUY or SELL
	Tickets  []int64
	Scope    string
	Currency string
	Level    float64
	Budget   DailyStopBudget
}

DailyStopTarget is a stop loss the daily loss limits ask now, see SetDailyStop.

type ExposureLimits

type ExposureLimits struct {
	ID        int16           `gorm:"primaryKey;autoIncrement:false"`
	Pairs     json.RawMessage `gorm:"type:jsonb"`
	UpdatedBy string
	UpdatedAt time.Time
}

ExposureLimits is the exposure limit of all the agents, a single record, see ui.ExposureSettings: none while never set (off). Its rules are its pairs; the column max_agents of the table, a limit of every asset of its first version, is never read nor written (left at 0).

func (ExposureLimits) LimitOf

func (e ExposureLimits) LimitOf(pair string) int

LimitOf returns the most agents that may hold pair in a direction at once, by its rule, 0 for none (no rule).

func (ExposureLimits) On

func (e ExposureLimits) On() bool

On reports whether the limit applies to some asset: a rule at least.

func (ExposureLimits) Settings

func (e ExposureLimits) Settings() ui.ExposureSettings

Settings returns the limit as the dashboard takes it.

func (ExposureLimits) TableName

func (ExposureLimits) TableName() string

type GuardTrip

type GuardTrip struct {
	Day      string
	AgentID  *int64
	Kind     string
	Trigger  string
	Result   float64
	Limit    float64
	Currency string
	Reason   string
	Metric   any
}

GuardTrip is a daily guard to trip, see TripDailyGuard: its day, scope (AgentID, nil for all the agents), kind and trigger; the result and the limit in Currency, why, and the result of the day (Metric) for the record.

type JournalEntry

type JournalEntry struct {
	ID          string             `json:"id"`
	At          time.Time          `json:"at"`
	Pair        string             `json:"pair"`
	Trigger     string             `json:"trigger,omitempty"`
	RequestedBy string             `json:"requested_by,omitempty"`
	Model       string             `json:"model"`
	Prompt      *ui.DecisionPrompt `json:"prompt,omitempty"`
	LatencyMS   int64              `json:"latency_ms"`
	Input       json.RawMessage    `json:"input"`
	Decision    json.RawMessage    `json:"decision,omitempty"`
	Error       string             `json:"error,omitempty"`
}

JournalEntry is a call to the model of an LLM agent with its whole context: Input and Decision are the JSON the agent sent, its ID the one of the decision kept of it.

type LLMSettings

type LLMSettings struct {
	AgentID         int64         `gorm:"primaryKey;autoIncrement:false" json:"-"`
	Provider        string        `json:"provider"`
	Model           string        `json:"model"`
	APIKey          []byte        `gorm:"column:api_key" json:"-"` // encrypted
	BaseURL         *string       `gorm:"column:base_url" json:"base_url,omitempty"`
	ReasoningEffort *string       `json:"reasoning_effort,omitempty"`
	MaxTokens       *int          `json:"max_tokens,omitempty"`
	PromptID        *int64        `json:"prompt_id,omitempty"`
	PromptStatus    *PromptStatus `gorm:"type:jsonb" json:"prompt_status,omitempty"`
	Params          Params        `gorm:"type:jsonb" json:"params"`
	CreatedAt       time.Time     `json:"-"`
	UpdatedAt       time.Time     `json:"-"`
}

LLMSettings are the language model of an LLM agent: its Params are its other settings by the name of their flag, eg: llm-min-stop-atr.

func (LLMSettings) TableName

func (LLMSettings) TableName() string

type LLMUpdate

type LLMUpdate struct {
	Provider        *string
	Model           *string
	BaseURL         *string
	ReasoningEffort *string
	MaxTokens       *int
}

LLMUpdate is a change of the language model of an LLM agent, of the fields set: an empty BaseURL or ReasoningEffort and a MaxTokens of 0 remove them, the defaults of the agent applying.

type ListQuery

type ListQuery struct {
	Page   pagination.Page
	Search string
}

ListQuery is a list the dashboard asks for: a page of it (Page.Number 0 for all of it, as before the pages), of the rows matching Search (see searchScope), in the order of the list.

func (ListQuery) Paged

func (q ListQuery) Paged() bool

Paged reports whether q asks for a page of the list.

type Listed

type Listed[T any] struct {
	Rows  []T
	Page  pagination.Page
	Total int64
}

Listed is a page of a list: its rows, the page they are (the last one for a page past it; the whole list as one page when not paged), and the rows of the list matching its search (Total).

type MT5Account

type MT5Account struct {
	ID          int64      `gorm:"primaryKey" json:"id"`
	Name        string     `json:"name"`
	Login       int64      `json:"login"`
	Server      string     `json:"server"`
	Password    []byte     `json:"-"` // encrypted
	BridgeURL   string     `gorm:"column:bridge_url" json:"bridge_url"`
	BridgeKey   string     `gorm:"column:bridge_key" json:"-"`
	BridgeToken []byte     `json:"-"` // encrypted
	AllowReal   bool       `json:"allow_real"`
	ReadOnly    bool       `json:"read_only"`
	Active      bool       `json:"active"`
	Kind        string     `json:"kind"`
	Currency    string     `json:"currency"`
	Company     string     `json:"company"`
	CheckedAt   *time.Time `json:"checked_at,omitempty"`
	CheckError  string     `json:"check_error"`
	UpdatedBy   string     `json:"updated_by"`
	CreatedAt   time.Time  `json:"created_at"`
	UpdatedAt   time.Time  `json:"updated_at"`
}

MT5Account is an account of MetaTrader 5 (mt5_accounts): its login, its server and its password, encrypted, sent to the terminal; the terminal serving it, through its bridge (BridgeURL, BridgeToken encrypted); whether the bridge may trade it real (AllowReal) or trade at all (ReadOnly), and whether it is the account of its terminal (Active); what the bridge confirmed of it (Kind, Currency, Company, CheckedAt, CheckError).

func (MT5Account) TableName

func (MT5Account) TableName() string

type MT5AccountEvent

type MT5AccountEvent struct {
	ID          int64           `gorm:"primaryKey" json:"id"`
	At          time.Time       `json:"at"`
	AccountID   *int64          `json:"account_id,omitempty"`
	AgentID     *int64          `json:"agent_id,omitempty"`
	Kind        string          `json:"kind"`
	RequestedBy string          `json:"requested_by"`
	UserID      *int64          `json:"user_id,omitempty"`
	Reason      string          `json:"reason"`
	Previous    json.RawMessage `gorm:"type:jsonb" json:"previous,omitempty"`
	Next        json.RawMessage `gorm:"type:jsonb" json:"next,omitempty"`
}

MT5AccountEvent is an event of the accounts of MT5 (mt5_account_events), never holding a secret.

func (MT5AccountEvent) TableName

func (MT5AccountEvent) TableName() string

type MT5AccountInput

type MT5AccountInput struct {
	Name        *string
	Login       *int64
	Server      *string
	BridgeURL   *string
	AllowReal   *bool
	ReadOnly    *bool
	Password    Secret
	BridgeToken Secret
}

MT5AccountInput is an account of MT5 to create, or the change of one, of the fields set: the secrets as Secret (nil keeps, "" removes).

type MT5Change

type MT5Change struct {
	By     string
	UserID *int64
	Reason string
}

MT5Change is who changes the accounts of MT5 and why, for their events.

type MarginGuard

type MarginGuard struct {
	ID            int64      `gorm:"primaryKey" json:"id"`
	Day           time.Time  `gorm:"type:date" json:"day"`
	AgentID       *int64     `json:"agent_id,omitempty"`
	State         string     `json:"state"`
	Margin        float64    `json:"margin"`
	Least         float64    `json:"least"`
	Result        float64    `json:"result"`
	Currency      string     `json:"currency"`
	Reason        string     `json:"reason"`
	Trips         int        `json:"trips"`
	TrippedAt     time.Time  `json:"tripped_at"`
	ReleasedAt    *time.Time `json:"released_at,omitempty"`
	ReleaseReason string     `json:"release_reason"`
	UpdatedAt     time.Time  `json:"updated_at"`
}

MarginGuard is a guard of the margin of a daily loss limit (daily_margin_guards): the loss left to the limit below its least for new entries (see ui.DailyLimitSettings.MinMargin), of all the agents (AgentID nil) or of an agent, a day; tripped, the entries of its agents are blocked, nothing closed, until it is released; the margin, its least and the result of the day then, in Currency; why. Its trips and releases are recorded as events of the daily limits (guard_id NULL, the guard in their metric).

func (MarginGuard) Guard

func (g MarginGuard) Guard() DailyGuard

Guard returns the guard of the margin as a daily guard of kind GuardMargin, for the code weighing the guards of the scopes together (its ID of the guards of the margin, never of daily_guards).

func (MarginGuard) TableName

func (MarginGuard) TableName() string

type MarginTrip

type MarginTrip struct {
	Day      string
	AgentID  *int64
	Margin   float64
	Least    float64
	Result   float64
	Currency string
	Reason   string
	Metric   any
}

MarginTrip is a guard of the margin to trip, see TripMarginGuard: its day, scope (AgentID, nil for all the agents), the margin, its least and the result in Currency, why, and the result of the day (Metric) for the record.

type Model

type Model struct {
	ID        int64          `gorm:"primaryKey" json:"id"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `json:"-"`
}

Model is the ID and the timestamps of the records deleted softly: deleted, they stay in their table out of every query, their unique names free again.

type NewsMigration

type NewsMigration struct {
	// Tokens is how many agents held one.
	Tokens int
	// Taken tells the token of the news was set from theirs, all the same.
	Taken bool
	// Conflict names the agents of a conflict: different tokens, or one
	// that can't be opened, none chosen.
	Conflict []string
}

NewsMigration is how the former tokens of the calendar of the agents were carried to the news, see MigrateNewsToken.

type NewsRules

type NewsRules struct {
	ID              int16     `gorm:"primaryKey;autoIncrement:false" json:"-"`
	MCPURL          *string   `gorm:"column:mcp_url" json:"mcp_url,omitempty"`
	BlockBefore     int       `gorm:"column:block_before_minutes" json:"block_before"`
	BlockAfter      int       `gorm:"column:block_after_minutes" json:"block_after"`
	BlockImportance string    `json:"block_importance"`
	UpdatedBy       string    `json:"updated_by"`
	UpdatedAt       time.Time `json:"updated_at"`
}

NewsRules are the rules of the news of all the agents, a single record set on the dashboard with NewsSettings: the address of the MCP server of the calendar, and the window of the news block in minutes (BlockBefore before a release of at least BlockImportance to BlockAfter after it, both 0 for none). UpdatedBy is who changed them last, empty for the seeds.

func (NewsRules) TableName

func (NewsRules) TableName() string

type NewsSettings

type NewsSettings struct {
	ID        int16     `gorm:"primaryKey;autoIncrement:false" json:"-"`
	Enabled   bool      `json:"enabled"`
	MCPToken  []byte    `gorm:"column:mcp_token" json:"-"` // encrypted
	UpdatedBy string    `json:"updated_by"`
	UpdatedAt time.Time `json:"updated_at"`
}

NewsSettings are the news of the agents, a single record set on the dashboard: the feature on or off for all the agents, and the token of the MCP server of the economic calendar (its address in NewsRules), shared by every agent, encrypted, never answered.

func (NewsSettings) TableName

func (NewsSettings) TableName() string

type NewsURLMigration

type NewsURLMigration struct {
	// URLs is how many agents had a server.
	URLs int
	// Taken is the address of the news set from theirs, all the same.
	Taken string
	// Conflict names the agents of different servers, none chosen.
	Conflict []string
	// Params is how many agents had params of the window, removed.
	Params int
}

NewsURLMigration is how the former servers of the calendar of the LLM agents and their windows of the news block were carried to the news, see MigrateNewsURL.

type NewsUpdate

type NewsUpdate struct {
	Enabled         *bool
	Token           Secret
	URL             *string
	BlockBefore     *int
	BlockAfter      *int
	BlockImportance *string
	By              string
}

NewsUpdate is a change of the news, of the fields set: Token is a Secret (nil keeps the one kept); URL the address of the MCP server ("" removes it), the window in minutes and its importance (see NewsRules); By is who changes them.

type ParamChange

type ParamChange struct {
	Name, Value string
}

ParamChange is a param to set on an agent, see SetAgentParams.

type ParamSet

type ParamSet struct {
	Status string
	Had    string
	Detail string
}

ParamSet is what SetAgentParam did on an agent: its outcome (see ParamUpdated and the others), the value it had (Had, when it had the param), and why it was left (Detail, when skipped).

type Params

type Params map[string]string

Params are settings by name, a JSON object of strings.

func (*Params) Scan

func (p *Params) Scan(src interface{}) error

Scan reads the params of a JSON object.

func (Params) Value

func (p Params) Value() (driver.Value, error)

Value writes the params as a JSON object, {} when nil.

type Period

type Period struct {
	ID        int64     `gorm:"primaryKey" json:"id"`
	AgentID   int64     `json:"agent_id"`
	StartedAt time.Time `json:"started_at"`
	Deposit   float64   `json:"deposit"`
	Currency  string    `json:"currency"`
	CreatedBy string    `json:"created_by"`
	CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
}

Period is an accounting period of an agent: the cards of the dashboard (trades, win rate, net profit, profit factor) count the trades closed from StartedAt, until the next period started; Deposit, in Currency, is the balance it started with, and CreatedBy the user who started it. The orders are never touched: a period only tells which of their results count. See StartPeriod.

func (Period) TableName

func (Period) TableName() string

type PositionProtection

type PositionProtection struct {
	ID          int64           `gorm:"primaryKey" json:"id"`
	AgentID     int64           `json:"agent_id"`
	RunID       *int64          `json:"run_id,omitempty"`
	UserID      *int64          `json:"user_id,omitempty"`
	Pair        string          `json:"pair"`
	PositionRef string          `json:"position_ref"`
	Ticket      int64           `json:"ticket"`
	Side        string          `json:"side"`
	Feature     string          `json:"feature"`
	Reason      string          `json:"reason"`
	Category    *string         `json:"category,omitempty"`
	Evidence    json.RawMessage `gorm:"type:jsonb" json:"evidence"`
	RequestedBy string          `json:"requested_by"`
	Status      string          `json:"status"`
	Move        string          `json:"move"`
	Previous    float64         `json:"previous"`
	Requested   float64         `json:"requested"`
	Confirmed   float64         `json:"confirmed"`
	Detail      string          `json:"detail"`
	CreatedAt   time.Time       `json:"created_at"`
	UpdatedAt   time.Time       `json:"updated_at"`
	EndedAt     *time.Time      `json:"ended_at,omitempty"`
}

PositionProtection is a protection the XTrader AI armed on an open position of an agent (position_protections): the breakeven or the trailing stop of the position PositionRef of Pair, asked by the analysis RunID or by the user UserID confirming a proposal, for Reason resting on Evidence (a JSON array); its status (see ArmRequested) and its last move of the stop loss (Move, see MoveConfirmed): Previous, Requested and Confirmed, 0 for none.

func (PositionProtection) Arm

Arm returns the arm as the agents take it.

func (PositionProtection) TableName

func (PositionProtection) TableName() string

type Prompt

type Prompt struct {
	Model
	Name        string `json:"name"`
	Description string `json:"description"`
	Content     string `json:"content"`
	Version     int    `json:"version"`
}

Prompt is a prompt of the LLM agents, the strategy the model trades.

type PromptEdit

type PromptEdit struct {
	Description *string
	Content     *string
	Version     int
}

PromptEdit is an edit of a prompt, of the fields set: Version, when set, is the version the edit was made on, refused when it changed since (ErrConflict).

type PromptStatus

type PromptStatus struct {
	PromptID int64     `json:"prompt_id,omitempty"`
	Name     string    `json:"name"`
	Version  int       `json:"version"`
	Applied  bool      `json:"applied"`
	Error    string    `json:"error,omitempty"`
	At       time.Time `json:"at"`
}

PromptStatus is the last prompt an agent was asked to switch to, and how it went: applied, or refused with Error, the previous one kept.

func (*PromptStatus) Scan

func (s *PromptStatus) Scan(src interface{}) error

Scan reads the status of its JSON.

func (*PromptStatus) Value

func (s *PromptStatus) Value() (driver.Value, error)

Value writes the status as JSON, NULL when nil.

type PromptSummary

type PromptSummary struct {
	Prompt
	UsedBy []string `gorm:"-" json:"used_by"`
}

PromptSummary is a prompt without its content, with the agents using it.

type PromptVersion

type PromptVersion struct {
	PromptID  int64     `gorm:"primaryKey;autoIncrement:false" json:"prompt_id"`
	Version   int       `gorm:"primaryKey;autoIncrement:false" json:"version"`
	Content   string    `json:"content"`
	CreatedBy string    `json:"created_by"`
	CreatedAt time.Time `json:"created_at"`
}

PromptVersion is a version of a prompt, the content an edit left: kept for good, the decisions pointing at it (append-only, without DeletedAt).

type ProtectionMove

type ProtectionMove struct {
	Move      string
	Previous  float64
	Requested float64
	Confirmed float64
	Detail    string
}

ProtectionMove is a move of the stop loss an arm made, see PositionProtection.

type Remembered

type Remembered struct {
	Pair       string    `json:"pair"`
	Candle     time.Time `json:"candle"`
	At         time.Time `json:"at"`
	Action     string    `json:"action"`
	Confidence float64   `json:"confidence"`
	Reason     string    `json:"reason"`
}

Remembered is a decision of the journal of an LLM agent for the memory of its prompt: the candle it was taken on, when (the time of its entry), and its answer.

type Role

type Role struct {
	ID          int64            `gorm:"primaryKey" json:"id"`
	Name        string           `json:"name"`
	Description string           `json:"description"`
	System      string           `json:"system"`
	UpdatedBy   string           `json:"updated_by"`
	CreatedAt   time.Time        `json:"created_at"`
	UpdatedAt   time.Time        `json:"updated_at"`
	Permissions []RolePermission `gorm:"foreignKey:RoleID" json:"permissions"`
	Users       int64            `gorm:"-" json:"users"`
}

Role is a role of the users of the dashboard: the permissions it grants (see Granted), Users the number of users holding it (filled by Roles).

func (Role) Effective

func (r Role) Effective() []string

Effective returns what r lets its users see and do, the implied permissions included, see ui.Effective.

func (Role) Fixed

func (r Role) Fixed() bool

Fixed reports whether r is the fixed role of the administrators.

func (Role) Granted

func (r Role) Granted() []string

Granted returns the permissions r grants as set, in the order of the catalog: every one for the fixed role; a permission gone from the catalog dropped.

type RoleChange

type RoleChange struct {
	Name        *string
	Description *string
	Permissions *[]string
	By          string
}

RoleChange is a role created or changed, of the fields set, by By.

type RolePermission

type RolePermission struct {
	RoleID     int64  `gorm:"primaryKey;autoIncrement:false"`
	Permission string `gorm:"primaryKey"`
}

RolePermission is a permission a role grants, see ui.PermissionAreas.

type Secret

type Secret = *string

Secret is a secret to write, see SetAgentSecrets and SetTelegram: nil keeps the one kept, a pointer to "" removes it, any other value replaces it.

type Store

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

Store is the database of xtrader.

func Open

func Open(cfg config.Database, key []byte) (*Store, error)

Open connects to the database of cfg, the secrets encrypted with key.

func (*Store) ActionIDsOfRuns

func (s *Store) ActionIDsOfRuns(ctx context.Context, runIDs []int64) (map[int64][]int64, error)

ActionIDsOfRuns returns the actions the analyses of runIDs asked for, by analysis, the oldest first.

func (*Store) ActivateMT5Account

func (s *Store) ActivateMT5Account(ctx context.Context, id int64, active bool,
	change MT5Change) (deactivated []MT5Account, err error)

ActivateMT5Account makes the account of MT5 of id the one of its terminal (active), the one of it before, if any, deactivated; or deactivates it. Recorded; the accounts deactivated returned.

func (*Store) AddSupervisorMessage

func (s *Store) AddSupervisorMessage(ctx context.Context, m SupervisorMessage) (SupervisorMessage, error)

AddSupervisorMessage records the message m of its user.

func (*Store) AddTelegramUser

func (s *Store) AddTelegramUser(ctx context.Context, telegramID int64, name string) (TelegramUser, error)

AddTelegramUser authorizes the Telegram user of telegramID, named name.

func (*Store) AdminRole

func (s *Store) AdminRole(ctx context.Context) (Role, error)

AdminRole returns the fixed role of the administrators, created by the seeds.

func (*Store) Agent

func (s *Store) Agent(ctx context.Context, id int64) (Agent, error)

Agent returns the agent of id.

func (*Store) AgentByName

func (s *Store) AgentByName(ctx context.Context, name string) (Agent, error)

AgentByName returns the agent of name.

func (*Store) AgentSecrets

func (s *Store) AgentSecrets(ctx context.Context, id int64) (AgentSecretValues, error)

AgentSecrets returns the secrets of the agent of id, decrypted: only for the agent itself, see the internal API of the controller.

func (*Store) Agents

func (s *Store) Agents(ctx context.Context) ([]Agent, error)

Agents returns the agents with their accounts and language models, in the order of the dashboard.

func (*Store) AppendJournal

func (s *Store) AppendJournal(ctx context.Context, id int64, entries []JournalEntry) error

AppendJournal appends the entries of the journal of the agent of id, the ones kept already left as they are.

func (*Store) ArmProtection

func (s *Store) ArmProtection(ctx context.Context, a PositionProtection) (PositionProtection, error)

ArmProtection records the arm a, requested: ErrConflict when one is in force already on its position and feature, ErrInvalid for one out of the rules.

func (*Store) AssetAgents

func (s *Store) AssetAgents(ctx context.Context) (AssetAgents, bool, error)

AssetAgents returns the agents allowed on assets, false while never set.

func (*Store) Authenticate

func (s *Store) Authenticate(ctx context.Context, username, password string) (User, error)

Authenticate returns the enabled user of username whose password is password, with its role (see User), else ErrCredentials, and keeps the time of the login.

func (*Store) BacktestBatch

func (s *Store) BacktestBatch(ctx context.Context, id int64) (BacktestBatch, error)

BacktestBatch returns the batch of id, ErrNotFound without one.

func (*Store) BacktestBatchChoices

func (s *Store) BacktestBatchChoices(ctx context.Context) ([]BacktestBatch, error)

BacktestBatchChoices returns every batch, the newest first, with its ID, its name and its period only.

func (*Store) BacktestBatches

func (s *Store) BacktestBatches(ctx context.Context, limit int) ([]BacktestBatch, error)

BacktestBatches returns the last limit batches, the newest first.

func (*Store) BacktestRun

func (s *Store) BacktestRun(ctx context.Context, id int64) (BacktestRun, error)

BacktestRun returns the run of id with its result, ErrNotFound without one.

func (*Store) BacktestRuns

func (s *Store) BacktestRuns(ctx context.Context, ids []int64, withResult bool) ([]BacktestRun, error)

BacktestRuns returns the runs of the batches of ids, by batch and ID, their result left out unless withResult.

func (*Store) Bootstrap

func (s *Store) Bootstrap(ctx context.Context, username, password string) (bool, error)

Bootstrap creates the first user, username with password, when the database has none, the fixed role of the administrators given to it, and reports whether it did.

func (*Store) CancelQueuedBacktestRun

func (s *Store) CancelQueuedBacktestRun(ctx context.Context, id int64) (bool, error)

CancelQueuedBacktestRun cancels the run of id while queued, false when it isn't (running, or ended).

func (*Store) CheckSchema

func (s *Store) CheckSchema(ctx context.Context) error

CheckSchema fails unless the migrations applied to the database are SchemaVersion at least, and none of them stopped halfway (dirty): the controller never migrates, cmd/migrator does.

func (*Store) ClaimBacktestRun

func (s *Store) ClaimBacktestRun(ctx context.Context) (BacktestRun, bool, error)

ClaimBacktestRun takes the oldest run queued, running from now, false without one; a run is claimed once whatever the controllers.

func (*Store) ClaimSupervisorAction

func (s *Store) ClaimSupervisorAction(ctx context.Context, id int64, by string) (SupervisorAction, error)

ClaimSupervisorAction takes the proposal of id to execute, confirmed by by, at once and once: executing, the others (another click, another user) getting ErrDecided; a proposal expired is marked so, ErrExpired.

func (*Store) ClearAgentStop

func (s *Store) ClearAgentStop(ctx context.Context, id int64, by string) (bool, error)

ClearAgentStop clears the stop of the agent of id by the supervisor, as a user enables it again, and allows its entries again when they were blocked by that stop (a block of its own stays): true when they were.

func (*Store) Close

func (s *Store) Close() error

Close closes the connections to the database.

func (*Store) CountActiveBacktestRuns

func (s *Store) CountActiveBacktestRuns(ctx context.Context) (int64, error)

CountActiveBacktestRuns returns the runs queued or running, of every batch.

func (*Store) CountUsers

func (s *Store) CountUsers(ctx context.Context) (int64, error)

CountUsers returns the number of users, the disabled ones included.

func (*Store) CreateAgent

func (s *Store) CreateAgent(ctx context.Context, agent Agent, secrets AgentSecrets) (Agent, error)

CreateAgent creates an agent with its account and language model, if any, their secrets encrypted: checked (see checkAgent), its API at an address no other agent has and, trading, positions no other agent trading trades (ErrConflict otherwise, see checkBookFree), its params given merged or apart (see Agent.AllParams), its prompt one of the database, not deleted, nor meanwhile (see sharePrompt). An agent without a position, 0, goes after the others on the dashboard. An LLM agent gets the switch of its reanalysis, off without its Reanalysis (see AgentReanalysis), one of another kind none.

func (*Store) CreateBacktestBatch

func (s *Store) CreateBacktestBatch(ctx context.Context, batch BacktestBatch, runs []BacktestRun) (BacktestBatch,
	[]BacktestRun, error)

CreateBacktestBatch records batch and its runs, queued, at once.

func (*Store) CreateMT5Account

func (s *Store) CreateMT5Account(ctx context.Context, in MT5AccountInput, active bool, kind string,
	change MT5Change) (MT5Account, error)

CreateMT5Account creates the account of MT5 of in, its name, login, server and bridge required, inactive unless active (then the account of its terminal, ErrConflict when another one is), recorded.

func (*Store) CreatePrompt

func (s *Store) CreatePrompt(ctx context.Context, name, description, content, by string) (Prompt, error)

CreatePrompt creates a prompt, its first version by who, eg: web:xtrader.

func (*Store) CreateRole

func (s *Store) CreateRole(ctx context.Context, change RoleChange) (Role, error)

CreateRole creates a role, of the name, the description and the permissions of change, by change.By.

func (*Store) CreateSupervisorAction

func (s *Store) CreateSupervisorAction(ctx context.Context, a SupervisorAction) (SupervisorAction, error)

CreateSupervisorAction records the action a, its ID and its time set.

func (*Store) CreateUser

func (s *Store) CreateUser(ctx context.Context, username, password string) (User, error)

CreateUser creates an enabled user of the dashboard.

func (*Store) CurrentPeriods

func (s *Store) CurrentPeriods(ctx context.Context) (map[string]Period, error)

CurrentPeriods returns the current period of the agents with one, by the name of the agent.

func (*Store) DailyEntries

func (s *Store) DailyEntries(ctx context.Context, id int64) (blocked bool, reason string, revision int64,
	err error)

DailyEntries returns whether the entries of the agent of id are blocked by a daily guard tripped, its own or the one of all the agents, of any day (only the end of its day releases one), why, and the revision of the daily limits it concerns (the last of their events), which only grows.

func (*Store) DailyLimitEvents

func (s *Store) DailyLimitEvents(ctx context.Context, limit int) ([]DailyLimitEvent, error)

DailyLimitEvents returns the last limit records of the daily limits, the newest first.

func (*Store) DailyStopsInForce

func (s *Store) DailyStopsInForce(ctx context.Context, id int64) ([]DailyStop, error)

DailyStopsInForce returns the stop losses of the daily loss limits in force, of the agent of id (all of them for 0), by agent, asset and account.

func (*Store) Decision

func (s *Store) Decision(ctx context.Context, id int64, decisionID string) (ui.Decision, error)

Decision returns the decision of the agent of id of decisionID.

func (*Store) DecisionAttachment

func (s *Store) DecisionAttachment(ctx context.Context, id int64, decisionID string, number int) (string, []byte,
	error)

DecisionAttachment returns the attachment number of the decision decisionID of the agent of id: its media type and its content.

func (s *Store) DecisionLinks(ctx context.Context, id int64) (map[int64]string, error)

DecisionLinks returns the decision that placed each order of the agent of id, by the ID of the order.

func (*Store) Decisions

func (s *Store) Decisions(ctx context.Context, id int64, pair string, limit int) ([]ui.Decision, error)

Decisions returns the last decisions of the agent of id, of pair when set, limit at most, newest first.

func (*Store) DecisionsPerPair

func (s *Store) DecisionsPerPair(ctx context.Context, id int64, perPair int) ([]ui.Decision, error)

DecisionsPerPair returns the last perPair decisions of each pair of the agent of id, newest first.

func (*Store) DeleteAgent

func (s *Store) DeleteAgent(ctx context.Context, id int64) error

DeleteAgent deletes the agent of id, softly: it stays in its table out of every query, with its account and its language model, their secrets removed, and with its orders, its decisions and its journal; a new agent may take its name. An agent enabled isn't deleted (ErrConflict): disabled, it is stopped.

func (*Store) DeleteBacktestBatch

func (s *Store) DeleteBacktestBatch(ctx context.Context, id int64) error

DeleteBacktestBatch deletes the batch of id and its runs, ErrBacktestBusy while some are queued or running, ErrNotFound without it.

func (*Store) DeleteMT5Account

func (s *Store) DeleteMT5Account(ctx context.Context, id int64, change MT5Change) error

DeleteMT5Account deletes the account of MT5 of id, inactive and without an agent, its events kept.

func (*Store) DeletePrompt

func (s *Store) DeletePrompt(ctx context.Context, id int64) error

DeletePrompt deletes the prompt of id, unless an agent uses it: locked first, so that an agent given it meanwhile (see sharePrompt) is one of them, and one given it after waits and fails.

func (*Store) DeleteRole

func (s *Store) DeleteRole(ctx context.Context, id int64) error

DeleteRole deletes the role of id: not the fixed one, nor one some users hold (their role changed first).

func (*Store) DeleteTelegramUser

func (s *Store) DeleteTelegramUser(ctx context.Context, id int64) error

DeleteTelegramUser stops answering the Telegram user of id, the record.

func (*Store) DeleteUser

func (s *Store) DeleteUser(ctx context.Context, id int64) error

DeleteUser deletes the user of id, its role with it: not the last one enabled, nor the last one able to manage the users and the roles.

func (*Store) Discards

func (s *Store) Discards(ctx context.Context, id int64) ([]model.Discard, error)

Discards returns the positions the order controller of the agent of id discarded, by the fill after which each one was.

func (*Store) EndDailyStops

func (s *Store) EndDailyStops(ctx context.Context, keep []int64) (int64, error)

EndDailyStops ends the stop losses in force but the ones of keep: their positions closed, their limits turned off, their day over. It returns how many ended.

func (*Store) EndProtectionArms

func (s *Store) EndProtectionArms(ctx context.Context, id int64, held []string) (int64, error)

EndProtectionArms ends the arms in force of the agent of id whose positions aren't among held (by their references), eg: closed; it returns how many.

func (*Store) ExpireSupervisorActions

func (s *Store) ExpireSupervisorActions(ctx context.Context) (int64, error)

ExpireSupervisorActions marks the proposals past their expiry expired.

func (*Store) ExposureLimits

func (s *Store) ExposureLimits(ctx context.Context) (ExposureLimits, bool, error)

ExposureLimits returns the exposure limit of all the agents, false while never set.

func (*Store) FailRunningSupervisorRuns

func (s *Store) FailRunningSupervisorRuns(ctx context.Context, why string) (int64, error)

FailRunningSupervisorRuns ends the analyses left running, failed for why: the ones of a controller stopped in their middle.

func (*Store) FindBacktestBatches

func (s *Store) FindBacktestBatches(ctx context.Context, q ListQuery) (Listed[BacktestBatch], error)

FindBacktestBatches returns the batches of q, the newest first.

func (*Store) FindMT5Accounts

func (s *Store) FindMT5Accounts(ctx context.Context, q ListQuery) (Listed[MT5Account], error)

FindMT5Accounts returns the accounts of MT5 of q, by their names.

func (*Store) FindPrompts

func (s *Store) FindPrompts(ctx context.Context, q ListQuery) (Listed[PromptSummary], error)

FindPrompts returns the prompts of q, without their content, by name, with the agents using each one.

func (*Store) FindProtectionArms

func (s *Store) FindProtectionArms(ctx context.Context, q ListQuery) (Listed[PositionProtection], error)

FindProtectionArms returns the arms of every agent of q, the newest first.

func (*Store) FindRoles

func (s *Store) FindRoles(ctx context.Context, q ListQuery) (Listed[Role], error)

FindRoles returns the roles of q, the fixed one first and then by name, each with its number of users.

func (*Store) FindSupervisorActions

func (s *Store) FindSupervisorActions(ctx context.Context, q ListQuery) (Listed[SupervisorAction], error)

FindSupervisorActions returns the actions of q, the newest first.

func (*Store) FindSupervisorRuns

func (s *Store) FindSupervisorRuns(ctx context.Context, q ListQuery) (Listed[SupervisorRun], error)

FindSupervisorRuns returns the analyses of q, the newest first, without their snapshot.

func (*Store) FindTelegramUsers

func (s *Store) FindTelegramUsers(ctx context.Context, q ListQuery) (Listed[TelegramUser], error)

FindTelegramUsers returns the Telegram users of q the bot answers, by their ID.

func (*Store) FindUsers

func (s *Store) FindUsers(ctx context.Context, q ListQuery) (Listed[User], error)

FindUsers returns the users of q, by username, with their roles.

func (*Store) FinishBacktestRun

func (s *Store) FinishBacktestRun(ctx context.Context, id int64, status, why string, summary,
	result json.RawMessage) error

FinishBacktestRun records how the run of id ended: its status, error, summary and result.

func (*Store) FinishSupervisorAction

func (s *Store) FinishSupervisorAction(ctx context.Context, id int64, status string, result json.RawMessage) error

FinishSupervisorAction records how the action of id ended, status, and its result, checked.

func (*Store) FinishSupervisorRun

func (s *Store) FinishSupervisorRun(ctx context.Context, run SupervisorRun) error

FinishSupervisorRun records how the analysis run ended: its status, summary, findings, snapshot, usage and error.

func (*Store) GlobalDailyLimit

func (s *Store) GlobalDailyLimit(ctx context.Context) (DailyLimit, bool, error)

GlobalDailyLimit returns the daily limits of all the agents together, false while never set.

func (*Store) InterruptRunningBacktestRuns

func (s *Store) InterruptRunningBacktestRuns(ctx context.Context, why string) (int64, error)

InterruptRunningBacktestRuns ends the runs left running, interrupted for why: the ones of a controller stopped in their middle.

func (*Store) JournalMemory

func (s *Store) JournalMemory(ctx context.Context, id int64, perPair int) ([]Remembered, error)

JournalMemory returns the last perPair decisions of each pair of the journal of the agent of id, oldest first, the errors and the entries without a decision left out: the memory of its prompt, see agents/llm.

func (*Store) LastTradingHoursEnd

func (s *Store) LastTradingHoursEnd(ctx context.Context) (TradingHoursEvent, bool, error)

LastTradingHoursEnd returns the last actions at the end of the window, false while none.

func (*Store) LeaseOrderIDs

func (s *Store) LeaseOrderIDs(ctx context.Context, id, count int64) (first, last int64, err error)

LeaseOrderIDs returns a range of count order IDs for the agent of id, first to last, never leased again: the agent numbers its orders with them.

func (*Store) MT5Account

func (s *Store) MT5Account(ctx context.Context, id int64) (MT5Account, error)

MT5Account returns the account of MT5 of id, ErrNotFound without one.

func (*Store) MT5AccountAgents

func (s *Store) MT5AccountAgents(ctx context.Context) (map[int64][]string, error)

MT5AccountAgents returns the names of the agents linked to each account of MT5, by its ID, the deleted ones left out.

func (*Store) MT5AccountByLogin

func (s *Store) MT5AccountByLogin(ctx context.Context, login int64, server string) (MT5Account, bool, error)

MT5AccountByLogin returns the account of MT5 of login on server, false without one.

func (*Store) MT5AccountEvents

func (s *Store) MT5AccountEvents(ctx context.Context, id int64, limit int) ([]MT5AccountEvent, error)

MT5AccountEvents returns the last limit events of the account of MT5 of id, the newest first.

func (*Store) MT5AccountSecrets

func (s *Store) MT5AccountSecrets(account MT5Account) (password, token string, err error)

MT5AccountSecrets returns the password and the token of the bridge of account, decrypted: "" for none. Only to send them to the bridge.

func (*Store) MT5Accounts

func (s *Store) MT5Accounts(ctx context.Context) ([]MT5Account, error)

MT5Accounts returns the accounts of MT5, by their names.

func (*Store) MarkAgentStop

func (s *Store) MarkAgentStop(ctx context.Context, id int64, state, reason, category, by string,
	actionID *int64) (AgentSupervision, error)

MarkAgentStop records the stop of the agent of id by the supervisor: state pending_flat while it waits for the agent to hold nothing, stopped once disabled; none clears it.

func (*Store) MigrateNewsToken

func (s *Store) MigrateNewsToken(ctx context.Context) (NewsMigration, error)

MigrateNewsToken carries the tokens of the calendar the LLM agents kept each (the column agent_llm_settings.calendar_token, encrypted for their place) to the news of all the agents, the column dropped after: none, nothing to carry; all the same, the token of the news, the news on (as the agents read their calendar); a token of the news already set, kept. With different ones, or one that can't be opened, none is chosen: the column is kept, its tokens as they were, told on the dashboard (NewsConflict) until a token is set there; the next run drops it then. Run by cmd/migrator after the migrations and the seeds, before the controller starts, harmless once the column is dropped.

func (*Store) MigrateNewsURL

func (s *Store) MigrateNewsURL(ctx context.Context) (NewsURLMigration, error)

MigrateNewsURL carries the MCP server of the calendar each LLM agent had (the column agent_llm_settings.calendar_url) to the news of all the agents, the column dropped after: none, nothing to carry; all the same, the address of the news unless set on the dashboard. With different ones, none is chosen: the column is kept, told on the dashboard (NewsURLConflict) until the address is set there; the next run drops it then. The params of the window of the news block of the agents (news-block-*) are removed: the window is the one of the news of all the agents. Run by cmd/migrator after the migrations and the seeds, before the controller starts, harmless after.

func (*Store) MigrateUserRoles

func (s *Store) MigrateUserRoles(ctx context.Context) (int64, error)

MigrateUserRoles gives the fixed role of the administrators to every user of a database whose users hold no role yet, the dashboard having had no roles before: once, the users keeping the access they had; and returns how many. Afterwards a role is always held (see guardAdmins), so it does nothing.

func (*Store) News

func (s *Store) News(ctx context.Context) (NewsSettings, bool, error)

News returns the news of the agents, and whether they exist: false before the seeds are applied, the news off then.

func (*Store) NewsConflict

func (s *Store) NewsConflict(ctx context.Context) ([]string, error)

NewsConflict returns the agents whose former tokens of the calendar wait for the token of the news to be set (see MigrateNewsToken): they held different ones, or one that can't be opened, and none was chosen. Empty without a conflict.

func (*Store) NewsRules

func (s *Store) NewsRules(ctx context.Context) (NewsRules, bool, error)

NewsRules returns the rules of the news, and whether they exist: false before the seeds are applied, no server nor window then.

func (*Store) NewsToken

func (s *Store) NewsToken(ctx context.Context) (string, error)

NewsToken returns the token of the MCP server of the news, decrypted: "" for none.

func (*Store) NewsURLConflict

func (s *Store) NewsURLConflict(ctx context.Context) ([]string, error)

NewsURLConflict returns the LLM agents whose former servers of the calendar differ, none chosen, until the address of the news is set on the dashboard (see MigrateNewsURL). Empty without a conflict.

func (*Store) Orders

func (s *Store) Orders(ctx context.Context, id, after int64, limit int) ([]model.Order, error)

Orders returns at most limit orders of the agent of id after the order of ID after, by ID.

func (*Store) Periods

func (s *Store) Periods(ctx context.Context, name string) ([]Period, error)

Periods returns the periods of the agent of name, the current one first; none before its first reset.

func (*Store) Ping

func (s *Store) Ping(ctx context.Context) error

Ping checks the connection to the database.

func (*Store) PreviousSupervisorRun

func (s *Store) PreviousSupervisorRun(ctx context.Context, id int64) (SupervisorRun, bool, error)

PreviousSupervisorRun returns the last analysis ended ok before the one of id, false for none.

func (*Store) ProgressBacktestRun

func (s *Store) ProgressBacktestRun(ctx context.Context, id, processed, total int64) error

ProgressBacktestRun records the progress of the run of id, running.

func (*Store) Prompt

func (s *Store) Prompt(ctx context.Context, id int64) (Prompt, error)

Prompt returns the prompt of id.

func (*Store) PromptByName

func (s *Store) PromptByName(ctx context.Context, name string) (Prompt, error)

PromptByName returns the prompt of name.

func (*Store) PromptVersion

func (s *Store) PromptVersion(ctx context.Context, id int64, version int) (PromptVersion, error)

PromptVersion returns the version of the prompt of id.

func (*Store) Prompts

func (s *Store) Prompts(ctx context.Context) ([]PromptSummary, error)

Prompts returns the prompts without their content, by name, with the agents using each one.

func (*Store) ProtectionArms

func (s *Store) ProtectionArms(ctx context.Context, limit int) ([]PositionProtection, error)

ProtectionArms returns the last limit arms of every agent, the newest first.

func (*Store) ProtectionArmsInForce

func (s *Store) ProtectionArmsInForce(ctx context.Context, id int64) ([]PositionProtection, error)

ProtectionArmsInForce returns the arms in force of the agent of id (requested, armed or active), the oldest first.

func (*Store) ProtectionArmsOfRun

func (s *Store) ProtectionArmsOfRun(ctx context.Context, runID int64) ([]PositionProtection, error)

ProtectionArmsOfRun returns the arms an analysis asked for.

func (*Store) ProtectionIDsOfRuns

func (s *Store) ProtectionIDsOfRuns(ctx context.Context, runIDs []int64) (map[int64][]int64, error)

ProtectionIDsOfRuns returns the arms the analyses of runIDs asked for, by analysis, the oldest first.

func (*Store) RecentOrders

func (s *Store) RecentOrders(ctx context.Context, id int64, limit int) ([]model.Order, error)

RecentOrders returns the last limit orders of the agent of id, by ID.

func (*Store) RecordMT5Session

func (s *Store) RecordMT5Session(ctx context.Context, id int64, reason, failure string) error

RecordMT5Session records the session of the account of MT5 of id given to its terminal, why and how it went.

func (*Store) RecordTradingHours

func (s *Store) RecordTradingHours(ctx context.Context, e *TradingHoursEvent) error

RecordTradingHours records e, its ID (the revision of the entries) set.

func (*Store) RejectSupervisorAction

func (s *Store) RejectSupervisorAction(ctx context.Context, id int64, by string) (SupervisorAction, error)

RejectSupervisorAction rejects the proposal of id, by by, see ClaimSupervisorAction.

func (*Store) ReleaseDailyGuard

func (s *Store) ReleaseDailyGuard(ctx context.Context, id int64, change DailyChange,
	metric any) (DailyGuard, bool, error)

ReleaseDailyGuard releases the guard of id, tripped, for change (eg: a limit raised above the result), recorded; false when it wasn't tripped.

func (*Store) ReleaseMarginGuard

func (s *Store) ReleaseMarginGuard(ctx context.Context, id int64, change DailyChange, metric any) (bool, error)

ReleaseMarginGuard releases the guard of the margin of id, tripped, for change, recorded as an event released; false when it wasn't tripped.

func (*Store) RemoveAgentParams

func (s *Store) RemoveAgentParams(ctx context.Context, id int64, removals []ParamChange) ([]ParamSet, error)

RemoveAgentParams removes the params of removals from the agent of id at once, its row locked meanwhile, by their names: each one with any value, or only with its Value when it is set; its other params and its settings kept, checked as UpdateAgent checks a change of its params (see checkAgent): the agent then runs with the default of its strategy for them. A param is skipped on the agent without it, or holding another value than the one asked; nothing is written when none is removed. It returns what was done with each param, in their order (Had the value removed). Its error refuses them all on this agent, nothing changed on it: the caller goes on with the others.

func (*Store) RenameAgent

func (s *Store) RenameAgent(ctx context.Context, id int64, name string) (Agent, error)

RenameAgent renames the agent of id to name, keeping all it has: its ID, its account (its comment and magic number at the broker), its language model, its orders, its decisions and its journal; its former name is kept (see agent_former_names), so the seeds don't bring it back. A name taken by another agent is ErrConflict, one out of the rules ErrInvalid. An agent enabled isn't renamed (ErrConflict): disabled, it is stopped, and its files named after it, eg: its outbox, can be renamed with it, see Manager.

func (*Store) ReserveOrderIDs

func (s *Store) ReserveOrderIDs(ctx context.Context, id, last int64) error

ReserveOrderIDs moves the next order ID of the agent of id past last, the highest one of its orders imported.

func (*Store) Role

func (s *Store) Role(ctx context.Context, id int64) (Role, error)

Role returns the role of id.

func (*Store) Roles

func (s *Store) Roles(ctx context.Context) ([]Role, error)

Roles returns the roles, the fixed one first and then by name, each with its number of users.

func (*Store) RolloverDailyGuards

func (s *Store) RolloverDailyGuards(ctx context.Context, today string) ([]DailyGuard, error)

RolloverDailyGuards releases the guards tripped before today (eg: 2026-10-29), at the end of their day, recorded, and returns them.

func (*Store) SaveDecision

func (s *Store) SaveDecision(ctx context.Context, id int64, d ui.Decision, attachments []Attachment,
	overwrite bool) error

SaveDecision keeps a decision of the agent of id with its attachments and the links of its orders: an order placed by the first decision listing it, moved by the others. It replaces the decision of its ID, or, unless overwrite, keeps it only when missing.

func (*Store) SaveDiscard

func (s *Store) SaveDiscard(ctx context.Context, id int64, discard model.Discard) error

SaveDiscard keeps a position the order controller of the agent of id discarded: once, the one of the same pair after the same fill kept as it is, eg: sent again by the outbox.

func (*Store) SaveOrders

func (s *Store) SaveOrders(ctx context.Context, id int64, orders []model.Order, overwrite bool) error

SaveOrders writes the orders of the agent of id: each one replacing the one of its ID when it is a later state of it (see model.Order.Supersedes: the copy of an order a bot wrote late never takes back a fill written before it, the same state written again changing nothing; a fill written again keeping the time of the first, see fillTime), or, unless overwrite, kept only when missing (an import never replaces what the agent wrote since).

func (*Store) Savepoint

func (s *Store) Savepoint(ctx context.Context, name string, fn func(ctx context.Context) error) error

Savepoint runs fn in a savepoint of the transaction of ctx, named name (an SQL identifier): its writes undone when it fails, the transaction going on, whereas a failure in a transaction joined (see Transaction) leaves it aborted. Without a transaction, fn runs in one of its own.

func (*Store) SecretsOf

func (s *Store) SecretsOf(agent Agent) (AgentSecretValues, error)

SecretsOf returns the secrets of agent, as read, decrypted, eg: the ones it was launched with: only for the agent itself, see AgentSecrets.

func (*Store) SetAgentBotStopped

func (s *Store) SetAgentBotStopped(ctx context.Context, id int64, stopped bool, by string) error

SetAgentBotStopped records the bot of the agent of id stopped, or started, by by, now, see AgentBotControl.

func (*Store) SetAgentDailyLimit

func (s *Store) SetAgentDailyLimit(ctx context.Context, id int64, settings ui.DailyLimitSettings,
	change DailyChange) (previous, next AgentDailyLimit, err error)

SetAgentDailyLimit sets the daily limits of the agent of id, validated (see validateDailyLimit), recorded with the previous ones, and returns both.

func (*Store) SetAgentEntries

func (s *Store) SetAgentEntries(ctx context.Context, id int64, blocked bool, reason, by string,
	actionID *int64) (AgentSupervision, error)

SetAgentEntries blocks the entries of the agent of id, for reason, by by, of the action of actionID, if any, or allows them again: a new revision either way, so that the agent applies it after any older one.

func (*Store) SetAgentMT5Account

func (s *Store) SetAgentMT5Account(ctx context.Context, agentID int64, accountID *int64, change MT5Change) error

SetAgentMT5Account links the agent of agentID to the account of MT5 of accountID, unlinks it with nil: its bridge then the one of the account (its account created when missing), recorded. The token of the bridge of the agent itself is left: unread while it is linked, see SecretsOf.

func (*Store) SetAgentParam

func (s *Store) SetAgentParam(ctx context.Context, id int64, name, value string, addMissing bool) (ParamSet,
	error)

SetAgentParam sets the param name to value on the agent of id, see SetAgentParams.

func (*Store) SetAgentParams

func (s *Store) SetAgentParams(ctx context.Context, id int64, changes []ParamChange, addMissing bool) ([]ParamSet,
	error)

SetAgentParams sets the params of changes on the agent of id at once, its row locked meanwhile: its other params and its settings kept, checked as UpdateAgent checks a change of its params (see checkAgent), eg: a param of a language model on an agent of another kind refused. Each param changes on the agent holding it, and on the one without it when addMissing; nothing is written when the agent has every value already. A param is skipped on the agent without it and not addMissing, or without a language model for one of it (see llmParam), which it can't hold. It returns what was done with each param, in their order. Its error refuses them all on this agent, nothing changed on it: the caller goes on with the others.

func (*Store) SetAgentPrompt

func (s *Store) SetAgentPrompt(ctx context.Context, id int64, promptID *int64) error

SetAgentPrompt selects the prompt of the LLM agent of id, the default one embedded in the agent when nil: one deleted, or deleted meanwhile, is ErrNotFound (see sharePrompt).

func (*Store) SetAgentProtection

func (s *Store) SetAgentProtection(ctx context.Context, id int64, settings ui.ProtectionSettings,
	by string) (AgentProtection, error)

SetAgentProtection sets the protection of the positions of the agent of id, by by, validated (see validateProtection), and returns it.

func (*Store) SetAgentSecrets

func (s *Store) SetAgentSecrets(ctx context.Context, id int64, secrets AgentSecrets) error

SetAgentSecrets writes the secrets of the agent of id, the ones set: the token of the bridge to its account, the key to its language model.

func (*Store) SetArmStatus

func (s *Store) SetArmStatus(ctx context.Context, id int64, status string, move *ProtectionMove) error

SetArmStatus sets the status of the arm of id, and its last move when move is set; an arm ended stays ended.

func (*Store) SetAssetAgents

func (s *Store) SetAssetAgents(ctx context.Context, settings ui.AssetAgentsSettings, by string) (AssetAgents,
	error)

SetAssetAgents sets the agents allowed on assets, validated against the agents (see validateAssetAgents), by by, its revision grown, and returns them.

func (*Store) SetDailyStop

func (s *Store) SetDailyStop(ctx context.Context, target DailyStopTarget) (DailyStop, error)

SetDailyStop records the stop loss of target in force: the one of its position of the day updated (its level, side, tickets, scope and budget; its last move kept), else added; a position whose side changed starts again. It returns the stop as recorded.

func (*Store) SetDailyStopMove

func (s *Store) SetDailyStopMove(ctx context.Context, id int64, move DailyStopMove) error

SetDailyStopMove records the last move of the stop loss of id.

func (*Store) SetExposureLimits

func (s *Store) SetExposureLimits(ctx context.Context, settings ui.ExposureSettings, by string) (ExposureLimits,
	error)

SetExposureLimits sets the exposure limit of all the agents, validated (see validateExposure), by by, and returns it.

func (*Store) SetGlobalDailyLimit

func (s *Store) SetGlobalDailyLimit(ctx context.Context, settings ui.DailyLimitSettings,
	change DailyChange) (previous, next DailyLimit, err error)

SetGlobalDailyLimit sets the daily limits of all the agents together, validated (see validateDailyLimit), recorded with the previous ones (see DailyLimitEvent), and returns both.

func (*Store) SetGuardFlatten

func (s *Store) SetGuardFlatten(ctx context.Context, id int64, status string, actionID *int64,
	attempts int) error

SetGuardFlatten records how the positions of the guard of id are closed: status (see FlattenRunning), the action closing them and the attempts, and, once ended, an event of it.

func (*Store) SetMT5AccountCheck

func (s *Store) SetMT5AccountCheck(ctx context.Context, id int64, kind, currency, company, failure string,
	at time.Time, change MT5Change) error

SetMT5AccountCheck records what the bridge confirmed of the account of MT5 of id: its kind (of its trade_mode), currency and company, or why it couldn't (failure), at at; an event of it when tested by a user (change.By).

func (*Store) SetNews

func (s *Store) SetNews(ctx context.Context, update NewsUpdate) (NewsSettings, error)

SetNews changes the news and their rules, the rows locked from their read to their write: ErrNotFound before the seeds are applied, ErrInvalid for a rule out of its bounds. A token set ends a conflict of the former tokens of the agents (see NewsConflict): their column, unused, is dropped by the next run of cmd/migrator (see MigrateNewsToken), never by the controller, whose prepared queries of the table would change under it.

func (*Store) SetPassword

func (s *Store) SetPassword(ctx context.Context, id int64, password string) error

SetPassword replaces the password of the user of id.

func (*Store) SetPromptStatus

func (s *Store) SetPromptStatus(ctx context.Context, id int64, status PromptStatus) error

SetPromptStatus keeps the last prompt switch the LLM agent of id reported.

func (*Store) SetSupervisor

func (s *Store) SetSupervisor(ctx context.Context, update SupervisorUpdate) (SupervisorSettings, error)

SetSupervisor changes the settings of the supervisor, the row locked from its read to its write: ErrNotFound before the seeds are applied, ErrInvalid for a value out of its bounds, or the supervisor enabled without a model and its key.

func (*Store) SetTelegram

func (s *Store) SetTelegram(ctx context.Context, enabled *bool, token Secret) error

SetTelegram changes the settings of the Telegram bot: enabled when set, and its token, see Secret; the one kept, sealed by a version before the places of the secrets (see unseal), sealed again for its place as it is written. The row is locked from its read to its write, and only the columns changed are written: two changes at once, eg: the switch and the token, both apply.

func (*Store) SetTelegramUserName

func (s *Store) SetTelegramUserName(ctx context.Context, id int64, name string) error

SetTelegramUserName renames the Telegram user of id.

func (*Store) SetTradingHours

func (s *Store) SetTradingHours(ctx context.Context, settings ui.TradingHoursSettings, by string, userID *int64,
	reason string) (previous, next TradingHours, err error)

SetTradingHours sets the trading hours of all the agents, validated (see tradingWindows), by by (userID, when a user) for reason, recorded with the previous ones (see TradingHoursEvent), and returns both: their windows in trading_hours_windows, the first one also in their own columns.

func (*Store) SetTradingHoursEnd

func (s *Store) SetTradingHoursEnd(ctx context.Context, id int64, status string, actionID *int64) error

SetTradingHoursEnd records how the actions at the end of the window of the event of id ended: status and the action.

func (*Store) SetUserEnabled

func (s *Store) SetUserEnabled(ctx context.Context, id int64, enabled bool) error

SetUserEnabled enables or disables the user of id: the last user enabled can't be disabled, nor the last one able to manage the users and the roles (see guardAdmins), which would lock the dashboard.

func (*Store) SetUserRole

func (s *Store) SetUserRole(ctx context.Context, userID, roleID int64, by string) error

SetUserRole gives the role of roleID to the user of userID, by by; 0 takes its role away, the user then refused at the login. Refused when it leaves nobody to manage the users and the roles, see guardAdmins.

func (*Store) StartPeriod

func (s *Store) StartPeriod(ctx context.Context, name string, deposit float64, currency, by string) (Period,
	error)

StartPeriod resets the results of the agent of name: a new period starting now, deposit, in currency, its balance (rounded to cents, see cents), started by the user by. The earlier periods are kept, the current one ending as it starts. A deposit out of 0 to 1e12, or a currency that isn't a code of 3 letters, is refused (ErrInvalid).

func (*Store) StartSupervisorRun

func (s *Store) StartSupervisorRun(ctx context.Context, origin, status, requestedBy, model string) (SupervisorRun,
	error)

StartSupervisorRun records an analysis starting, running; skipped ones are recorded ended, see FinishSupervisorRun.

func (*Store) StopAgentFlat

func (s *Store) StopAgentFlat(ctx context.Context, id, actionID int64) (bool, error)

StopAgentFlat disables the agent of id, stopped by the supervisor once flat, only when it is still enabled and waits for it as the action of actionID asked: false when anything changed meanwhile, eg: a user who enabled it again, or another stop.

func (*Store) Supervisor

func (s *Store) Supervisor(ctx context.Context) (SupervisorSettings, bool, error)

Supervisor returns the settings of the supervisor, and whether they exist: false before the seeds are applied, the supervisor off then.

func (*Store) SupervisorAction

func (s *Store) SupervisorAction(ctx context.Context, id int64) (SupervisorAction, error)

SupervisorAction returns the action of id.

func (*Store) SupervisorActions

func (s *Store) SupervisorActions(ctx context.Context, limit int) ([]SupervisorAction, error)

SupervisorActions returns the last actions, the newest first.

func (*Store) SupervisorKey

func (s *Store) SupervisorKey(ctx context.Context) (string, error)

SupervisorKey returns the key of the language model of the supervisor, decrypted: "" for none.

func (*Store) SupervisorMessages

func (s *Store) SupervisorMessages(ctx context.Context, userID, before int64, limit int) ([]SupervisorMessage,
	error)

SupervisorMessages returns the last limit messages of the conversation of the user of userID before the one of before (0 for the last ones), the oldest first.

func (*Store) SupervisorRun

func (s *Store) SupervisorRun(ctx context.Context, id int64) (SupervisorRun, error)

SupervisorRun returns the analysis of id, its snapshot included.

func (*Store) SupervisorRuns

func (s *Store) SupervisorRuns(ctx context.Context, limit int) ([]SupervisorRun, error)

SupervisorRuns returns the last analyses, the newest first, without their snapshot.

func (*Store) Telegram

func (s *Store) Telegram(ctx context.Context) (settings TelegramSettings, hasToken bool, err error)

Telegram returns the settings of the Telegram bot, and whether it has a token, without it.

func (*Store) TelegramToken

func (s *Store) TelegramToken(ctx context.Context) (string, error)

TelegramToken returns the token of the Telegram bot, decrypted: "" for none.

func (*Store) TelegramUsers

func (s *Store) TelegramUsers(ctx context.Context) ([]TelegramUser, error)

TelegramUsers returns the Telegram users the bot answers, by their ID.

func (*Store) TradingHours

func (s *Store) TradingHours(ctx context.Context) (TradingHours, bool, error)

TradingHours returns the trading hours of all the agents, false while never set.

func (*Store) TradingHoursEntries

func (s *Store) TradingHoursEntries(ctx context.Context, id int64) (blocked bool, reason string, pairs []string,
	pairsReason string, revision int64, err error)

TradingHoursEntries returns whether the entries of the agent of id are blocked by the trading hours (outside their windows, or in a window for other agents, as recorded), why, the only assets it may open positions on in the window open (pairs, none for all of them, and why), and the revision of the trading hours (the last of their events), which only grows.

func (*Store) TradingHoursState

func (s *Store) TradingHoursState(ctx context.Context) (TradingHoursEvent, bool, error)

TradingHoursState returns the last event of the trading hours closing, opening or releasing their window: how they stand, false while none.

func (*Store) Transaction

func (s *Store) Transaction(ctx context.Context, fn func(ctx context.Context) error) error

Transaction runs fn in a transaction, carried by its context: the methods of the store called with it take part in it. A transaction already in the context is joined.

func (*Store) TripDailyGuard

func (s *Store) TripDailyGuard(ctx context.Context, trip GuardTrip) (guard DailyGuard, newly bool, err error)

TripDailyGuard trips the guard of trip: created, or tripped again when released that day (its trips counted), recorded (see DailyLimitEvent); a guard tripped already is left as it is. newly tells it tripped now.

func (*Store) TripMarginGuard

func (s *Store) TripMarginGuard(ctx context.Context, trip MarginTrip) (guard MarginGuard, newly bool, err error)

TripMarginGuard trips the guard of the margin of trip, once a day by scope (again after a release, its trips counted), recorded as an event tripped; newly false when it was tripped already.

func (*Store) TrippedDailyGuards

func (s *Store) TrippedDailyGuards(ctx context.Context) ([]DailyGuard, error)

TrippedDailyGuards returns the daily guards tripped, of any day, in their order.

func (*Store) TrippedMarginGuards

func (s *Store) TrippedMarginGuards(ctx context.Context) ([]MarginGuard, error)

TrippedMarginGuards returns the guards of the margin tripped.

func (*Store) UnknownExecutingSupervisorActions

func (s *Store) UnknownExecutingSupervisorActions(ctx context.Context, why string) (int64, error)

UnknownExecutingSupervisorActions ends the actions left executing, their outcome unknown: the ones of a controller stopped in their middle, to check on the accounts, never to execute again.

func (*Store) UpdateAgent

func (s *Store) UpdateAgent(ctx context.Context, id int64, update AgentUpdate) (Agent, error)

UpdateAgent changes the agent of id, see AgentUpdate: a change of more than its switches (Enabled, TradePanel, TelegramControl, Reanalysis) is checked with the whole agent, as CreateAgent checks a new one, and a new address with the ones of the others; the switches alone always apply, eg: to disable it, but for enabling an agent trading the positions of another one, as a change of what it trades (ErrConflict, see checkBookFree), and for the reanalysis of an agent of another kind than llm (ErrInvalid).

func (*Store) UpdateMT5Account

func (s *Store) UpdateMT5Account(ctx context.Context, id int64, in MT5AccountInput,
	change MT5Change) (previous, next MT5Account, err error)

UpdateMT5Account changes the account of MT5 of id as in, validated, the bridge of its agents with it, recorded, and returns it before and after.

func (*Store) UpdatePrompt

func (s *Store) UpdatePrompt(ctx context.Context, id int64, edit PromptEdit, by string) (Prompt, error)

UpdatePrompt edits the prompt of id by who: a new content is a new version.

func (*Store) UpdateRole

func (s *Store) UpdateRole(ctx context.Context, id int64, change RoleChange) (Role, error)

UpdateRole changes the role of id, of the fields of change set, by change.By: not the fixed one; its permissions refused when the change leaves nobody to manage the users and the roles (see guardAdmins).

func (*Store) User

func (s *Store) User(ctx context.Context, id int64) (User, error)

User returns the user of id, with its role and the permissions of it.

func (*Store) Users

func (s *Store) Users(ctx context.Context) ([]User, error)

Users returns the users, by username, with their roles.

type SupervisorAction

type SupervisorAction struct {
	ID          int64           `json:"id"`
	Source      string          `json:"source"`
	RunID       *int64          `json:"run_id,omitempty"`
	UserID      *int64          `json:"user_id,omitempty"`
	Action      string          `json:"action"`
	Mode        string          `json:"mode,omitempty"`
	Scope       json.RawMessage `json:"scope"`
	Options     json.RawMessage `json:"options"`
	Reason      string          `json:"reason"`
	Category    string          `json:"category,omitempty"`
	Evidence    json.RawMessage `json:"evidence"`
	Status      string          `json:"status"`
	Result      json.RawMessage `json:"result,omitempty"`
	RequestedBy string          `json:"requested_by"`
	ConfirmedBy string          `json:"confirmed_by"`
	CreatedAt   time.Time       `json:"created_at"`
	ExpiresAt   *time.Time      `json:"expires_at,omitempty"`
	DecidedAt   *time.Time      `json:"decided_at,omitempty"`
	FinishedAt  *time.Time      `json:"finished_at,omitempty"`
}

SupervisorAction is an action of the supervision on the agents: Scope, Options, Evidence and Result are JSON, the shapes of the controller.

type SupervisorMessage

type SupervisorMessage struct {
	ID        int64      `gorm:"primaryKey" json:"id"`
	UserID    int64      `json:"-"`
	Role      string     `json:"role"`
	Kind      string     `json:"kind"`
	Content   string     `json:"content"`
	ActionID  *int64     `json:"action_id,omitempty"`
	DataAt    *time.Time `json:"data_at,omitempty"`
	CreatedAt time.Time  `json:"created_at"`
}

SupervisorMessage is a message of the conversation of a user with the supervisor: DataAt is when the data the answer rests on was read.

func (SupervisorMessage) TableName

func (SupervisorMessage) TableName() string

type SupervisorRun

type SupervisorRun struct {
	ID          int64
	Origin      string
	Status      string
	RequestedBy string
	Model       string
	StartedAt   time.Time
	FinishedAt  *time.Time
	Snapshot    json.RawMessage
	Summary     string
	Findings    json.RawMessage
	Error       string
	Usage       json.RawMessage
}

SupervisorRun is an analysis of the supervisor: Snapshot the data sent to the model, Findings what it found, a JSON array, Usage the tokens of its answers.

type SupervisorSettings

type SupervisorSettings struct {
	ID              int16     `gorm:"primaryKey;autoIncrement:false" json:"-"`
	Enabled         bool      `json:"enabled"`
	IntervalSeconds int       `json:"interval_seconds"`
	Provider        *string   `json:"provider,omitempty"`
	Model           *string   `json:"model,omitempty"`
	APIKey          []byte    `gorm:"column:api_key" json:"-"` // encrypted
	BaseURL         *string   `gorm:"column:base_url" json:"base_url,omitempty"`
	ReasoningEffort *string   `json:"reasoning_effort,omitempty"`
	MaxTokens       *int      `json:"max_tokens,omitempty"`
	TimeoutSeconds  int       `json:"timeout_seconds"`
	Instructions    string    `json:"instructions"`
	Autonomy        Autonomy  `gorm:"type:jsonb" json:"autonomy"`
	UpdatedAt       time.Time `json:"updated_at"`
}

SupervisorSettings are the supervisor of the agents, a single record: its switch, the interval of its analyses, its language model as the ones of the LLM agents (see LLMSettings), the timeout of an answer, its instructions and its autonomy.

func (SupervisorSettings) TableName

func (SupervisorSettings) TableName() string

type SupervisorUpdate

type SupervisorUpdate struct {
	Enabled         *bool
	IntervalSeconds *int
	Provider        *string
	Model           *string
	BaseURL         *string
	ReasoningEffort *string
	MaxTokens       *int
	TimeoutSeconds  *int
	Instructions    *string
	Autonomy        *Autonomy
	APIKey          Secret
}

SupervisorUpdate is a change of the settings of the supervisor, of the fields set: an empty BaseURL or ReasoningEffort and a MaxTokens of 0 remove them, the defaults of the model applying; APIKey is a Secret.

type TelegramSettings

type TelegramSettings struct {
	ID        int16     `gorm:"primaryKey;autoIncrement:false" json:"-"`
	Enabled   bool      `json:"enabled"`
	Token     []byte    `json:"-"` // encrypted
	UpdatedAt time.Time `json:"updated_at"`
}

TelegramSettings are the Telegram bot of the controller, a single record.

type TelegramUser

type TelegramUser struct {
	Model
	TelegramID int64  `gorm:"column:telegram_id" json:"telegram_id"`
	Name       string `json:"name"`
}

TelegramUser is a Telegram user the bot answers.

type TradingHours

type TradingHours struct {
	ID            int16              `gorm:"primaryKey;autoIncrement:false" json:"-"`
	Enabled       bool               `json:"enabled"`
	StartTime     string             `json:"start_time"`
	EndTime       string             `json:"end_time"`
	Flatten       bool               `json:"flatten"`
	CancelPending bool               `json:"cancel_pending"`
	UpdatedBy     string             `json:"updated_by"`
	UpdatedAt     time.Time          `json:"updated_at"`
	Windows       []ui.TradingWindow `gorm:"-" json:"windows,omitempty"`
}

TradingHours is the trading hours of all the agents, a single record, see ui.TradingHoursSettings: none while never set (off). Its windows are in trading_hours_windows (Windows, read with it); its own start, end and actions are its first one, kept for the readers of a single window, and its only one while it has none there (the hours of before).

func (TradingHours) Settings

func (h TradingHours) Settings() ui.TradingHoursSettings

Settings returns the hours as the dashboard takes them: their windows, the first one also as its start, end and actions.

func (TradingHours) TableName

func (TradingHours) TableName() string

type TradingHoursEvent

type TradingHoursEvent struct {
	ID          int64           `gorm:"primaryKey" json:"id"`
	At          time.Time       `json:"at"`
	Kind        string          `json:"kind"`
	RequestedBy string          `json:"requested_by"`
	UserID      *int64          `json:"user_id,omitempty"`
	Reason      string          `json:"reason"`
	Previous    json.RawMessage `gorm:"type:jsonb" json:"previous,omitempty"`
	Next        json.RawMessage `gorm:"type:jsonb" json:"next,omitempty"`
	ActionID    *int64          `json:"action_id,omitempty"`
	Status      string          `json:"status"`
}

TradingHoursEvent is an event of the trading hours (trading_hours_events): the hours changed (Previous and Next), the window closed, opened or released (the hours off), or the actions at its end (ActionID and their Status). Its ID is the revision of the entries of the agents.

func (TradingHoursEvent) TableName

func (TradingHoursEvent) TableName() string

type TradingHoursWindow

type TradingHoursWindow struct {
	ID            int64 `gorm:"primaryKey"`
	HoursID       int16
	Position      int16
	StartTime     string
	EndTime       string
	Flatten       bool
	CancelPending bool
}

TradingHoursWindow is a window of the trading hours (trading_hours_windows), at Position in the order of the day, see ui.TradingWindow.

func (TradingHoursWindow) TableName

func (TradingHoursWindow) TableName() string

type TradingHoursWindowAgent

type TradingHoursWindowAgent struct {
	WindowID int64 `gorm:"primaryKey;autoIncrement:false"`
	AgentID  int64 `gorm:"primaryKey;autoIncrement:false"`
}

TradingHoursWindowAgent is an agent allowed in a window of the trading hours (trading_hours_window_agents), by id.

func (TradingHoursWindowAgent) TableName

func (TradingHoursWindowAgent) TableName() string

type TradingHoursWindowPair

type TradingHoursWindowPair struct {
	WindowID int64  `gorm:"primaryKey;autoIncrement:false"`
	Pair     string `gorm:"primaryKey"`
}

TradingHoursWindowPair is an asset of a window of the trading hours (trading_hours_window_pairs).

func (TradingHoursWindowPair) TableName

func (TradingHoursWindowPair) TableName() string

type User

type User struct {
	Model
	Username     string     `json:"username"`
	PasswordHash string     `json:"-"`
	Enabled      bool       `json:"enabled"`
	LastLoginAt  *time.Time `json:"last_login_at,omitempty"`
	RoleLink     *UserRole  `gorm:"foreignKey:UserID" json:"-"`
}

User is a user of the dashboard: RoleLink its role, see RoleOf.

func (User) RoleOf

func (u User) RoleOf() *Role

RoleOf returns the role of u as read, nil for none: it can't log in.

type UserRole

type UserRole struct {
	UserID    int64 `gorm:"primaryKey;autoIncrement:false"`
	RoleID    int64
	Role      *Role `gorm:"foreignKey:RoleID"`
	UpdatedBy string
	UpdatedAt time.Time
}

UserRole is the role of a user of the dashboard, who gave it last and when.

Jump to

Keyboard shortcuts

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