agentapi

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: 19 Imported by: 0

Documentation

Overview

Package agentapi is the internal API of the controller for the agents it launches: the settings each agent runs with, what it applies while it runs (the channels of its control panel, the prompt of an LLM agent), and the records it keeps through the controller, which alone reaches the database: its orders and the positions its order controller discarded, and the decisions and journal of an LLM agent.

The controller serves it on the loopback (agents.api of config.yml), under Prefix, and gives each start of an agent its URL and a token of its own in the environment (see EnvURL): every request carries the token, and only reaches the settings and the records of that agent.

Index

Constants

View Source
const (
	// EnvURL is the variable of the URL of the internal API, eg:
	// http://127.0.0.1:8090.
	EnvURL = "XTRADER_CONTROLLER_URL"
	// EnvAgent is the variable of the name of the agent.
	EnvAgent = "XTRADER_AGENT"
	// EnvToken is the variable of the token of the start of the agent, sent
	// as Authorization: Bearer <token>.
	EnvToken = "XTRADER_AGENT_TOKEN"
	// EnvAPIKey is the variable of the key of the start of the agent the
	// controller sends to its API, which wants it (see ui.WithAPIKey): apart
	// from the token, which the API of the agent never gets.
	EnvAPIKey = "XTRADER_AGENT_API_KEY"

	// Prefix is the path of the routes of the internal API.
	Prefix = "/internal/v1"

	// MaxBody is the size of a request to the internal API at most: a batch
	// of records, see OutboxRequest.
	MaxBody = 64 << 20
)
View Source
const (
	KindOrder        = "order"         // a model.Order
	KindDecision     = "decision"      // a DecisionRecord
	KindJournal      = "journal"       // a JournalRecord
	KindPromptStatus = "prompt_status" // a PromptStatus
	KindDiscard      = "discard"       // a model.Discard
)

The kinds of the records of the outbox of an agent, see Record.

View Source
const (
	BacktestStatusSucceeded       = "succeeded"
	BacktestStatusCanceled        = "canceled"
	BacktestStatusFailed          = "failed"
	BacktestStatusBudgetExhausted = "budget_exhausted"
)

The status of a report: the run ended with its last candle, was canceled (its report partial), failed, or stopped at its budget (an LLM).

View Source
const (
	BacktestReasonMarket     = "market"        // an order at the market of the strategy
	BacktestReasonLimit      = "limit"         // a limit order
	BacktestReasonStopEntry  = "stop_entry"    // a stop entry order
	BacktestReasonStopLoss   = "stop_loss"     // the stop loss, maybe moved by the breakeven or the trailing stop
	BacktestReasonTakeProfit = "take_profit"   // the take profit
	BacktestReasonDailyLimit = "daily_limit"   // closed by the daily limit, see the backtest of the agents
	BacktestReasonStopOut    = "stop_out"      // closed as the equity reached 0
	BacktestReasonHours      = "trading_hours" // closed at the end of the trading hours
)

The reasons of the entries and the exits of the trades, see Trade.

View Source
const DefaultPair = "XAUUSDm"

DefaultPair is the pair an agent trades without -pair.

View Source
const ExposurePath = "/exposure/claim"

ExposurePath is the path of the claims of an entry, POST, under Prefix.

View Source
const MT5MaxComment = 31

MT5MaxComment is the longest comment of an order MT5 keeps.

View Source
const MaxTradingWindows = 24

MaxTradingWindows is the number of windows the trading hours take at most.

View Source
const PrintWarmupFlag = "print-warmup"

PrintWarmupFlag is the flag of the agents printing the warmup of their strategy, see Warmup, and exiting: what the controller reads before the period of a backtest.

Variables

This section is empty.

Functions

func DefaultStrategy

func DefaultStrategy(kind string) string

DefaultStrategy returns the strategy an agent of kind trades without -strategy, "" for an LLM agent or a kind unknown.

