Documentation
¶
Overview ¶
Package llm trades with a language model as its analyst. On every candle close the Trader sends the market context of the pair to a Provider, OpenAI or Anthropic: its last candles, its indicators, its prices and the position held. The model answers with a structured Decision: WAIT, ENTER_LONG, ENTER_SHORT, HOLD, EXIT, MODIFY_SL or MODIFY_TP, with its entry, stop loss, take profit, confidence and reason.
The model never trades. The Trader validates its decision against the context, then hands it to the broker of the bot as the other strategies do: an entry is a market order with its stop loss and take profit at the broker (service.ProtectionBroker), an exit a market order, a new level a leg moved with UpdateProtection. An answer that fails, or that is not a valid decision, trades nothing.
Index ¶
- Constants
- Variables
- func CalendarCurrencies(pair string) []string
- func CheckPrompt(strategy string) error
- func JournalDecisions(data []byte, orders func(pair string) []model.Order) []ui.Decision
- func KeyEnv(name string) string
- func LocalZone() *time.Location
- func NormalizeIndicator(spec string) string
- func ProbeNews(ctx context.Context, url, token string) error
- func ReadStrategy(path string) (string, error)
- func StrategyContext(strategy string) ([]string, error)
- func StrategyDailyLimits(strategy string) (gain, loss float64, currency string, err error)
- func StrategyDrawings(strategy string) (bool, error)
- func StrategyIndicators(strategy string) (groups []string, ok bool)
- func StrategyPendingOrders(strategy string) ([]string, error)
- func StrategyTakeProfitOptional(strategy string) bool
- func StrategyWithoutTakeProfit(strategy string) bool
- type APIError
- type Action
- type Anthropic
- type Attachment
- type Box
- type Calendar
- type CalendarContext
- type CandleInProgress
- type CandleShape
- type CandleSource
- type Candles
- type Chat
- type ChatAnswer
- type ChatMessage
- type ChatStreamer
- type Config
- type Correlated
- type DailyHistory
- type DailyLimits
- type DailyOrder
- type DailyPosition
- type DailyResult
- type DealingRange
- type Decision
- type DecisionStore
- type Drawing
- type Event
- type FairValueGap
- type Frame
- type Importance
- type Input
- type Instrument
- type Journal
- type JournalEntry
- type Level
- type LiquiditySweep
- type MCPCalendar
- type MCPOption
- type Memory
- type MemoryDecisions
- func (m *MemoryDecisions) Attachment(id string, index int) (string, []byte, error)
- func (m *MemoryDecisions) Decision(id string) (ui.Decision, bool, error)
- func (m *MemoryDecisions) Decisions(pair string, limit int) ([]ui.Decision, error)
- func (m *MemoryDecisions) Load(decisions []ui.Decision, placed map[int64]string)
- func (m *MemoryDecisions) OrderDecision(orderID int64) string
- func (m *MemoryDecisions) Save(d ui.Decision, attachments []Attachment) error
- type NewsConfig
- type NewsSwitch
- func (n *NewsSwitch) Blocking(events []Event, at time.Time) (Event, bool)
- func (n *NewsSwitch) Enabled() bool
- func (n *NewsSwitch) Events(ctx context.Context, currencies []string, from, to time.Time) ([]Event, error)
- func (n *NewsSwitch) Set(config NewsConfig) (switched, changed bool)
- func (n *NewsSwitch) String() string
- func (n *NewsSwitch) Window() (before, after time.Duration, importance Importance)
- type Note
- type OpenAI
- type Option
- type OrderBlock
- type PastDecision
- type PastTrade
- type PendingOrder
- type Position
- type Prompt
- type PromptOverrides
- type PromptReporter
- type PromptSource
- type Provider
- type ProviderOption
- func WithBaseURL(baseURL string) ProviderOption
- func WithHTTPClient(httpClient *http.Client) ProviderOption
- func WithMaxTokens(tokens int) ProviderOption
- func WithReasoningEffort(effort string) ProviderOption
- func WithStrategy(strategy string) ProviderOption
- func WithUsageHook(hook func(Usage)) ProviderOption
- type RecordedCall
- type Recorder
- func (r *Recorder) Analyze(ctx context.Context, input Input) (Decision, error)
- func (r *Recorder) AnalyzeWith(ctx context.Context, system string, input Input) (Decision, error)
- func (r *Recorder) Report(model string, context []string) RecorderReport
- func (r *Recorder) String() string
- func (r *Recorder) Usage(usage Usage)
- type RecorderReport
- type Reference
- type Remembered
- type Rules
- type SMC
- type Session
- type Structure
- type StructureBreak
- type Summary
- type Swing
- type SystemPromptProvider
- type TimeMode
- type ToolCall
- type ToolSpec
- type Trader
- func (t *Trader) Attachment(id string, index int) (string, []byte, error)
- func (t *Trader) ChartAnalysis(pair string) (ui.Analysis, bool)
- func (t *Trader) ChartLevels(pair string) []ui.Level
- func (t *Trader) CheckPromptAccount() error
- func (t *Trader) Decision(id string) (ui.Decision, bool, error)
- func (t *Trader) Decisions(pair string, limit int) ([]ui.Decision, error)
- func (t *Trader) Indicators(df *model.Dataframe) []strategy.ChartIndicator
- func (t *Trader) LLM() string
- func (t *Trader) ListenDecisions(listener func(ui.Decision))
- func (t *Trader) News() *NewsSwitch
- func (t *Trader) OnCandle(df *model.Dataframe, broker service.Broker)
- func (t *Trader) OnPartialCandle(df *model.Dataframe, broker service.Broker)
- func (t *Trader) OrderDecision(orderID int64) string
- func (t *Trader) Prompt() ui.DecisionPrompt
- func (t *Trader) Reanalyze(pair string, channel ui.Channel, note string) (ui.ReanalysisResponse, error)
- func (t *Trader) SetAccountReporter(reporter service.AccountReporter)
- func (t *Trader) SetClock(now func() time.Time)
- func (t *Trader) SetDecisionStore(store DecisionStore)
- func (t *Trader) SetFeeder(feeder CandleSource)
- func (t *Trader) SetJournal(journal Journal) error
- func (t *Trader) SetNews(config NewsConfig) (switched, changed bool)
- func (t *Trader) SetNotifier(notify func(message string))
- func (t *Trader) SetOrderSource(orders func(pair string) ([]model.Order, error))
- func (t *Trader) SetPromptSource(source PromptSource) error
- func (t *Trader) Stop()
- func (t *Trader) Timeframe() string
- func (t *Trader) WarmupPeriod() int
- type Usage
- type Zone
Constants ¶
const ( ChatUser = "user" // a message of the user ChatAssistant = "assistant" // an answer of the model, with its calls of tools ChatTool = "tool" // the result of a call of a tool, to the model )
The roles of the messages of a conversation of a Chat.
const ( PendingLimit = "limit" PendingStop = "stop" )
The types of the pending orders, see Config.PendingOrders.
const ( LevelSupport = "support" LevelResistance = "resistance" )
The kinds of a Level.
const ( TriggerCandle = "candle" TriggerStart = "start" TriggerReanalysis = "reanalysis" TriggerInterval = "interval" )
The triggers of a decision, see ui.Decision: at the close of a candle, on the first candle after the start, asked again between the closes (see Trader.Reanalyze), or on the consult interval between the closes (see Config.ConsultInterval).
const ( OutcomeApplied = "applied" OutcomeIgnored = "ignored" OutcomeRefused = "refused" OutcomeFailed = "failed" OutcomeSkipped = "skipped" )
The outcomes of a decision, see ui.Decision: applied (WAIT and HOLD included), ignored under the min confidence, refused by the rules of its context, or failed without a decision; skipped, an analysis that didn't ask the model, its Reason the code of why (one of the Skip constants) and its Error the detail.
const ( SkipPosition = "position" // the position unread from the broker SkipCloseRetry = "close_retry" // a close that failed, being retried SkipProtection = "protection" // the broker can't place the legs with the order SkipDailyLimit = "daily_limit" // the entries refused by a daily limit SkipNews = "news" // the entries refused around a release SkipSize = "size" // no position fits the balance and the sizing SkipSpread = "spread" // the spread wider than allowed SkipSetup = "setup" // no trend for the setup SkipDirection = "direction" // no entry the direction of the positions allows SkipHigherTrend = "higher_trend" // no trend of the higher timeframes, one required SkipAgainstTrend = "against_trend" // the entries allowed all against the higher trend SkipRateLimited = "rate_limited" // the provider rate limited SkipPendingCancel = "pending_cancel" // the cancel of the pending order sent, its outcome awaited )
The codes of why an analysis didn't ask the model, see OutcomeSkipped.
const ( DrawingZone = ui.DrawingZone DrawingSupply = ui.DrawingSupply DrawingDemand = ui.DrawingDemand DrawingLevel = ui.DrawingLevel DrawingMarker = ui.DrawingMarker BiasBullish = ui.BiasBullish BiasBearish = ui.BiasBearish BiasNeutral = ui.BiasNeutral ZoneFresh = ui.ZoneFresh ZoneTested = ui.ZoneTested ZoneBroken = ui.ZoneBroken )
The kinds, the biases and the states of the zones of a Drawing, see ui.Drawing.
const ( SetupFree = "free" SetupTrendPullback = "trend_pullback" )
The setups of Config.Setup.
const ( CalendarDisabled = "disabled" CalendarMissingToken = "missing_token" )
The reasons a calendar couldn't be read, told to the model (see CalendarContext.Status) and in the logs: the news feature off, its token missing, the token refused by the server, or the server unavailable. In none of them is the absence of releases a calm market.
const ( PlacedByModel = "model" PlacedByTrader = "trader" )
Who placed a pending order, see PendingOrder.PlacedBy: the model itself, or someone else, eg: the trader from the dashboard, the order found on the pair.
const ( ProviderOpenAI = "openai" ProviderAnthropic = "anthropic" )
The providers of NewProvider.
const ( OpenAIKeyEnv = "OPENAI_API_KEY" AnthropicKeyEnv = "ANTHROPIC_API_KEY" )
The environment variables of the API keys of the providers.
const ( ReanalysisQueued = "queued" ReanalysisRunning = "running" )
The statuses of a reanalysis, see ui.ReanalysisResponse.
const CalendarMissingServer = "missing_server"
CalendarMissingServer is the reason of a calendar not read for want of the address of its MCP server, see CalendarDisabled.
const ContextSMC = "smc"
ContextSMC is the part of the context of the structure in smart money concepts, see StrategyContext and SMC.
const DefaultMaxTokens = 4096
DefaultMaxTokens caps the tokens of an answer without WithMaxTokens, the reasoning of the models that reason included: a decision takes a few hundred, a model that reasons may spend them all thinking on a longer task.
Variables ¶
var ( // ErrInvalidResponse is returned for an answer of a provider that is not a // decision: not JSON, a field missing or unknown, a value out of the // schema, a refusal or an answer cut short. ErrInvalidResponse = errors.New("llm: invalid response") // ErrInvalidDecision is returned for a decision that breaks the rules of // its context, see Decision.Validate. ErrInvalidDecision = errors.New("llm: invalid decision") )
var ( // ErrTimeout is returned when the answer doesn't come in time: the // deadline of the context or the timeout of the HTTP client. ErrTimeout = errors.New("llm: timeout") // ErrRateLimited is returned for an answer HTTP 429: too many requests or // tokens, or the quota of the account spent. ErrRateLimited = errors.New("llm: rate limited") // answers HTTP 5xx, eg: 529 when Anthropic is overloaded. ErrUnavailable = errors.New("llm: provider unavailable") )
var Actions = []Action{ActionWait, ActionEnterLong, ActionEnterShort, ActionHold, ActionExit, ActionModifySL, ActionModifyTP}
Actions are the actions of a Decision, in the order of the schema.
var ErrBudgetExhausted = errors.New("the budget of the backtest is exhausted")
ErrBudgetExhausted is the error of a call of a backtest past its budget, see Recorder.
ErrMCPUnauthorized is the error of a call the MCP server refused for its credential (HTTP 401 or 403): the token missing on the server's side, wrong or revoked, never the service unavailable.
var ErrNewsDisabled = errors.New("llm: the news feature is off")
ErrNewsDisabled is the error of a read of the calendar while the news feature is off for all the agents: nothing was asked to the server.
var ErrNewsNoServer = errors.New("llm: the address of the MCP server of the news is missing")
ErrNewsNoServer is the error of a read of the calendar without the address of the MCP server: nothing was asked.
var ErrNewsNoToken = errors.New("llm: the token of the MCP server of the news is missing")
ErrNewsNoToken is the error of a read of the calendar without the token of the MCP server: nothing was asked to the server.
var ErrToolNotAllowed = errors.New("llm: MCP tool not allowed")
ErrToolNotAllowed is returned by the MCP client for a tool out of mcpAllowedTools.
var IndicatorGroups = []string{"ema", "sma", "rsi", "atr", "adx", "macd", "bb", "volume"}
IndicatorGroups are the groups of Config.Indicators: the fast and the slow EMAs, the SMA of the trend, the RSI, the ATR, the ADX with its DIs, the MACD with its signal and histogram, the Bollinger Bands, and the average volume.
var IndicatorKinds = []string{
"ema periods... (ema_<period>)",
"sma periods... (sma_<period>)",
"rsi period (rsi_<period>)",
"atr period [average] (atr_<period>, atr_<period>_sma_<average>)",
"adx period (adx_<period>, plus_di_<period>, minus_di_<period>)",
"macd fast slow signal (macd_<fast>_<slow>, macd_signal_<signal>, macd_histogram_<fast>_<slow>_<signal>)",
"bb period deviations (bb_upper_<period>_<deviations>, bb_middle_<period>, bb_lower_<period>_<deviations>)",
"volume period (volume_sma_<period>)",
"supertrend atr factor (10 3: supertrend_<atr>_<factor>, supertrend_side_<atr>_<factor>)",
"psar step max (0.02 0.2: psar_<step>_<max>, psar_side_<step>_<max>)",
"ichimoku tenkan kijun senkou (9 26 52: ichimoku_tenkan_<tenkan>, ichimoku_kijun_<kijun>, ichimoku_senkou_a, " +
"ichimoku_senkou_b_<senkou>)",
"stoch k smoothing d (14 3 3: stoch_k_<k>_<smoothing>, stoch_d_<d>)",
"donchian period (20: donchian_upper_<period>, donchian_lower_<period>)",
"keltner ema atr multiplier (20 10 2: keltner_upper_<ema>_<atr>_<multiplier>, keltner_middle_<ema>, " +
"keltner_lower_<ema>_<atr>_<multiplier>)",
"chandelier period multiplier (22 3: chandelier_stop_<period>_<multiplier>, chandelier_side_<period>_<multiplier>)",
"vwap anchor timezone (00:00 UTC: vwap)",
"roc period (10: roc_<period>)",
"range start end until timezone (range_high, range_low)",
}
IndicatorKinds describes the kinds of Config.Indicators with their parameters, their defaults in parentheses, and the series each one sends.
var PendingActions = []Action{ActionBuyLimit, ActionSellLimit, ActionBuyStop, ActionSellStop, ActionModifyPending, ActionCancelPending}
PendingActions are the actions of the pending orders, in the order of the schema, after Actions, for the prompts that place them (see Config.PendingOrders).
var PendingTypes = []string{PendingLimit, PendingStop}
PendingTypes are the types of the pending orders, in their order.
Functions ¶
func CalendarCurrencies ¶
CalendarCurrencies returns the currencies of the calendar of pair, eg: USD for XAUUSD, USD and EUR for EURUSD, none for a crypto quoted in USDT.
func CheckPrompt ¶
CheckPrompt fails on a strategy the model can't take: not UTF-8, or empty once its header lines are left out.
func JournalDecisions ¶
JournalDecisions returns the decisions of the lines of a journal, oldest first: the decisions of a bot of the versions before they were kept apart, each with the orders of its pair (of orders, read once a pair) it placed or moved, found by their time (see linkByTime), and its trigger told by its time when the entry has none (see journalTrigger). The lines of other versions are left out.
func KeyEnv ¶
KeyEnv returns the environment variable of the API key of the provider name, empty for an unknown one.
func LocalZone ¶
LocalZone returns the time zone of the agent by its name, eg: America/Belem rather than Local, for Config.DayZone and the time_zone of DailyHistory: the one of TZ, a name of the IANA database (eg: America/Belem) or the path of its file; without TZ, the one of the system, /etc/localtime, by the name of the file its link points to, else time.Local. An empty or unknown TZ is UTC, as it is for time.Local, the unknown one logged.
func NormalizeIndicator ¶
NormalizeIndicator returns an indicator of Config.Indicators with its kind in lower case and its parameters, eg: "ema 20 50" for "EMA+20+50", the time zones kept as they are.
func ProbeNews ¶
ProbeNews reads the calendar of the MCP server at url with token, the releases of USD in the next hour: nil when it answers, ErrNewsNoToken without a token, an error wrapping ErrMCPUnauthorized when it refuses the token, any other one when it is unavailable. For the test of the settings of the news on the dashboard.
func ReadStrategy ¶
ReadStrategy reads the strategy of the instructions from a file, eg: one of a prompt saved apart, for WithStrategy or WithPrompt. The lines starting with # at its top describe it and aren't sent to the model.
func StrategyContext ¶
StrategyContext returns the parts of the context the header of strategy adds to the one of every prompt, eg: smc for "# Context: smc" (see Config.SMC): none without the line; an unknown part fails.
func StrategyDailyLimits ¶
StrategyDailyLimits returns the daily limits the header of strategy declares, eg: "# Daily gain limit: 250 BRL" and "# Daily loss limit: 150 BRL" (see promptLines), for Config.DailyGain, Config.DailyLoss and Config.DailyCurrency: the gain and the loss of the realized result of each symbol in an operational day, 0 for none, in currency, the one of the account. A line it wouldn't read fails, rather than leaving a limit off, see checkDailyLines.
func StrategyDrawings ¶
StrategyDrawings reports whether the header of strategy asks the model to draw its analysis on the chart, "# Drawings: on", for Config.Drawings: off without the line or with "off"; another value fails.
func StrategyIndicators ¶
StrategyIndicators returns the indicators the header of strategy declares, eg: "# Indicators: atr, volume" or "# Indicators: ema 20 50, atr 14", for Config.Indicators; ok is false without the line: all the groups.
func StrategyPendingOrders ¶
StrategyPendingOrders returns the types of the pending orders the header of strategy lets the model place, for Config.PendingOrders, of PendingTypes in their order: eg: limit and stop for "# Pending orders: limit, stop". None without the line, or with "none"; an unknown type fails.
func StrategyTakeProfitOptional ¶
StrategyTakeProfitOptional reports whether the header of strategy lets the entries go without a take profit, "# Take profit: optional", for Config.TakeProfitOptional.
func StrategyWithoutTakeProfit ¶
StrategyWithoutTakeProfit reports whether the header of strategy leaves the take profit out of every entry, "# Take profit: none", for Config.NoTakeProfit.
Types ¶
type APIError ¶
type APIError struct {
Provider string // openai or anthropic
Status int // HTTP status
Type string // of the error, eg: rate_limit_error
Param string // the param of the request refused, eg: reasoning_effort
Message string // without the API key
RetryAfter time.Duration // the Retry-After of the answer, 0 without it
}
APIError is an error answer of the API of a provider. It wraps ErrRateLimited for HTTP 429 and ErrUnavailable for HTTP 5xx; the other 4xx, eg: 401 for an invalid API key, are errors of the request.
type Action ¶
type Action string
Action is what a Decision asks of the Trader.
const ( // ActionWait opens nothing: flat, without a clear opportunity. ActionWait Action = "WAIT" // ActionEnterLong buys at the market, the stop loss below the price and // the take profit above it. ActionEnterLong Action = "ENTER_LONG" // ActionEnterShort sells at the market, the stop loss above the price and // the take profit below it. ActionEnterShort Action = "ENTER_SHORT" // ActionHold keeps the position held as it is. ActionHold Action = "HOLD" // ActionExit closes the position held at the market. ActionExit Action = "EXIT" // ActionModifySL moves the stop loss of the position held. ActionModifySL Action = "MODIFY_SL" // ActionModifyTP moves the take profit of the position held. ActionModifyTP Action = "MODIFY_TP" // ActionBuyLimit places a pending buy at entry, below the ask, filled when // the price comes down to it, with its stop loss and take profit at the // broker, see Config.PendingOrders. ActionBuyLimit Action = "BUY_LIMIT" // ActionSellLimit places a pending sell at entry, above the bid, filled // when the price comes up to it. ActionSellLimit Action = "SELL_LIMIT" // ActionBuyStop places a pending buy at entry, above the ask, filled when // the price rises to it. ActionBuyStop Action = "BUY_STOP" // ActionSellStop places a pending sell at entry, below the bid, filled // when the price falls to it. ActionSellStop Action = "SELL_STOP" // ActionModifyPending moves the entry, the stop loss and the take profit // of the pending order waiting. ActionModifyPending Action = "MODIFY_PENDING" // ActionCancelPending cancels the pending order waiting. ActionCancelPending Action = "CANCEL_PENDING" )
type Anthropic ¶
type Anthropic struct {
// contains filtered or unexported fields
}
Anthropic is the Provider of the Claude models of Anthropic, through the Messages API. The answer is forced into a tool whose input schema is the one of a Decision: the model answers with the call of the tool, never with text. A model that refuses the forced call, eg: claude-opus-5-5, is left the tool, asked to answer with it, the forced call tried again each anthropicForcedRetry; its decision is then read from the text too when it answers without the tool, still through ParseDecision and Decision.Validate.
func NewAnthropic ¶
func NewAnthropic(model, apiKey string, options ...ProviderOption) (*Anthropic, error)
NewAnthropic creates the provider of Anthropic answering with model, eg: the one of -llm-model, authenticated with apiKey, eg: from ANTHROPIC_API_KEY.
func (*Anthropic) Analyze ¶
Analyze asks the model for the decision of the context. The answer is the input of the call of the tool of the decision or, the tool left to the model, the JSON of the decision in its text.
func (*Anthropic) AnalyzeWith ¶
AnalyzeWith asks the model for the decision of the context with the instructions system, see SystemPromptProvider.
func (Anthropic) String ¶
func (c Anthropic) String() string
String names the provider and its model for the logs, eg: anthropic claude-sonnet-5.
func (Anthropic) TodayUsage ¶
TodayUsage returns the tokens the provider used today, in UTC, and the count of its answers.
type Attachment ¶
Attachment is a file the provider returned with a decision, eg: an image, its media type and its content, kept with it, see DecisionStore.
type Box ¶
type Box struct {
Candles int `json:"candles"`
High number `json:"high"`
Low number `json:"low"`
WidthATR ratio `json:"width_atr"`
}
Box is the range of the last Candles candles, its width in ATR.
type Calendar ¶
type Calendar interface {
Events(ctx context.Context, currencies []string, from, to time.Time) ([]Event, error)
}
Calendar is a source of the economic calendar: the releases of the currencies between from and to, with their importance.
type CalendarContext ¶
type CalendarContext struct {
Available bool `json:"available"`
Status string `json:"status,omitempty"`
Events []calendarEvent `json:"events"`
}
CalendarContext is the economic calendar of a decision: the releases around the time of the analysis (now, live, the candle in progress included; else the close of the candle just closed), oldest first. Available is false when the calendar couldn't be read, so the model doesn't take the silence for a calm market, and Status tells why: the news off, the token missing or refused, the server unavailable (see CalendarDisabled).
type CandleInProgress ¶
type CandleInProgress struct {
Time time.Time `json:"time"`
Open number `json:"open"`
High number `json:"high"`
Low number `json:"low"`
Close number `json:"close"`
Volume number `json:"volume"`
}
CandleInProgress is the candle not closed yet of a reanalysis: its open time, and its prices and volume so far.
type CandleShape ¶
type CandleShape struct {
CandlesAgo int `json:"candles_ago"`
Direction string `json:"direction"` // up, down or flat
RangeATR ratio `json:"range_atr"`
BodyPct ratio `json:"body_pct"`
UpperWickPct ratio `json:"upper_wick_pct"`
LowerWickPct ratio `json:"lower_wick_pct"`
CloseInRange ratio `json:"close_in_range"`
Pattern string `json:"pattern,omitempty"`
}
CandleShape describes a candle, CandlesAgo before the last one: its direction, its range in ATR, its body and wicks in % of its range, where it closed in its range (0 at the low, 1 at the high), and its patterns.
type CandleSource ¶
type CandleSource interface {
CandlesByLimit(ctx context.Context, pair, period string, limit int) ([]model.Candle, error)
}
CandleSource is where the Trader reads the candles of the other timeframes of the pair and of the correlated markets, see SetFeeder: the Feeder of the exchange, whose CandlesByLimit returns the last complete candles.
type Candles ¶
Candles are the last candles of the context, oldest first, written as rows of candleColumns to save tokens.
func (Candles) MarshalJSON ¶
type Chat ¶
type Chat interface {
// Complete answers the conversation of messages with the instructions
// system, the tools offered to the model, none for text only.
Complete(ctx context.Context, system string, messages []ChatMessage, tools []ToolSpec) (ChatAnswer, error)
// String names the provider and its model, eg: openai gpt-5.
String() string
}
Chat is a language model behind the API of a provider, answering a conversation with text or with calls of the tools it is offered: the supervisor of the agents of the controller, eg. It shares the requests of the providers of the decisions (see Provider): the same retries, errors (ErrTimeout, ErrRateLimited, ErrUnavailable, *APIError) and API keys left out of them.
func NewChat ¶
func NewChat(name, model, apiKey string, options ...ProviderOption) (Chat, error)
NewChat creates the chat of the provider name, openai or anthropic, answering with model, authenticated with apiKey, with the options of the providers but WithStrategy, which it ignores: the instructions come with each conversation.
type ChatAnswer ¶
ChatAnswer is the answer of the model: its text and the calls of tools it asked for, the tokens of it, and whether it was cut at the max tokens.
type ChatMessage ¶
ChatMessage is a message of a conversation: of the user, of the model with the calls of tools it answered, or the result of a call of a tool, of the call of ToolCallID.
type ChatStreamer ¶
type ChatStreamer interface {
Stream(ctx context.Context, system string, messages []ChatMessage, tools []ToolSpec,
text func(piece string)) (ChatAnswer, error)
}
ChatStreamer is a Chat that answers as the model writes: Stream returns the answer Complete returns, calling text with the pieces of its text as they come, from the goroutine of the call. A stream cut halfway is an error, never sent again: its text was told already.
type Config ¶
type Config struct {
Timeframe string
// Candles is the window of the model: the last candles of the context.
// The warmup covers it, and the periods of the indicators.
Candles int
// Warmup is the candles the Trader keeps at least, whatever its prompt:
// the room of the prompts it switches to while it runs (see
// SetPromptSource), whose indicators may need a longer history than the
// ones of the prompt it starts with, which a bot running can't give. 0
// keeps what its first prompt needs.
Warmup int
// The indicators of the context, the last History values of each: the
// fast and slow EMAs, the SMA of the trend, the RSI, the ATR, the ADX
// with its DIs, the MACD, the Bollinger Bands of BBLen candles BBDev
// deviations wide, and the average of the volume.
EMAFastLen int // must be shorter than EMASlowLen
EMASlowLen int
TrendLen int
RSILen int
ATRLen int
ADXLen int
MACDFast int // must be shorter than MACDSlow
MACDSlow int
MACDSignal int
BBLen int
BBDev float64
VolumeLen int
History int
// MinConfidence ignores the decisions trading, all but WAIT and HOLD,
// with a lower confidence, from 0 to 1: but the ones reducing the risk of
// the position held that answer the note of a trader, who asked for them
// (see reducesRisk).
MinConfidence float64
// MaxEntryATR refuses the entries whose price is further from the close
// than that many ATR of ATRLen candles, as they are filled at the market,
// and MaxLevelATR the stop losses and take profits further from it. 0
// disables them.
MaxEntryATR float64
MaxLevelATR float64
// WidenStop lets MODIFY_SL move the stop loss away from the price, which
// adds risk to the position. Off, the stop loss only ever tightens.
WidenStop bool
// Language is the language of the reasons of the decisions, eg: pt-BR or
// en.
Language string
// Timeout bounds each decision: the request to the provider.
Timeout time.Duration
// DailyGain and DailyLoss are the daily limits of the result of each pair,
// in DailyCurrency, the one of the account, 0 for none: once the positions
// of a pair closed during the operational day (from the midnight of
// DayZone) made DailyGain, or lost DailyLoss, as the broker books them,
// costs included, the new entries on the pair are refused until the next
// day, in the reanalyses too; the positions held are managed as usual.
// Read from the header of the prompt, see StrategyDailyLimits, and applied
// with the results of SetAccountReporter only.
DailyGain, DailyLoss float64
DailyCurrency string
// DayZone is the time zone of the operational day of the daily limits,
// LocalZone (the TZ of the agent, by its name) when nil.
DayZone *time.Location
// ConsultInterval is the time between the consultations of the model
// about each pair, on a schedule of the clock (eg: 10m at :00, :10,
// :20...), 10s at least. Live, it is required and the only schedule of
// the model: each slot is asked on the first candle in progress of the
// pair in it (see Input.Scheduled), a slot on the close of a candle on the
// first one of the next candle, and the model is never asked at the close
// of a candle (see OnCandle), besides the start and the reanalyses. In a
// backtest, which has no candles in progress, the model is asked at the
// closes on the schedule, at each close when 0.
ConsultInterval time.Duration
// Direction, MinPositionValue, PositionFraction, Leverage and PositionSize
// work as in strategies.BracketConfig: the size of the entries, the
// decision giving their stop loss and take profit.
Direction strategies.RKDirection
MinPositionValue float64
PositionFraction float64
Leverage float64
PositionSize map[string]float64
// Setup is the setup the model trades. SetupTrendPullback only enters with
// the trend of the pair, Summary.Trend up or down (the close beyond the
// SMA of the trend and the fast EMA beyond the slow one, on the same
// side), on a pullback confirmed by momentum, as the instructions describe:
// the entries against the trend are left out of the allowed actions, and
// without a trend the model isn't asked. SetupFree, the default, lets the
// model weigh the context as it sees fit.
Setup string
// MinRiskReward refuses the entries whose reward is under that many times
// their risk, both net of the spread when the exchange sends it: a long is
// filled at the ask and closed at the bid. 0 disables it.
MinRiskReward float64
// MaxSpreadATR refuses the entries while the spread is wider than that
// many ATR of ATRLen candles: the market is too costly to enter. 0
// disables it, as does a spread unknown.
MaxSpreadATR float64
// MinStopATR refuses the entries whose stop loss leaves less room than
// that many ATR before it is hit (from the bid for a long, from the ask
// for a short): a stop inside the noise of the candles is hit by it. 0
// disables it. The moves of a stop loss held aren't bound by it.
MinStopATR float64
// HigherTrendFilter leaves out of the allowed actions the entries against
// the trend the higher timeframes of the context agree on (all of them
// up, or all down, see Frame.Trend): only longs under higher timeframes
// trending up. Without a trend they agree on, or without them (no feeder),
// it filters nothing.
HigherTrendFilter bool
// HigherTrendRequired makes that trend a condition of every entry, the
// filter of HigherTrendFilter the strict way: only the entry with the
// trend the higher timeframes agree on is allowed, and without one (they
// don't agree, their trend is mixed or unknown, or their candles are
// missing) none: flat, the model isn't asked.
HigherTrendRequired bool
// Live, trading on the candles of the market as they close, refuses to
// ask on a candle closed more than two periods ago: the history an
// exchange hands after a restart or an outage, to keep the indicators
// whole, would otherwise be traded at the market of now, each candle
// billed. Its indicators are updated. Not for a backtest, all history.
Live bool
// Indicators are the indicators drawn on the chart and sent to the model:
// groups of IndicatorGroups alone, eg: atr and volume for a strategy of
// pure chart analysis, or kinds of IndicatorKinds with their parameters,
// eg: "ema 20 50" or "supertrend 10 3" (see parseExtra); all the groups
// when empty. The rules of the code use theirs whatever this, eg: the ATR
// of the distances.
Indicators []string
// TakeProfitOptional lets the entries go without a take profit, the stop
// loss alone protecting the position, eg: the trailing stop of the
// Turtles: the model may answer a null take_profit, and the risk:reward
// of such an entry isn't checked.
TakeProfitOptional bool
// NoTakeProfit trades without any take profit: the entries go with the
// stop loss alone, moved with MODIFY_SL until it closes the position (or
// EXIT does), eg: a trend followed. The model answers a null take_profit,
// an entry with one is refused and MODIFY_TP isn't allowed; no
// risk:reward is checked, so MinRiskReward must be 0. Exclusive with
// TakeProfitOptional.
NoTakeProfit bool
// PendingOrders are the types of the pending entries the model may place,
// of PendingTypes: limit (BUY_LIMIT and SELL_LIMIT) and stop (BUY_STOP and
// SELL_STOP), with their stop loss and take profit at the broker (see
// service.ProtectionBroker), none when empty. Read from the header of the
// prompt, "# Pending orders: limit, stop" (see StrategyPendingOrders). A
// pending entry is an entry: allowed while flat, one at a time on a pair,
// under the rules of the entries (the daily limits, the news block, the
// spread, the setup, the direction, the higher trend), measured from its
// price; the model keeps it, moves it (MODIFY_PENDING) or cancels it
// (CANCEL_PENDING) at its next analyses, and the Trader cancels it once an
// entry of its type isn't allowed anymore, or a position is held on the
// pair. Filled, it is the position held.
PendingOrders []string
// PendingExpiry cancels a pending entry once that many candles closed
// since it was placed without its fill, 0 for never: the broker keeps it
// until it is canceled otherwise.
PendingExpiry int
// Drawings asks the model to draw on the chart the structures its
// analysis relies on (see Drawing), read from the header of the prompt,
// "# Drawings: on" (see StrategyDrawings).
Drawings bool
// SMC adds to the context the structure of the candles, and of the higher
// timeframes, in smart money concepts (see SMC), read from the header of
// the prompt, "# Context: smc" (see StrategyContext).
SMC bool
// StructureCandles are the candles the price structure of the context is
// computed on (see Structure), more than the Candles sent as rows: the
// levels of a longer history for a few tokens. 0 leaves it out.
StructureCandles int
// HigherTimeframes are the higher timeframes of the context, read with a
// feeder (see SetFeeder): nil for the ones of Timeframe (see
// defaultHigherTimeframes), empty for none. HigherCandles of each are
// sent as rows, their levels computed on frameCandles.
HigherTimeframes []string
HigherCandles int
// feeder on Timeframe, eg: USTECm, XAUUSDm and DXYm for BTCUSDm on MT5;
// a pair among its own is left out.
Correlated map[string][]string
// Memory are the last decisions and trades closed of the pair sent, the
// trades read from the order source (see SetOrderSource). 0 leaves it out.
Memory int
// TickVolume tells the model the volume of the candles is a tick volume,
// the count of the changes of the price (eg: the CFDs of MT5), not the
// volume traded.
TickVolume bool
// Calendar, when set, adds to the context the economic calendar of the
// currencies of the pair (CalendarCurrencies, else the ones of the pair,
// see calendarCurrencies): the releases of at least CalendarImportance
// from CalendarBack before the time of the analysis to CalendarAhead after
// it, that time now live (the candle in progress included), else the close
// of the candle. New entries are refused from NewsBlockBefore before a
// release of at least NewsBlockImportance to NewsBlockAfter after it,
// whatever the model answers (both 0: never), checked again when an entry
// is applied. A calendar that can't be read blocks nothing: the context
// tells the model it is unavailable, and why. A NewsSwitch switches it
// from the dashboard, see SetNews.
Calendar Calendar
CalendarCurrencies []string
CalendarAhead time.Duration
CalendarBack time.Duration
CalendarImportance Importance
NewsBlockBefore time.Duration
NewsBlockAfter time.Duration
NewsBlockImportance Importance
// PairGate, when set, tells the assets the agent may open positions on now
// (the window of the trading hours open): an entry on another refused when
// a decision is applied, as the daily limits and the news are
PairGate *agentapi.PairGate
// Claim, when set, claims an entry of a decision of the controller (the
// exposure limit of the agents), last, just before it is sent
Claim func(pair string, side model.SideType) (bool, string)
}
Config holds the inputs of the Trader, with its defaults in DefaultConfig. Periods are counted in candles of Timeframe.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns the defaults of the Trader, on the 15m timeframe.
type Correlated ¶
type Correlated struct {
}
Correlated is a market correlated with the pair, on its timeframe: its last close, its change over the candles of the context and over the last 4, its trend, and the correlation of its returns with the ones of the pair (-1 to 1) over the candles both have. MarketClosed is set when its last candle is older than two periods, eg: an index on a weekend.
type DailyHistory ¶
type DailyHistory struct {
Day string `json:"day"` // eg: 2026-09-30
TimeZone string `json:"time_zone"` // of the day, eg: America/Belem
Currency string `json:"currency,omitempty"` // of the account: of the results and of the limits
Positions []DailyPosition `json:"positions"`
Orders []DailyOrder `json:"orders"`
Result DailyResult `json:"result"`
Limits *DailyLimits `json:"limits,omitempty"`
}
DailyHistory is the operational day of the symbol so far, see Config.DailyGain: its positions and its orders, told apart, and its result. The results are the ones of the positions, each counted once: an order carries none.
type DailyLimits ¶
type DailyLimits struct {
Gain number `json:"gain"`
Loss number `json:"loss"`
EntriesBlocked bool `json:"entries_blocked"`
Reason string `json:"reason,omitempty"`
}
DailyLimits are the daily limits of the symbol on the realized result of the day, not the take profit nor the stop loss of a position: Gain and Loss, null for none, and whether the new entries are refused until the next operational day, and why.
type DailyOrder ¶
type DailyOrder struct {
ID int64 `json:"id"`
Role string `json:"role"`
Side string `json:"side"`
Type string `json:"type"`
Status string `json:"status"`
Price number `json:"price"`
Quantity number `json:"quantity"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
DailyOrder is an order of the symbol created or updated during the day, oldest first: its role (entry or exit, a fill opening or closing a position; stop_loss or take_profit, a leg of one; other), its type, and its status, eg: FILLED, NEW, CANCELED, EXPIRED or REJECTED.
type DailyPosition ¶
type DailyPosition struct {
Side string `json:"side"`
Status string `json:"status"` // closed or open
Size number `json:"size"`
Entry number `json:"entry_price"`
Exit number `json:"exit_price"`
ExitBy string `json:"exit_by,omitempty"`
OpenedAt time.Time `json:"opened_at"`
ClosedAt *time.Time `json:"closed_at"`
Result number `json:"result"`
UnrealizedResult number `json:"unrealized_result"`
}
DailyPosition is a position of the symbol open during the day, oldest first: closed during it, its Result booked by the broker in the currency of the account, costs included (swap, commission and fee), null while unknown; or open, its UnrealizedResult as the broker shows it, null when unknown, which counts once it closes.
type DailyResult ¶
type DailyResult struct {
Realized number `json:"realized"`
Unrealized number `json:"unrealized"`
PendingResults int `json:"pending_results,omitempty"`
}
DailyResult is the result of the day in the currency of the account: Realized, of the positions closed during it, costs included; Unrealized, of the position open, null without one, counted once it closes; and PendingResults, the closes whose result the broker hasn't booked yet.
type DealingRange ¶
type DealingRange struct {
Direction string `json:"direction"`
High number `json:"high"`
HighTime time.Time `json:"high_time"`
Low number `json:"low"`
LowTime time.Time `json:"low_time"`
Equilibrium number `json:"equilibrium"`
Position ratio `json:"position"`
}
DealingRange is the range of the leg of the last break of the structure: for a break up, from the lowest low of the leg that broke the swing (at LowTime) to the highest high since (at HighTime); for a break down, from its highest high to the lowest low since. Equilibrium is its middle, and Position where the price is in it, 0 at its low and 1 at its high: under 0.5 the discount, over it the premium, beyond 0 and 1 out of the range.
type Decision ¶
type Decision struct {
Action Action `json:"action"`
Confidence float64 `json:"confidence"` // from 0 to 1
Entry *float64 `json:"entry"`
StopLoss *float64 `json:"stop_loss"`
TakeProfit *float64 `json:"take_profit"`
Reason string `json:"reason"`
// Sentiment is the reading of the market of the symbol by the model, from
// 0 (extremely bearish) to 100 (extremely bullish), 50 neutral, whatever the
// action: shown on the dashboard, it doesn't trade. Nil when the answer has
// none, or one out of the range, left out with a note.
Sentiment *float64 `json:"sentiment"`
// Levels are the supports and resistances the analysis relies on, drawn
// on the chart: what the model saw. They don't trade.
Levels []Level `json:"levels"`
// Drawings are the structures the analysis relies on, drawn on the chart
// for a prompt that asks for them (see Config.Drawings): its zones, its
// levels and its markers. They don't trade.
Drawings []Drawing `json:"drawings,omitempty"`
// Notes and Attachments are what the provider returned beside the
// decision, kept with it (see Trader.SetDecisionStore): its notes, eg: the
// text of the model beside the call of the decision, and its files, eg:
// images. They aren't part of the schema: the providers set them.
Notes []Note `json:"notes,omitempty"`
Attachments []Attachment `json:"-"`
}
Decision is the answer of the model to the context of a candle, see the schema of prompt.go. Entry, StopLoss and TakeProfit are null when they don't apply to the action.
func ParseDecision ¶
ParseDecision decodes the JSON of a decision as the schema describes it: every field present and no other, a known action, a confidence from 0 to 1, the prices null or positive, and a reason; a sentiment out of its range is left out with a note, the decision kept. Its errors wrap ErrInvalidResponse. It reads the decision of a prompt without pending orders nor drawings, see parseDecision.
func (Decision) Validate ¶
Validate checks the decision against its context: an action of in.Rules.Actions, and the prices it needs on their side of the current price, within the distances of the rules:
- ENTER_LONG and ENTER_SHORT need an entry near the price, as they are filled at the market, a stop loss on the losing side of both, and a take profit on the winning side of both, unless the rules make it optional: then without one, the risk:reward isn't checked; the rules may also leave it out, no_take_profit: then an entry with one is refused;
- MODIFY_SL needs a stop loss on the losing side of the price, not further from it than the current one unless the rules let it widen;
- MODIFY_TP needs a take profit on the winning side of the price;
- HOLD may repeat the levels of the position, which must then be on their sides of the price too;
- BUY_LIMIT, SELL_LIMIT, BUY_STOP and SELL_STOP need an entry on the side of the price of their type, its stop loss and take profit on their sides of the entry, see validatePending;
- MODIFY_PENDING needs the pending order of the context and its new levels, validated as the ones of its placement, with the levels it has: a stop loss, and a take profit when it has one, never one otherwise;
- CANCEL_PENDING needs the pending order of the context.
Its errors wrap ErrInvalidDecision.
type DecisionStore ¶
type DecisionStore interface {
// Save keeps d, attachments the content of d.Attachments by their index,
// and the decision that placed each of its orders: the first one listing
// it, the ones that move it later listing it among theirs only, as the
// order controller keeps the ID of a leg moved.
Save(d ui.Decision, attachments []Attachment) error
// Decision returns the decision of id, false when unknown.
Decision(id string) (ui.Decision, bool, error)
// Decisions returns the last decisions of pair, of every pair when empty,
// newest first, limit at most.
Decisions(pair string, limit int) ([]ui.Decision, error)
// OrderDecision returns the decision that placed the order, empty for
// none. Called by the chart holding its lock, it must not block.
OrderDecision(orderID int64) string
// Attachment returns the content of the attachment index of the decision
// id and its media type, ui.ErrUnknownDecision when there is none.
Attachment(id string, index int) (mediaType string, data []byte, err error)
}
DecisionStore keeps the decisions of a Trader with their justification, see SetDecisionStore: in memory by default (see MemoryDecisions). Save is called in the flow of the strategy, the others by the handlers of the chart too: they must be safe for concurrent use.
type Drawing ¶
type Drawing struct {
ID string `json:"id"`
Kind string `json:"kind"`
Label string `json:"label"`
Bias string `json:"bias"`
Timeframe string `json:"timeframe"`
From string `json:"from"`
To *string `json:"to"`
Price *float64 `json:"price"`
Low *float64 `json:"low"`
High *float64 `json:"high"`
State *string `json:"state"`
}
Drawing is a mark of the analysis of the model on the chart, see ui.Drawing, in the form of the schema: its times in RFC 3339, as the candles of the context write them, and its prices null when they don't apply to its kind: Low and High for a zone, of supply or of demand too, Price for a level and a marker. To is null while the structure holds: drawn up to the last candle. State is the one of a supply or demand zone (fresh, tested or broken), null for the other kinds.
type Event ¶
type Event struct {
Time time.Time
TimeMode TimeMode
Currency string
Name string
Code string
Importance Importance
Unit string
Actual float64
Forecast float64
Previous float64
// contains filtered or unexported fields
}
Event is a release of the economic calendar. Actual is NaN until it is published, and Forecast and Previous when the calendar has none. A release of a day rather than of a time (see TimeMode) has the start of its day, of the trade server, as its Time.
type FairValueGap ¶
type FairValueGap struct {
Direction string `json:"direction"`
Low number `json:"low"`
High number `json:"high"`
Time time.Time `json:"time"`
CandlesAgo int `json:"candles_ago"`
FilledPct ratio `json:"filled_pct"`
SizeATR ratio `json:"size_atr"`
DistanceATR ratio `json:"distance_atr"`
}
FairValueGap is a gap of three candles not filled yet: bullish when the low of the third is above the high of the first, the gap between them a support below the price; bearish when its high is under the low of the first, a resistance above it. Time is the open of the middle candle, the displacement, CandlesAgo before the last one. Low and High are the part not traded into yet, FilledPct the share of the gap traded into since (0 for none), SizeATR the size of the whole gap and DistanceATR the distance of the middle of the part left from the price, in ATR, positive above.
type Frame ¶
type Frame struct {
Timeframe string `json:"timeframe"`
Trend string `json:"trend"`
EMAFast []number `json:"ema_20,omitempty"` // frameFast
EMASlow []number `json:"ema_50,omitempty"` // frameSlow
SwingStructure string `json:"swing_structure"`
ATR number `json:"atr"`
Levels []Zone `json:"levels"`
Candles Candles `json:"candles"`
SMC *SMC `json:"smc,omitempty"`
}
Frame is a higher timeframe of the pair: its trend (EMA 20 against EMA 50, and the close against the EMA 50) with the last two values of both EMAs, its swing structure, its ATR, its levels (see Structure.Levels) around the price of now, its last candles, and its structure in smart money concepts for a prompt that asks for them (see Config.SMC).
type Importance ¶
type Importance int
Importance is the importance of an event of the calendar.
const ( ImportanceNone Importance = iota ImportanceLow ImportanceMedium ImportanceHigh )
func ParseImportance ¶
func ParseImportance(value string) (Importance, error)
ParseImportance reads low, medium or high, as the flags give them.
func (Importance) String ¶
func (i Importance) String() string
type Input ¶
type Input struct {
Symbol string `json:"symbol"`
Timeframe string `json:"timeframe"`
Time time.Time `json:"time"` // open time of the candle just closed, the last one
Price number `json:"price"` // its close, the current price
// Bid, Ask and Spread at the close, when the exchange sends them in the
// Metadata of the candles, eg: Exness, whose candles are bid prices.
Bid number `json:"bid"`
Ask number `json:"ask"`
Spread number `json:"spread"`
Candles Candles `json:"candles"`
Indicators map[string][]number `json:"indicators"` // the last values of each one, oldest first
Summary Summary `json:"summary"`
Market map[string]number `json:"market_data,omitempty"` // the other Metadata of the last candle
// Calendar is the economic calendar around now, nil when the
// Trader has none, see Config.Calendar.
Calendar *CalendarContext `json:"economic_calendar,omitempty"`
// The context computed by the code: the price structure of the last
// Config.StructureCandles candles, the higher timeframes and the levels
// of the previous day and week (with a feeder, see SetFeeder), the
// session, the instrument, the correlated markets and the memory of the
// last decisions and trades. Each absent when unknown or disabled.
Structure *Structure `json:"structure,omitempty"`
HigherTimeframes []Frame `json:"higher_timeframes,omitempty"`
Reference *Reference `json:"reference_levels,omitempty"`
Session *Session `json:"session,omitempty"`
Instrument *Instrument `json:"instrument,omitempty"`
Memory *Memory `json:"memory,omitempty"`
// Daily is the operational day of the symbol so far: its positions, its
// orders and its result, with the daily limits of the prompt, see
// DailyHistory. Absent without the orders of the bot.
Daily *DailyHistory `json:"daily_history,omitempty"`
// Reanalysis tells that the decision is asked on demand between the
// closes, see Trader.Reanalyze: Price is the last price of
// CandleInProgress, the candle not closed yet, and the other data are the
// ones of the closed candles.
Reanalysis bool `json:"reanalysis,omitempty"`
CandleInProgress *CandleInProgress `json:"candle_in_progress,omitempty"`
// Scheduled tells that the decision is asked on the consult interval
// between the closes, see Config.ConsultInterval, CandleInProgress as for
// a reanalysis, which the trader didn't ask.
Scheduled bool `json:"scheduled,omitempty"`
// ReanalysisNote is the note the trader sent with the reanalysis the
// decision answers, if any: their view, their question or their request;
// the requests reducing the risk of the position held are followed, the
// others weighed, see Config.MinConfidence.
ReanalysisNote string `json:"reanalysis_note,omitempty"`
Position *Position `json:"position"` // nil when flat
EntrySize number `json:"entry_size"` // of the position an entry opens, in units of the asset
Balance number `json:"available_balance"` // available for new positions, see Instrument.Currency
// PendingOrder is the pending entry waiting on the pair for its fill,
// while flat, see Config.PendingOrders: nil without one.
PendingOrder *PendingOrder `json:"pending_order,omitempty"`
// SMC is the structure of the candles in smart money concepts, for a
// prompt that asks for it, see Config.SMC: nil otherwise.
SMC *SMC `json:"smc,omitempty"`
// Drawings are the drawings on the chart of the last analysis of the
// pair, for a prompt that draws (see Config.Drawings): the model keeps the
// ones still valid. Absent without any.
Drawings []Drawing `json:"chart_drawings,omitempty"`
Rules Rules `json:"rules"`
// contains filtered or unexported fields
}
Input is the market context of a decision, as sent to the provider, its JSON the user message of the request: the pair and its prices, its last candles and indicators, the position held, and the rules of the decision, which Decision.Validate enforces. A number unknown is NaN, null in JSON.
type Instrument ¶
type Instrument struct {
Volume string `json:"volume"`
ValuePerPriceUnit number `json:"value_per_price_unit"`
QuoteCurrency string `json:"quote_currency"`
Currency string `json:"account_currency"`
}
Instrument tells what the numbers of the pair mean: its volume (tick volume, the count of the changes of the price, or the volume traded), the profit or the loss of the position (or of entry_size when flat) for a move of 1 of the price, and Currency, the one of the money: the account's (in the paper wallet, the quote, simulated), of value_per_price_unit, available_balance and unrealized_pnl. The prices are in QuoteCurrency.
type Journal ¶
type Journal interface {
// Append keeps the entry. It must not wait for a store far away: the
// flow of the strategy waits for it.
Append(entry JournalEntry) error
// Recent returns the last decisions of each pair, perPair at most,
// oldest first: the calls answered with a valid decision only.
Recent(perPair int) ([]Remembered, error)
}
Journal keeps the calls of the Trader to its model with their whole context, see SetJournal: the journal to measure the decisions against their outcomes (the orders of the bot), and the memory of the context across the restarts. Called in the flow of the strategy.
type JournalEntry ¶
type JournalEntry struct {
At time.Time `json:"at"`
ID string `json:"id,omitempty"`
Trigger string `json:"trigger,omitempty"`
Requested string `json:"requested_by,omitempty"`
Model string `json:"model"`
Prompt *ui.DecisionPrompt `json:"prompt,omitempty"`
LatencyMS int64 `json:"latency_ms"`
Input Input `json:"input"`
Decision *Decision `json:"decision,omitempty"`
Error string `json:"error,omitempty"`
}
JournalEntry is a call of the Trader to its model, see Journal: when, the decision kept of it (ID, see ui.Decision), why it was asked (Trigger, and Requested, the channel of the reanalysis it answers), the model and the prompt, the whole context it was asked with, and its answer, refused with Error too, or its error.
type LiquiditySweep ¶
type LiquiditySweep struct {
Side string `json:"side"`
Level number `json:"level"`
SwingTime time.Time `json:"swing_time"`
Extreme number `json:"extreme"`
Time time.Time `json:"time"`
CandlesAgo int `json:"candles_ago"`
}
LiquiditySweep is a wick beyond a swing that closed back without breaking it: Side buy_side for a swing high (the stops of the shorts and the buy stops above it), sell_side for a swing low. Level is the price of the swing, at SwingTime; Extreme the high (low) of the candle of the sweep, opened at Time, CandlesAgo before the last one.
type MCPCalendar ¶
type MCPCalendar struct {
// contains filtered or unexported fields
}
MCPCalendar reads the economic calendar of a MetaTrader 5 terminal from its MCP server, calling only the read-only tools of the calendar (see mcpAllowedTools). The descriptions of the events of each currency are read once a day, and the releases a day at a time: the past days once, the current ones again every few minutes, so a backtest reads each day once.
func NewMCPCalendar ¶
func NewMCPCalendar(url, token string, options ...MCPOption) (*MCPCalendar, error)
NewMCPCalendar returns the calendar of the MCP server of a MetaTrader 5 terminal at url, eg: http://127.0.0.1:22346/mcp, with the token of its settings. It connects on the first read.
func (*MCPCalendar) Events ¶
func (c *MCPCalendar) Events(ctx context.Context, currencies []string, from, to time.Time) ([]Event, error)
Events returns the releases of the currencies between from and to, oldest first. A currency without any event in the calendar, eg: one it doesn't know, asked again an hour later, is skipped; none of the currencies with events is an error, as is any read failing: the calendar is then unavailable, never taken for a calm one.
func (*MCPCalendar) SetToken ¶
func (c *MCPCalendar) SetToken(token string) bool
SetToken replaces the token of the MCP server, eg: changed on the dashboard, the session of the former one dropped; the releases read stay, the same whatever the token.
func (*MCPCalendar) String ¶
func (c *MCPCalendar) String() string
type MCPOption ¶
type MCPOption func(*MCPCalendar)
MCPOption configures an MCPCalendar.
func WithMCPHTTPClient ¶
WithMCPHTTPClient sends the requests with client.
func WithMCPServerOffset ¶
WithMCPServerOffset sets how far the time of the trade server is from UTC, the times the calendar reads and writes, eg: +2h. It is 0 by default, as on Exness.
type Memory ¶
type Memory struct {
Decisions []PastDecision `json:"recent_decisions"`
Trades []PastTrade `json:"recent_trades"`
}
Memory is what the model decided and traded lately on the pair, newest first: its last decisions, and its last trades closed with their outcome, so it builds on them rather than starting over at every candle.
type MemoryDecisions ¶
type MemoryDecisions struct {
// contains filtered or unexported fields
}
MemoryDecisions is a DecisionStore in memory, the one of the Trader by default: the decisions of a backtest or of a paper wallet, or the cache of a store kept elsewhere (see Load), which then holds the last ones, capacity at most, with the decisions that placed the orders.
func NewMemoryDecisions ¶
func NewMemoryDecisions(capacity int) *MemoryDecisions
NewMemoryDecisions returns a store of the decisions in memory, holding the last capacity of them at most, all of them for 0.
func (*MemoryDecisions) Attachment ¶
Attachment implements DecisionStore: ui.ErrUnknownDecision for the content of an attachment kept elsewhere, see Load.
func (*MemoryDecisions) Load ¶
func (m *MemoryDecisions) Load(decisions []ui.Decision, placed map[int64]string)
Load keeps decisions kept elsewhere, without the content of their attachments, and the decisions that placed the orders of placed, eg: the last ones read from the controller at the start, the ones saved since taking precedence.
func (*MemoryDecisions) OrderDecision ¶
func (m *MemoryDecisions) OrderDecision(orderID int64) string
OrderDecision implements DecisionStore.
func (*MemoryDecisions) Save ¶
func (m *MemoryDecisions) Save(d ui.Decision, attachments []Attachment) error
Save implements DecisionStore.
type NewsConfig ¶
type NewsConfig struct {
Enabled bool
URL, Token string
Before, After time.Duration
Importance Importance
}
NewsConfig is the news of all the agents, set on the dashboard (the tab Notícias): on or off, the MCP server of the economic calendar and its token, and the window of the news block: no entry from Before before a release of at least Importance to After after it, both 0 for none.
type NewsSwitch ¶
type NewsSwitch struct {
// contains filtered or unexported fields
}
NewsSwitch is the calendar of the news of an agent, switched for all the agents from the dashboard (see NewsConfig): off, without the address of its MCP server or its token, it asks nothing to the server and its reads fail with why (ErrNewsDisabled, ErrNewsNoServer, ErrNewsNoToken); on, it reads the calendar of the server, its address, its token and its window replaced while the agent runs (see Set).
func NewNewsSwitch ¶
func NewNewsSwitch(config NewsConfig, options ...MCPOption) *NewsSwitch
NewNewsSwitch returns the switch of the news of config, its calendar read with options, eg: the offset of the trade server.
func (*NewsSwitch) Blocking ¶
Blocking returns the release of events blocking new entries at at in the window of the switch, if any, see NewsConfig.
func (*NewsSwitch) Enabled ¶
func (n *NewsSwitch) Enabled() bool
Enabled reports whether the news are on.
func (*NewsSwitch) Events ¶
func (n *NewsSwitch) Events(ctx context.Context, currencies []string, from, to time.Time) ([]Event, error)
Events reads the releases of the calendar while the news are on with the address of its server and its token, see Calendar.
func (*NewsSwitch) Set ¶
func (n *NewsSwitch) Set(config NewsConfig) (switched, changed bool)
Set applies config at once for the next read: the calendar of another server made anew, the token of the same one replaced (its session dropped). It reports what changed, for the logs: never the token itself.
func (*NewsSwitch) String ¶
func (n *NewsSwitch) String() string
func (*NewsSwitch) Window ¶
func (n *NewsSwitch) Window() (before, after time.Duration, importance Importance)
Window returns the window of the news block, see NewsConfig.
type Note ¶
type Note struct {
Kind string `json:"kind"`
Text string `json:"text,omitempty"`
Title string `json:"title,omitempty"`
URL string `json:"url,omitempty"`
}
Note is a note the provider returned with a decision beside its justification: Kind text, words of the model beside the decision; reasoning, the summary of its reasoning; citation, an annotation of the API with its Title and URL; image, an image the answer links to, at URL.
type OpenAI ¶
type OpenAI struct {
// contains filtered or unexported fields
}
OpenAI is the Provider of the models of OpenAI, eg: ChatGPT, through the Chat Completions API, its answer constrained to the schema of a Decision with a strict JSON schema (structured outputs).
func NewOpenAI ¶
func NewOpenAI(model, apiKey string, options ...ProviderOption) (*OpenAI, error)
NewOpenAI creates the provider of OpenAI answering with model, eg: the one of -llm-model, authenticated with apiKey, eg: from OPENAI_API_KEY.
func (*OpenAI) Analyze ¶
Analyze asks the model for the decision of the context. The answer is the JSON of the decision in the content of the first choice.
func (*OpenAI) AnalyzeWith ¶
AnalyzeWith asks the model for the decision of the context with the instructions system, see SystemPromptProvider.
func (OpenAI) String ¶
func (c OpenAI) String() string
String names the provider and its model for the logs, eg: anthropic claude-sonnet-5.
func (OpenAI) TodayUsage ¶
TodayUsage returns the tokens the provider used today, in UTC, and the count of its answers.
type Option ¶
type Option func(*options)
Option configures the Trader, see New.
func WithPrompt ¶
func WithPrompt(p Prompt, overrides PromptOverrides) Option
WithPrompt sets the prompt the Trader starts with, rather than the instructions of its provider with the indicators and the take profit of its Config: its strategy, sent with each request (see SystemPromptProvider), its indicators and its take profit read from its header, the overrides taking precedence over it. The prompts of SetPromptSource take the same overrides.
type OrderBlock ¶
type OrderBlock struct {
Direction string `json:"direction"`
Low number `json:"low"`
High number `json:"high"`
Time time.Time `json:"time"`
CandlesAgo int `json:"candles_ago"`
BreakTime time.Time `json:"break_time"`
Mitigated bool `json:"mitigated"`
DistanceATR ratio `json:"distance_atr"`
}
OrderBlock is the last candle against the move that broke the structure, before it: for a break up, the last bearish candle at or before the lowest low of the leg between the swing broken and the break (bullish, a support); for a break down, the last bullish one at or before its highest high (bearish, a resistance). Low and High are its range, Time its open, CandlesAgo before the last one, BreakTime the open of the candle of the break it led to. Mitigated tells the price traded back into it since the break; a close beyond it, below a bullish one or above a bearish one, broke it, and it is left out.
type PastDecision ¶
type PastDecision struct {
CandlesAgo int `json:"candles_ago"`
Action Action `json:"action"`
Confidence ratio `json:"confidence"`
Reason string `json:"reason"`
}
PastDecision is a decision taken CandlesAgo candles before now, the time of the analysis, rounded: 0 within the last half candle, eg: an analysis of the candle in progress (see Config.ConsultInterval).
type PastTrade ¶
type PastTrade struct {
Side string `json:"side"`
Entry number `json:"entry_price"`
Exit number `json:"exit_price"`
ExitBy string `json:"exit_by"`
ResultPct ratio `json:"result_pct"`
HeldCandles int `json:"held_candles"`
ClosedCandlesAgo int `json:"closed_candles_ago"`
}
PastTrade is a trade closed ClosedCandlesAgo candles before now: its side, its average entry, its exit and what exited it (stop loss, take profit or exit at the market), its result in % of the entry, and its candles held.
type PendingOrder ¶
type PendingOrder struct {
Type Action `json:"type"`
Entry number `json:"entry_price"`
StopLoss number `json:"stop_loss"`
TakeProfit number `json:"take_profit"`
Size number `json:"size"`
Candles int `json:"candles_pending"`
PlacedBy string `json:"placed_by"`
}
PendingOrder is the pending entry waiting on the pair for its fill: Type the action that places it, eg: BUY_LIMIT, its entry, its stop loss and take profit at the broker (null without one), its size in units of the asset, the candles closed since it was placed, and who placed it: model, the model itself, or trader, someone else, eg: from the dashboard.
type Position ¶
type Position struct {
Side model.SideType `json:"-"`
Size number `json:"size"` // in units of the asset
Entry number `json:"entry_price"`
StopLoss number `json:"stop_loss"`
TakeProfit number `json:"take_profit"`
PnL number `json:"unrealized_pnl"` // at the price, in the account currency, before the costs
Candles int `json:"candles_held"` // closed since the entry, or since it is followed
// InitialStop is the stop loss placed with the entry, whose distance to
// it is the risk of the trade, and RMultiple the profit of a close at the
// market now, net of the spread, in units of that risk: 1 is a profit of
// the initial risk, -1 the loss at the initial stop. Both are null for a
// position the Trader didn't open.
InitialStop number `json:"initial_stop_loss"`
RMultiple number `json:"r_multiple"`
}
Position is the position held on the pair. Entry is unknown for a position opened before a restart, or by someone else, as its levels without their legs, and PnL without the entry.
func (Position) MarshalJSON ¶
MarshalJSON writes the side of the position as LONG or SHORT, as the actions name them.
type Prompt ¶
type Prompt struct {
Ref ui.DecisionPrompt
Content string
}
Prompt is a prompt of the Trader: Ref names it in the records of its decisions, and Content is its strategy with its header lines, the default one (see DefaultPrompt) when empty.
func DefaultPrompt ¶
func DefaultPrompt() Prompt
DefaultPrompt returns the default prompt, embedded: trend + pullback aligned with the SMA of the trend, or free weighing.
type PromptOverrides ¶
PromptOverrides are the settings of the flags of the agent that take precedence over the header of a prompt: Indicators, when set, replace its # Indicators:, the take profit flags add to its # Take profit:.
type PromptReporter ¶
type PromptReporter interface {
ReportPrompt(ref ui.DecisionPrompt, err error)
}
PromptReporter, implemented by a PromptSource, is told whether a prompt of it was applied, or refused with err, the previous one kept.
type PromptSource ¶
type PromptSource interface {
Current(known ui.DecisionPrompt) (p Prompt, changed bool)
}
PromptSource is where the Trader reads the prompt to analyze with at the start of each analysis, see SetPromptSource: changed is false when the one selected is known, the prompt then unset.
type Provider ¶
Provider is the analyst of the Trader: a language model behind an API, which answers the market context of a candle with a decision. Analyze returns an error whenever the answer is not a valid decision for the context: an error of the API, a timeout, or an answer that fails ParseDecision, without a decision, or one that fails Decision.Validate, with the decision refused, kept with its justification but never applied.
func NewProvider ¶
func NewProvider(name, model, apiKey string, options ...ProviderOption) (Provider, error)
NewProvider creates the provider name, openai or anthropic, answering with model, authenticated with apiKey, see NewOpenAI and NewAnthropic.
type ProviderOption ¶
type ProviderOption func(*client)
ProviderOption configures a provider.
func WithBaseURL ¶
func WithBaseURL(baseURL string) ProviderOption
WithBaseURL sets the base URL of the API, eg: a proxy, the one of the provider by default.
func WithHTTPClient ¶
func WithHTTPClient(httpClient *http.Client) ProviderOption
WithHTTPClient sets the HTTP client of the requests, http.DefaultClient by default. The Trader bounds each request with its Timeout.
func WithMaxTokens ¶
func WithMaxTokens(tokens int) ProviderOption
WithMaxTokens caps the tokens of an answer, the thinking of the model included: 4096 by default, 16000 for an answer of Anthropic left to the model (see Anthropic).
func WithReasoningEffort ¶
func WithReasoningEffort(effort string) ProviderOption
WithReasoningEffort sets how much the models that reason think before they answer: none, minimal, low, medium, high or xhigh, as the model takes them, the default of the model when empty. Less effort spends fewer output tokens, billed as the answer. It applies to OpenAI (reasoning_effort); Anthropic answers through a forced tool call, which extended thinking doesn't take, so it is ignored there.
func WithStrategy ¶
func WithStrategy(strategy string) ProviderOption
WithStrategy sets the strategy of the instructions of the model, eg: from ReadStrategy, the one of prompts/default.txt by default. It follows the part the code relies on (the actions, the rules, the context), which it can't change.
func WithUsageHook ¶
func WithUsageHook(hook func(Usage)) ProviderOption
WithUsageHook tells hook the usage of each answer of the provider, as it comes, eg: the budget of a backtest.
type RecordedCall ¶
type RecordedCall struct {
At int64 `json:"at"`
Pair string `json:"pair"`
InputHash string `json:"input_sha256"`
Action string `json:"action,omitempty"`
Confidence float64 `json:"confidence,omitempty"`
Reason string `json:"reason,omitempty"`
Error string `json:"error,omitempty"`
Input int `json:"input_tokens"`
Output int `json:"output_tokens"`
Cost float64 `json:"cost"`
}
RecordedCall is a call of the model in a backtest, see Recorder.
type Recorder ¶
type Recorder struct {
MaxCalls int
MaxCost float64
PriceInput, PriceOutput float64
// contains filtered or unexported fields
}
Recorder is the provider of a backtest: it asks provider, records each call (the simulated time, a hash of the context, the decision, the error, the tokens and the estimated cost), and stops the run once MaxCalls calls were made or their cost reached MaxCost dollars (estimated with PriceInput and PriceOutput, dollars per million tokens; 0 for unknown): the call past it refused (ErrBudgetExhausted) and stop called. Its usage comes from the provider (see WithUsageHook and Usage).
func NewRecorder ¶
NewRecorder returns the provider of a backtest asking provider, its calls timed by now, stop called once its budget is exhausted, see Recorder.
func (*Recorder) AnalyzeWith ¶
type RecorderReport ¶
type RecorderReport struct {
Calls int `json:"calls"`
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
Cost *float64 `json:"cost,omitempty"`
MaxCalls int `json:"max_calls"`
MaxCost float64 `json:"max_cost"`
Exhausted bool `json:"exhausted"`
Model string `json:"model"`
Context []string `json:"context"`
Recorded []RecordedCall `json:"recorded"`
}
RecorderReport is what a Recorder adds to the report of a backtest: its calls, their tokens and their estimated cost (nil when unknown: no price), the ceilings, whether they were reached, and the model.
type Reference ¶
type Reference struct {
PreviousDayHigh number `json:"previous_day_high"`
PreviousDayLow number `json:"previous_day_low"`
PreviousDayClose number `json:"previous_day_close"`
PreviousWeekHigh number `json:"previous_week_high"`
PreviousWeekLow number `json:"previous_week_low"`
DayOpen number `json:"day_open"`
DayHigh number `json:"day_high"`
DayLow number `json:"day_low"`
}
Reference holds the levels of the previous day and week, and of the day so far (UTC days), which the market watches.
type Remembered ¶
type Remembered struct {
Pair string
Candle time.Time
At time.Time
Action Action
Confidence float64
Reason string
}
Remembered is a decision of a Journal read back for the memory of the context: its pair, the candle it was taken on, when (the time of its entry, zero when unknown: the close of the candle then), and its answer.
type Rules ¶
type Rules struct {
Actions []Action `json:"allowed_actions"`
MinConfidence number `json:"min_confidence"` // the actions trading under it are ignored
MaxEntryDistance number `json:"max_entry_distance"` // of the entry from the price, null: no limit
MaxLevelDistance number `json:"max_level_distance"` // of the stop loss and take profit from the price
StopCanWiden bool `json:"stop_loss_can_widen"`
ReasonLanguage string `json:"reason_language"`
// Setup is the setup to trade, see Config.Setup, and MinRiskReward the
// least reward over risk of an entry, net of the spread, null for none.
Setup string `json:"setup"`
MinRiskReward number `json:"min_risk_reward"`
// MinStopDistance is the least room between the stop loss of an entry and
// the price that hits it (the bid for a long, the ask for a short), null
// for none, see Config.MinStopATR.
MinStopDistance number `json:"min_stop_distance"`
// TakeProfitOptional lets an entry go without a take profit, see
// Config.TakeProfitOptional, and NoTakeProfit leaves it out: every entry
// goes without one, see Config.NoTakeProfit.
TakeProfitOptional bool `json:"take_profit_optional,omitempty"`
NoTakeProfit bool `json:"no_take_profit,omitempty"`
// HigherTrend, when set, is the trend the higher timeframes agree on: the
// entries against it are left out of Actions, see
// Config.HigherTrendFilter.
HigherTrend string `json:"higher_timeframes_trend,omitempty"`
// EntriesBlockedBy names the release of the calendar that refuses new
// entries now, left out of Actions, see Config.NewsBlockBefore.
EntriesBlockedBy string `json:"entries_blocked_by_news,omitempty"`
// EntriesBlockedByDailyLimit tells why the new entries on the symbol are
// refused until the next operational day, see Config.DailyGain: a daily
// limit reached, or a result unknown yet; a position held is managed as
// usual.
EntriesBlockedByDailyLimit string `json:"entries_blocked_by_daily_limit,omitempty"`
// PendingOrders are the types of the pending entries the model may place,
// limit and stop, see Config.PendingOrders, and PendingExpiry the candles
// after which one not filled is canceled, 0 for never, see
// Config.PendingExpiry.
PendingOrders []string `json:"pending_orders,omitempty"`
PendingExpiry int `json:"pending_expiry_candles,omitempty"`
}
Rules are the rules of the decision, sent to the model so that it follows them, and enforced by Decision.Validate.
type SMC ¶
type SMC struct {
Breaks []StructureBreak `json:"structure_breaks"` // newest first
FairValueGaps []FairValueGap `json:"fair_value_gaps"` // the nearest to the price first
OrderBlocks []OrderBlock `json:"order_blocks"` // the nearest to the price first
Sweeps []LiquiditySweep `json:"liquidity_sweeps"` // newest first
DealingRange *DealingRange `json:"dealing_range"`
}
SMC is the price structure of the candles of a timeframe in smart money concepts: the last breaks of its structure, the fair value gaps not filled and the order blocks not broken nearest to the price, the last sweeps of the liquidity resting beyond its swings, and the dealing range of the leg of its last break.
type Session ¶
type Session struct {
Weekday string `json:"weekday"`
HourUTC int `json:"hour_utc"`
Open []string `json:"sessions_open"`
NextOpen string `json:"next_session_open"`
Weekend bool `json:"weekend"`
AsiaHigh number `json:"asia_high"`
AsiaLow number `json:"asia_low"`
}
Session is the time of the close of the candle for the market: its weekday and hour in UTC, the sessions open, the next one to open, whether it is a weekend (thin crypto markets, FX and indexes closed), and the range of the Asian session of the day (00:00 to 07:00 UTC) when the candles cover it.
type Structure ¶
type Structure struct {
Candles int `json:"candles"`
SwingStructure string `json:"swing_structure"`
SwingHighs []Swing `json:"swing_highs"` // the last ones, newest first
SwingLows []Swing `json:"swing_lows"`
// Levels are the prices where swings cluster, within levelTolerance ATR:
// a support below the price, a resistance above, the nearest first.
Levels []Zone `json:"levels"`
RoundLevels []number `json:"round_levels"` // the round numbers around the price
RecentRange Box `json:"recent_range"`
LastCandles []CandleShape `json:"last_candles"` // newest first
ATRPercentile ratio `json:"atr_percentile"` // of the last ATR among the ones of the candles, 0 to 100
VolumePercentile ratio `json:"volume_percentile"` // of the last volume among the ones of the candles
}
Structure is the price structure of the last Candles candles: their swing highs and lows, the levels the swings cluster into, the round numbers near the price, the range of the last candles, the shape of the last ones, and the percentile of the volatility and of the volume of the last one.
type StructureBreak ¶
type StructureBreak struct {
Kind string `json:"kind"`
Direction string `json:"direction"`
Level number `json:"level"`
SwingTime time.Time `json:"swing_time"`
Time time.Time `json:"time"`
CandlesAgo int `json:"candles_ago"`
}
StructureBreak is a close beyond the last swing high (Direction up) or low (down) not broken yet: Kind bos when the break before it went the same way, choch when it went the other way, break for the first one of the candles. Level is the price of the swing broken, at SwingTime, and Time the open of the candle that closed beyond it, CandlesAgo before the last one.
type Summary ¶
type Summary struct {
// Trend is up with the fast EMA above the slow one and the close above
// the SMA of the trend, down with both below, else mixed. Left out for a
// strategy that doesn't use the averages (Config.Indicators).
Trend string `json:"trend,omitempty"`
ATRPct number `json:"atr_pct"` // ATR in % of the price
VolumeRatio number `json:"volume_ratio"` // volume of the last candle over its average
High number `json:"high"` // highest high of the candles
Low number `json:"low"` // lowest low of the candles
ChangePct number `json:"change_pct"` // change of the close over the candles, in %
}
Summary sums the candles of the context up.
type Swing ¶
type Swing struct {
Price number `json:"price"`
CandlesAgo int `json:"candles_ago"`
}
Swing is a swing high or low, candles ago.
type SystemPromptProvider ¶
type SystemPromptProvider interface {
Provider
AnalyzeWith(ctx context.Context, system string, input Input) (Decision, error)
}
SystemPromptProvider is a Provider taking the instructions of the model with each request, eg: of the prompt the Trader switches to while it runs (see SetPromptSource): AnalyzeWith analyzes as Analyze, with system, the whole instructions (the part the code relies on and the strategy), rather than its own.
type TimeMode ¶
type TimeMode int
TimeMode is how the calendar knows the time of a release (time_mode of the events of MQL5): at a time, or only its day.
type ToolCall ¶
type ToolCall struct {
ID string
Name string
Arguments json.RawMessage
}
ToolCall is a call of a tool the model answered: Arguments, a JSON object, are the model's, to be validated before anything is done with them.
type ToolSpec ¶
type ToolSpec struct {
Name string
Description string
Parameters json.RawMessage
}
ToolSpec is a tool offered to the model: Parameters is the JSON schema of the arguments of its calls, an object.
type Trader ¶
type Trader struct {
// contains filtered or unexported fields
}
Trader trades the decisions of a Provider, one position at a time per pair, see the package documentation and Config. Positions opened before a restart, or by someone else, are followed without their entry nor their legs, so the model may hold or exit them, but not move their levels.
func (*Trader) Attachment ¶
Attachment returns the content of the attachment index of the decision id, and its media type.
func (*Trader) ChartAnalysis ¶
ChartAnalysis returns the last analysis of the model on pair drawn on the chart, false without one yet. It implements ui.AnalysisSource.
func (*Trader) ChartLevels ¶
ChartLevels returns the supports and resistances of the last decision on pair, drawn on the chart: what the model saw. It implements ui.LevelsSource.
func (*Trader) CheckPromptAccount ¶
CheckPromptAccount checks the prompt the Trader analyzes with against the account of SetAccountReporter, set after the prompt was applied, eg: the one it was made with: daily limits in a currency other than the one of the account, when known, refuse it, as a prompt of SetPromptSource is. Once the reporter is set, before the bot runs.
func (*Trader) Decisions ¶
Decisions returns the last decisions of pair, of every pair when empty, newest first, limit at most. It implements ui.DecisionSource, as the methods below.
func (*Trader) Indicators ¶
func (t *Trader) Indicators(df *model.Dataframe) []strategy.ChartIndicator
Indicators computes the indicators of the prompt analyzed with on df, and returns the ones drawn. Called by the chart too, whose candles are its own, it reads the prompt once: the one of the last analysis.
func (*Trader) LLM ¶
LLM names the model of the Trader, eg: openai gpt-5-mini. It implements strategy.LLMStrategy: the application offers the justifications of its decisions and their reanalysis.
func (*Trader) ListenDecisions ¶
ListenDecisions calls listener with every decision kept from then on, eg: ui.Chart, which sends them to the dashboards.
func (*Trader) News ¶
func (t *Trader) News() *NewsSwitch
News returns the switch of the news of the Trader, nil when its calendar isn't one, see NewsSwitch.
func (*Trader) OnCandle ¶
OnCandle follows the candle just closed of df: live, the model isn't asked at the close (see Config.ConsultInterval), only the exit that failed retried and the pending order followed; in a backtest, the model is asked about it on the schedule, see onClose.
func (*Trader) OnPartialCandle ¶
OnPartialCandle asks the model on the candles in progress, live only, the only place it is asked live: once on the first one after the start, about the candle closed before it; on the one after a reanalysis is asked, at its price, see Reanalyze; and on the first one of each slot of ConsultInterval from the open of the candle in progress to its close, a slot on the close of a candle asked on the first one of the next candle, the candle closed with the others (never on a candle still handed in progress past its close, the close late, complete but not confirmed). The decision of the start, asked apart for the pairs to be asked at once (see startApart), is applied on the next one, and takes the slots it is asked in. On each of them, the close of an exit that failed is retried once due, see retryClose.
func (*Trader) OrderDecision ¶
OrderDecision returns the decision that placed the order, empty for none: the leg of a position keeps the decision of its entry when a later one moves it.
func (*Trader) Prompt ¶
func (t *Trader) Prompt() ui.DecisionPrompt
Prompt returns the prompt the Trader analyzes with, empty when unknown: the instructions of its provider.
func (*Trader) Reanalyze ¶
func (t *Trader) Reanalyze(pair string, channel ui.Channel, note string) (ui.ReanalysisResponse, error)
Reanalyze asks the model again about pair now, rather than at the next close: on the next tick of the candle in progress (see OnPartialCandle), in the flow of the strategy, the rules of its analyses applied, the price the one of that candle. It implements ui.Reanalyzer, from the control panel of the dashboard or of Telegram. An analysis of the pair in progress answers the request, as a reanalysis already queued does, so the model is never asked twice at once; but a note, sent to the model in the context (Input.ReanalysisNote), is answered by the analysis after the one in progress, asked without it, and replaces the note of a reanalysis queued. Its result is notified, see SetNotifier, and its decision kept as the others, with the note. Refused in a backtest, and while the provider is rate limited.
func (*Trader) SetAccountReporter ¶
func (t *Trader) SetAccountReporter(reporter service.AccountReporter)
SetAccountReporter sets where the Trader reads the results of the trades of the bot as the broker books them, in the currency of the account, eg: the MT5 adapter, before the bot runs: the daily limits of the prompts (see Config.DailyGain) are applied with it only, and the results of the positions of the day sent in the context (see DailyHistory). The prompt the Trader was made with is checked against its account with CheckPromptAccount.
func (*Trader) SetClock ¶
SetClock sets the clock of the Trader in place of the wall clock: of its rate limits, its retries and the times of its decisions, eg: the simulated now of a backtest, the same whatever the speed of the machine. Before the run.
func (*Trader) SetDecisionStore ¶
func (t *Trader) SetDecisionStore(store DecisionStore)
SetDecisionStore sets where the Trader keeps its decisions with their justification, in memory by default, eg: the store of the controller: each decision whether or not it traded, and the orders it placed or moved. Before the bot runs.
func (*Trader) SetFeeder ¶
func (t *Trader) SetFeeder(feeder CandleSource)
SetFeeder sets where the Trader reads the candles of the higher timeframes of the pair (Config.HigherTimeframes, and the daily and weekly levels) and of the correlated markets (Config.Correlated): the Feeder of the exchange, live or on paper. Without it, before the bot runs, the context goes without them, as in a backtest.
func (*Trader) SetJournal ¶
SetJournal journals every call of the Trader to its model to journal, with the whole context it was asked with and its answer or its error, and reads back the last decisions of each pair it holds for the memory of the context. Before the bot runs.
func (*Trader) SetNews ¶
func (t *Trader) SetNews(config NewsConfig) (switched, changed bool)
SetNews applies the news of the dashboard to the calendar of the Trader, when it is a NewsSwitch, while it runs: on or off, the server, its token and the window of the news block. It reports what changed, see NewsSwitch.Set.
func (*Trader) SetNotifier ¶
SetNotifier sets where the Trader sends its messages, eg: ui.Chart.Notify, which the dashboard and the Telegram of the controller show: the results of the reanalyses, and the exits that fail, see Trader.close.
func (*Trader) SetOrderSource ¶
SetOrderSource sets where the Trader finds the stored orders of a pair, eg: the storage of the bot, before it runs: a position found at the start, opened before a restart, is followed with its entry and the legs of its stop loss and take profit, which it may move, rather than without them.
func (*Trader) SetPromptSource ¶
func (t *Trader) SetPromptSource(source PromptSource) error
SetPromptSource sets where the Trader reads the prompt it analyzes with, eg: the one selected for the agent in the controller, switched while it runs: at the start of each analysis, the one in progress finishing with the prompt it started with. A prompt it can't analyze with is refused, the previous one kept, and told to the source when it is a PromptReporter, as is the one applied. The provider must take the instructions with each request (see SystemPromptProvider). Before the bot runs.
func (*Trader) Stop ¶
func (t *Trader) Stop()
Stop ends the requests to the model in progress, and fails the ones asked after at once, as the bot exits: its orders refused anyway (see xtrader.XTrader.Run), the candle in progress ends without waiting for the reply, and nothing is kept of those requests (see finish).
func (*Trader) WarmupPeriod ¶
type Usage ¶
Usage is the tokens of the answers of a provider: Input the tokens of the prompts, Cached the ones of them read from the cache of the provider, billed at a discount, CacheWritten the ones of the prompts written to the cache (Anthropic), apart from Input, billed at a premium, Output the tokens answered, and Reasoning the ones of them the model spent reasoning, billed as output but not shown (OpenAI; Anthropic doesn't tell them apart).
type Zone ¶
type Zone struct {
Kind string `json:"kind"` // support or resistance
Price number `json:"price"`
Low number `json:"low"`
High number `json:"high"`
Touches int `json:"touches"`
LastTouch int `json:"last_touch_candles_ago"`
DistanceATR ratio `json:"distance_atr"`
}
Zone is a level of swings: their mean price, their span from Low to High, how many swings touched it, the last one how many candles ago, and its distance from the price in ATR, positive above.
func (Zone) MarshalJSON ¶
MarshalJSON leaves out the span of a zone of a single swing: its price.