func HoursWindows

func HoursWindows(windows []ui.TradingWindow, start, end string, flatten, cancelPending bool) []ui.TradingWindow

HoursWindows returns the windows of trading hours: windows when there are, else the single window from start to end with flatten and cancelPending (the hours of before), none without it.

func MT5BridgeKey

func MT5BridgeKey(raw string) string

MT5BridgeKey returns the key of the bridge at the URL raw, the same for two URLs reaching it, see SameMT5Bridge: its host and its port.

func MT5Comment

func MT5Comment(comment, name string) string

MT5Comment returns the comment of the orders of an agent on MT5, the one its magic number is a hash of by default (see MT5Magic): comment, trimmed, when set (-mt5-comment), else "nb:" followed by name, its strategy or llm for an LLM agent, cut to MT5MaxComment. The agents, the controller and the store compute it alike, so that the store refuses two agents trading the same positions.

func MT5Magic

func MT5Magic(magic int64, comment string) int64

MT5Magic returns the magic number of the orders and positions of an agent on MT5: magic when above 0 (-mt5-magic), else a stable hash of its comment (see MT5Comment), a positive int32, so that the agent finds its positions again after a restart, and two agents of comments of their own keep theirs apart.

func MT5Pairs

func MT5Pairs(value string) []string

MT5Pairs returns the pairs of -pair, separated by ; or by ,, as the agents read them.

func SameMT5Bridge

func SameMT5Bridge(a, b string) bool

SameMT5Bridge reports whether the URLs a and b reach the same bridge, a process listening at a host and a port: the same host, case aside, or two names of the loopback, and the same port, the one of the scheme when missing, whatever their paths. Two names of a host, eg: a name and its address, can't be told apart.

func SameWindow

func SameWindow(a, b ui.TradingWindow) bool

SameWindow reports whether a and b are the same window: the same times, agents and assets (in any order) and actions at its end.

func SortedWindows

func SortedWindows(windows []ui.TradingWindow) []ui.TradingWindow

SortedWindows returns windows in the order of the day, by their start.

func TradingWindow

func TradingWindow(start, end string, at time.Time, zone *time.Location) (open bool, next time.Time)

TradingWindow returns whether at is inside the window of the trading hours from start to end (HH:MM of zone, crossing midnight when start is after end; the end itself outside), and its next change: the end while inside, the start else. The controller applies it to the agents, the backtests to their candles.

func TradingWindows

func TradingWindows(windows []ui.TradingWindow, at time.Time, zone *time.Location) (open, upcoming int,
	next time.Time)

TradingWindows returns the window of windows (see TradingWindow, each of zone) at is inside (open, -1 for none), the window that opens next while in none (upcoming, -1 while open or without windows), and the next change: the end of the window open, else the start of the next one, today or tomorrow.

func ValidClock

func ValidClock(text string) bool

ValidClock reports whether text is a time of the trading hours, HH:MM from 00:00 to 23:59.

func WindowAllows

func WindowAllows(w ui.TradingWindow, name string) bool

WindowAllows reports whether the window w lets the agent of name open positions in it: any agent while it names none.

func WindowEnd

func WindowEnd(w ui.TradingWindow, openedAt time.Time, zone *time.Location) time.Time

WindowEnd returns when the window w, opened at openedAt, ends: its end on the day it opened (the next day for a window crossing midnight opened before it).

func WindowLabel

func WindowLabel(w ui.TradingWindow) string

WindowLabel returns the window w in words, eg: 08:00–10:00.

func WindowPairsReason

func WindowPairsReason(w ui.TradingWindow) string

WindowPairsReason returns why an entry is refused outside the assets of the window w, eg: Janela 08:00–10:00 só para os ativos XAUUSDm, BTCUSDm.

func WindowsFor

func WindowsFor(windows []ui.TradingWindow, name string) []ui.TradingWindow

WindowsFor returns the windows of windows the agent of name may open positions in, without their agents.

func WindowsProblem

func WindowsProblem(windows []ui.TradingWindow) string

WindowsProblem returns why windows can't be trading hours, in Portuguese, "" when they can: MaxTradingWindows at most, each start and end HH:MM, the start before the end (a window never crossing midnight), and none overlapping nor touching another (one then).

Types

type Account

type Account struct {
	BridgeURL   string  `json:"bridge_url"`
	BridgeToken string  `json:"bridge_token,omitempty"`
	Magic       *int64  `json:"magic,omitempty"`
	Comment     *string `json:"comment,omitempty"`
	RealAllowed bool    `json:"real_allowed"`
}

Account is the trading account of an agent: the bridge of MT5, the token of the bridge, and what tells its orders apart there, the magic number and the comment, their defaults when nil.

type Attachment

type Attachment struct {
	MediaType string `json:"media_type"`
	Data      []byte `json:"data"`
}

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

type BacktestConfig

type BacktestConfig struct {
	// From and To bound the trading period, Unix seconds: the entries are
	// refused before From, the run ends with the last candle before To.
	From int64 `json:"from"`
	To   int64 `json:"to"`

	// Balance is the starting balance, in the quote currency of the pairs
	// (a simulation: the money of the account isn't converted).
	Balance float64 `json:"balance"`
	// Leverage, 1 for none, is the leverage of the margin: a position commits
	// its notional over it, see wallet.
	Leverage float64 `json:"leverage"`
	// Fee is charged on the notional of every fill, a share of it.
	Fee float64 `json:"fee"`
	// SlippagePoints worsens the fills at the market and of the stops, in
	// points of each symbol; SpreadPoints is the spread of the candles without
	// one of their own (their spread column), in points too.
	SlippagePoints float64 `json:"slippage_points"`
	SpreadPoints   float64 `json:"spread_points"`
	// Conservative assumes the worst of what a candle can't tell, see
	// exchange.PaperExecution; GapFills fills the stops at the open of a
	// candle opening beyond them.
	Conservative bool `json:"conservative"`
	GapFills     bool `json:"gap_fills"`

	// Symbols are the specs of the symbols, by pair, see BacktestSymbol.
	Symbols map[string]BacktestSymbol `json:"symbols"`

	// Protection is the breakeven and trailing stop of the agent, nil for
	// none; DailyLoss and DailyGain its daily limits on the result of the day
	// (realized plus open, from midnight of America/Belem), in the quote
	// currency, 0 for none.
	Protection *ui.ProtectionSettings `json:"protection,omitempty"`
	DailyLoss  float64                `json:"daily_loss,omitempty"`
	DailyGain  float64                `json:"daily_gain,omitempty"`
	// Hours are the trading hours of the run, nil for none, see
	// ui.BacktestHours and TradingWindow.
	Hours *ui.BacktestHours `json:"hours,omitempty"`

	// LLMMaxCalls and LLMMaxCost bound the calls of the language model of an
	// LLM agent and their cost, in dollars, estimated with LLMPriceInput and
	// LLMPriceOutput, dollars per million tokens (0: the cost unknown, the
	// calls bound it): reached, the run stops, budget_exhausted.
	LLMMaxCalls    int     `json:"llm_max_calls,omitempty"`
	LLMMaxCost     float64 `json:"llm_max_cost,omitempty"`
	LLMPriceInput  float64 `json:"llm_price_input,omitempty"`
	LLMPriceOutput float64 `json:"llm_price_output,omitempty"`

	// Agent is the name of the agent backtested, for what the run records,
	// eg: the samples of its -meta-record; "" for none. Run is the id of the
	// run at the controller (0 for none) and Segment its segment of the
	// period (fit or validation, "" for none), written in those samples too,
	// so that a training tells the runs and their segments apart.
	Agent   string `json:"agent,omitempty"`
	Run     int64  `json:"run,omitempty"`
	Segment string `json:"segment,omitempty"`
	// References are the candles of the symbols the strategy reads but never
	// trades (see Warmup.References), by symbol: a CSV of the same timeframe
	// and period as the pairs, loaded in the feed of the run, never
	// subscribed nor traded.
	References map[string]string `json:"references,omitempty"`
	// Releases are the scheduled releases of the economic calendar of the
	// period, by pair (the ones of its currencies), for a strategy trading
	// around them (see Warmup.Releases): their times and importance, never a
	// value released; nil for none (the news off or unreadable).
	Releases map[string][]BacktestRelease `json:"releases,omitempty"`

	// Report is the file the report is written to; Progress prints the
	// progress on the standard error (PROGRESS done total).
	Report   string `json:"report"`
	Progress bool   `json:"progress"`
}

BacktestConfig is the backtest a run of an agent makes, read from the file of -backtest-config: its period (the candles before From warm the indicators up, no entry then), its money, its costs, its symbols, the protection and the daily limits of the agent, and where its report and progress go.

func ReadBacktestConfig

func ReadBacktestConfig(path string) (BacktestConfig, error)

ReadBacktestConfig reads the config of a backtest from path, validated.

func (*BacktestConfig) Validate

func (c *BacktestConfig) Validate() error

Validate returns why c can't run.

type BacktestOpen

type BacktestOpen struct {
	Pair     string  `json:"pair"`
	Side     string  `json:"side"`
	Quantity float64 `json:"quantity"`
	OpenedAt int64   `json:"opened_at"`
	Entry    float64 `json:"entry"`
	Mark     float64 `json:"mark"`
	Profit   float64 `json:"profit"`
}

BacktestOpen is a position open at the end of a backtest: valued at Mark, its exit at the market then (the bid less the slippage for a long, the ask plus it for a short), its Profit after the fees paid and the one of that exit; never in the realized result.

type BacktestPoint

type BacktestPoint struct {
	Time  int64   `json:"time"`
	Value float64 `json:"value"`
}

BacktestPoint is the equity at a time, Unix seconds.

type BacktestRelease

type BacktestRelease struct {
	Time       int64  `json:"time"`
	Currency   string `json:"currency"`
	Code       string `json:"code"`
	Name       string `json:"name"`
	Importance int    `json:"importance"`
	Timed      bool   `json:"timed"`
	Tentative  bool   `json:"tentative,omitempty"`
}

BacktestRelease is a scheduled release of the economic calendar a backtest hands its strategy: its time (Unix seconds, UTC), the currency of the event, its code (the MQL5 event_code) and name, its importance (0 none, 1 low, 2 medium, 3 high), and whether its time is exact (Timed: an all-day release has none). Tentative tells a release whose time the calendar knows only once it is released (tentative, or published without a time): the run tells it untimed, at the start of its day, until then, as the calendar did live.

type BacktestReport

type BacktestReport struct {
	Status      string          `json:"status"`
	Error       string          `json:"error,omitempty"`
	Currency    string          `json:"currency"`
	Pairs       []string        `json:"pairs"`
	Timeframe   string          `json:"timeframe"`
	From        int64           `json:"from"`
	To          int64           `json:"to"`
	DataFrom    int64           `json:"data_from,omitempty"`
	DataTo      int64           `json:"data_to,omitempty"`
	Candles     int             `json:"candles"`
	Processed   int             `json:"processed"`
	Assumptions BacktestConfig  `json:"assumptions"`
	Summary     BacktestSummary `json:"summary"`
	Trades      []BacktestTrade `json:"trades"`
	Open        []BacktestOpen  `json:"open"`
	Equity      []BacktestPoint `json:"equity"`
	Warnings    []string        `json:"warnings"`
	Extra       json.RawMessage `json:"extra,omitempty"`
}

BacktestReport is the result of a backtest: its status (see BacktestStatusSucceeded) and error, the money (in Currency, the quote of the pairs: a simulation), the period traded and the one of the candles read, the assumptions effective, the summary, the trades closed in the period, the positions open at its end (valued at the market, apart from the realized result), the equity, the warnings (eg: data missing, an order refused) and what the strategy adds (Extra, eg: the calls of an LLM).

type BacktestSummary

type BacktestSummary struct {
	InitialBalance  float64 `json:"initial_balance"`
	FinalEquity     float64 `json:"final_equity"`
	Realized        float64 `json:"realized"`
	Gross           float64 `json:"gross"`
	Fees            float64 `json:"fees"`
	OpenProfit      float64 `json:"open_profit"`
	Trades          int     `json:"trades"`
	MaxDrawdown     float64 `json:"max_drawdown"`
	MaxDrawdownPct  float64 `json:"max_drawdown_pct"`
	ProtectionMoves int     `json:"protection_moves"`
	Refused         int     `json:"refused"`
}

BacktestSummary sums a report up: the starting balance, the final equity (the open positions valued at the market), the result of the trades closed (Realized, after their fees; Gross before them; Fees), the result of the positions open at the end (OpenProfit), the most the equity fell from a peak (MaxDrawdown, and its share of the peak), the moves of the protection, the entries refused.

type BacktestSymbol

type BacktestSymbol struct {
	Point       float64 `json:"point"`
	VolumeStep  float64 `json:"volume_step"`
	VolumeMin   float64 `json:"volume_min"`
	SpreadPoint float64 `json:"spread_points,omitempty"` // the fallback spread of the symbol, else BacktestConfig.SpreadPoints
}

BacktestSymbol is what a backtest knows of a symbol: the price of a point (the unit of the spread and of the slippage), the volume step and the least volume of its orders, in units of the asset (a lot times the contract size), 0 for none.

type BacktestTrade

type BacktestTrade struct {
	Pair        string  `json:"pair"`
	Side        string  `json:"side"`
	Quantity    float64 `json:"quantity"`
	OpenedAt    int64   `json:"opened_at"`
	ClosedAt    int64   `json:"closed_at"`
	Entry       float64 `json:"entry"`
	Exit        float64 `json:"exit"`
	Gross       float64 `json:"gross"`
	Fees        float64 `json:"fees"`
	Net         float64 `json:"net"`
	EntryReason string  `json:"entry_reason"`
	ExitReason  string  `json:"exit_reason"`
}

BacktestTrade is a position opened and closed in the period of a backtest, from flat back to flat (a reversal closes it, opening another): its side, its most units held, the average prices of its entries and of its exits (the spread and the slippage in them), its result before the fees (Gross), the fees and Net, the reasons of its entry and of its exit (see BacktestReasonMarket).

type Config

type Config struct {
	ID              int64             `json:"id"`
	Name            string            `json:"name"`
	Kind            string            `json:"kind"`
	Mode            string            `json:"mode"`
	APIAddress      string            `json:"api_address"`
	TradePanel      bool              `json:"trade_panel"`
	TelegramControl bool              `json:"telegram_control"`
	Reanalysis      bool              `json:"reanalysis"`
	Entries                           // the entries blocked by the supervisor or the dashboard, if any
	Protection                        // the protection of the positions, see Protection
	Params          map[string]string `json:"params"`
	Account         *Account          `json:"account,omitempty"`
	LLM             *LLM              `json:"llm,omitempty"`
	Prompt          *Prompt           `json:"prompt,omitempty"` // of an LLM agent, nil for its default one
	News            *News             `json:"news,omitempty"`   // see News
	// BotStopped tells that a user stopped the bot of the agent (Parar bot,
	// /stop) and never started it since: it starts stopped, see
	// remote.Agent.KeepBotStopped
	BotStopped bool `json:"bot_stopped,omitempty"`
}

Config are the settings of an agent, the answer of GET /config: its Params are its other flags by name, only the ones set. Reanalysis allows the reanalysis of an LLM agent, apart from its channels. The entries of the agent are the ones of its runtime as it starts, see Entries. The secrets are the ones of the agent, never of another.

func (Config) Args

func (cfg Config) Args() []string

Args returns the flags of the settings of the agent, the ones set only, as its command line gave them: its params, then its columns, which the controller keeps apart. Its secrets are never among them, see Config.

func (Config) CheckMT5Book

func (c Config) CheckMT5Book(book MT5Book) error

CheckMT5Book fails when book, the one the agent of c trades as it read its flags, isn't the one of its settings (see Config.MT5Book), the one the store and the controller keep apart from the books of the other agents: the agent would trade positions they don't know of.

func (Config) MT5Book

func (c Config) MT5Book() MT5Book

MT5Book returns the book of the agent of c, see NewMT5Book.

type DecisionLink struct {
	OrderID    int64  `json:"order_id"`
	DecisionID string `json:"decision_id"`
}

DecisionLink is an order and the decision that placed it, of GET /decision-links.

type DecisionRecord

type DecisionRecord struct {
	Decision    ui.Decision  `json:"decision"`
	Attachments []Attachment `json:"attachments,omitempty"`
}

DecisionRecord is a decision of an LLM agent to keep, with its attachments.

type Entries

type Entries struct {
	EntriesBlocked  bool     `json:"entries_blocked,omitempty"`
	EntriesReason   string   `json:"entries_reason,omitempty"`
	EntriesRevision int64    `json:"entries_revision,omitempty"`
	EntriesPairs    []string `json:"entries_pairs,omitempty"`
	PairsReason     string   `json:"pairs_reason,omitempty"`
	Exposure        bool     `json:"exposure,omitempty"`
}

Entries tells whether the entries of an agent are blocked, by the supervisor of the controller or from the dashboard, and why: the agent then opens no position, nor adds to one, and only reduces the ones it holds (see order.Controller.BlockEntries). Revision grows with every block and every allowance, so that an agent never applies an older one after a newer, eg: a runtime read before: 0 for an agent never blocked. EntriesPairs, while set, are the only assets the agent may open positions on (the window of the trading hours open allowing them only), PairsReason why: its other entries refused by its strategy (see PairGate), at the same revision. Exposure tells the exposure limit of the agents on: each entry claimed of the controller first (see ExposureClaim).

type ExposureAnswer

type ExposureAnswer struct {
	Granted bool   `json:"granted"`
	Reason  string `json:"reason,omitempty"`
}

ExposureAnswer answers an ExposureClaim: Granted, the entry may go (its place held a while for the agent); else why not.

type ExposureClaim

type ExposureClaim struct {
	Pair string `json:"pair"`
	Side string `json:"side"`
}

ExposureClaim is the payload of POST ExposurePath: an entry the agent is about to send, on Pair, on Side (BUY or SELL), claimed against the exposure limit of the agents (see ui.ExposureSettings).

type JournalRecord

type JournalRecord 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"`
}

JournalRecord is a call of an LLM agent to its model, with its whole context: Input and Decision as the agent marshals them, its ID the one of the decision kept of it.

type LLM

type LLM struct {
	Provider        string            `json:"provider"`
	Model           string            `json:"model"`
	APIKey          string            `json:"api_key,omitempty"`
	BaseURL         string            `json:"base_url,omitempty"`
	ReasoningEffort string            `json:"reasoning_effort,omitempty"`
	MaxTokens       int               `json:"max_tokens,omitempty"`
	Params          map[string]string `json:"params"`
}

LLM is the language model of an LLM agent: its Params are its other flags, -llm-*, -calendar-* and -news-*, by name.

type MT5Book

type MT5Book struct {
	Bridge  string
	Magic   int64
	Comment string
	Pairs   []string
}

MT5Book is what an agent trades on MT5: the bridge of the terminal, the magic number of its orders and positions, the comment it is a hash of by default, and the pairs. Two agents of overlapping books (see Overlaps) would trade the positions of each other.

func NewMT5Book

func NewMT5Book(kind string, params map[string]string, account *Account) MT5Book

NewMT5Book returns the book of an agent of kind as the agent reads it from its command line (see remote.Agent.Args): the fields of its account, nil for none, over its params (its flags by name, the ones of its language model included), over the defaults of the flags: the bridge exchange.MT5DefaultBaseURL, the comment of MT5Comment, of the param strategy else of the strategy of the kind (llm for an LLM agent), its hash for the magic number (see MT5Magic), and the pairs of the param pair, else DefaultPair.

func (MT5Book) Common

func (b MT5Book) Common(o MT5Book) []string

Common returns the pairs of b that o trades too, case aside, the ones of both when either has none known.

func (MT5Book) Overlaps

func (b MT5Book) Overlaps(o MT5Book) bool

Overlaps reports whether the books b and o share positions: the same bridge (see SameMT5Bridge), the same magic number and a pair in common, case aside, or no pair known.

type News

type News struct {
	Enabled         bool   `json:"enabled"`
	URL             string `json:"url,omitempty"`
	Token           string `json:"token,omitempty"`
	BlockBefore     int    `json:"block_before,omitempty"`
	BlockAfter      int    `json:"block_after,omitempty"`
	BlockImportance string `json:"block_importance,omitempty"`
}

News is the news feature of all the agents, set on the dashboard (the tab Notícias): on or off; the MCP server of the economic calendar (URL) and its token, shared by the agents; 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): inside it, an agent opens no position, its pending entries canceled and its positions closed as it starts. Every agent gets it at its start and in its runtime, applied while it runs: off, it reads no calendar and blocks nothing.

type OrderIDs

type OrderIDs struct {
	First int64 `json:"first"`
	Last  int64 `json:"last"`
}

OrderIDs is a range of order IDs leased to an agent, First to Last, never leased again: the IDs of its next orders.

type OrderIDsRequest

type OrderIDsRequest struct {
	Count int64 `json:"count"`
}

OrderIDsRequest is the payload of POST /order-ids: how many order IDs the agent leases.

type OutboxError

type OutboxError struct {
	Index int    `json:"index"`
	Error string `json:"error"`
}

OutboxError answers POST /outbox with 422: the record at Index is refused, for good, none written.

type OutboxRequest

type OutboxRequest struct {
	Records  []Record  `json:"records"`
	Pending  int       `json:"pending,omitempty"`
	NextAt   time.Time `json:"next_at,omitzero"`
	SetApart int       `json:"set_apart,omitempty"`
	Held     int       `json:"held,omitempty"`
}

OutboxRequest is the payload of POST /outbox: records in the order of their Seq, written in a single transaction. What the dashboard tells of the outbox of the agent: Pending are the records of the outbox not sent yet, the ones of the request included, and NextAt when the first of them after the ones of the request was added, zero for none; SetApart are the records the controller refused for good, kept apart in it, and Held the ones it failed again and again alone while it wrote the next ones of their kind, held apart in it, sent again now and then. A record held sent again is a request alone, counted among the ones not sent.

POST /outbox/check takes one too and answers as POST /outbox would, nothing written: the agent checks with it that the controller writes the records after one it fails to write again and again, before holding that one apart.

type OutboxResponse

type OutboxResponse struct {
	Acked uint64 `json:"acked"`
}

OutboxResponse answers POST /outbox: the records written, up to Acked.

type PairGate

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

PairGate tells the assets an agent may open positions on now: all of them, or only the ones of the window of the trading hours open (see Entries.EntriesPairs), set by the controller (or the backtest) and asked by the strategy of the agent before each entry. Safe for concurrent use; the zero value allows every asset.

func (*PairGate) Allows

func (g *PairGate) Allows(pair string) (bool, string)

Allows reports whether an entry on pair is allowed now, and why not.

func (*PairGate) Set

func (g *PairGate) Set(revision int64, pairs []string, reason string) bool

Set sets the assets of the gate at revision (nil for all of them) and why, an older revision ignored: whether it was taken.

type Prompt

type Prompt struct {
	PromptRef
	Content string `json:"content"`
}

Prompt is a prompt of the database with its content, the answer of GET /prompt: the strategy of an LLM agent, its header lines included.

type PromptRef

type PromptRef struct {
	ID      int64  `json:"id"`
	Name    string `json:"name"`
	Version int    `json:"version"`
}

PromptRef names a version of a prompt of the database.

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 LLM agent was asked to switch to, and how it went: applied, or refused with Error, the previous one kept.

type Protection

type Protection struct {
	ProtectionSettings *ui.ProtectionSettings `json:"protection_settings,omitempty"`
	ProtectionArms     []ui.ProtectionArm     `json:"protection_arms,omitempty"`
	DailyStops         []ui.DailyStop         `json:"daily_stops,omitempty"`
}

Protection is the protection of the open positions of an agent (breakeven, trailing stop), applied live, without a restart: its settings, nil when off, and the arms of the XTrader AI on its open positions, see ui.ProtectionArm.

DailyStops are the stop losses the daily loss limits ask of its open positions, see ui.DailyStop: kept across a restart of the agent, its stop guard on while it has one.

type Record

type Record struct {
	Seq     uint64          `json:"seq"`
	Kind    string          `json:"kind"`
	Key     string          `json:"key"`
	At      time.Time       `json:"at,omitzero"`
	Payload json.RawMessage `json:"payload"`
}

Record is a record an agent keeps through the controller, of its outbox. Seq orders the records of the outbox while it holds them, nothing more: it starts again from 1 once the outbox was sent whole and the agent starts again, and the controller keeps none of it, answering only the last one written (see OutboxResponse). Key names what the record writes for the logs, eg: the ID of an order. The controller writes a record by the keys of its payload, never by Seq or Key: the ID of an order, of a decision or of an entry of the journal, the prompt status of the agent, the pair and the fill after which a position was discarded (kept once). So a record sent again writes the same, and a later record of the same order, decision or prompt status replaces it, an order never going back (see model.Order.Supersedes). At is when the agent added it, zero for a record of a version before it.

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, of GET /journal/memory: the candle it was taken on, when (the time of its entry; zero from a controller of a version before it), and its answer.

type Runtime

type Runtime struct {
	Version         int64      `json:"version"`
	TradePanel      bool       `json:"trade_panel"`
	TelegramControl bool       `json:"telegram_control"`
	Reanalysis      bool       `json:"reanalysis"`
	Entries                    // the entries blocked by the supervisor or the dashboard, if any
	Protection                 // the protection of the positions, see Protection
	Prompt          *PromptRef `json:"prompt,omitempty"`
	News            *News      `json:"news,omitempty"` // see News
}

Runtime is what an agent applies while it runs, the answer of GET /runtime: the channels of its control panel, its entries (see Entries), and of an LLM agent the switch of its reanalysis, its prompt, nil for its default one, and the news (see News). Version changes with any of them: GET /runtime?wait=25s with If-None-Match: <version> waits for a change.

type Warmup

type Warmup struct {
	Timeframe  string   `json:"timeframe"`
	Candles    int      `json:"candles"`
	References []string `json:"references,omitempty"`
	Releases   bool     `json:"releases,omitempty"`
}

Warmup is the warmup of the strategy of an agent, as -print-warmup prints it: the candles of Timeframe its indicators need before it trades (the engine hands it a candle only once it holds that many); the symbols it reads but never trades (References, eg: the one of -intermarket-symbol), whose candles a backtest reads too; and whether it trades around the releases of the economic calendar (Releases), which a backtest reads then.

Jump to

Keyboard shortcuts

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