Documentation
¶
Index ¶
- Constants
- Variables
- func MT5ContractSize(symbol string) (float64, bool)
- func RegisterMT5Contract(symbol string, contractSize float64)
- func RegisterMT5Pair(symbol, base, quote string) (asset string)
- func RegisterPair(pair, asset, quote string)
- func SplitAssetQuote(pair string) (asset string, quote string)
- type AssetQuote
- type AssetValue
- type BacktestFeed
- func (b *BacktestFeed) AssetsInfo(pair string) model.AssetInfo
- func (b *BacktestFeed) CandlesByLimit(_ context.Context, pair, timeframe string, limit int) ([]model.Candle, error)
- func (b *BacktestFeed) CandlesByPeriod(_ context.Context, pair, timeframe string, start, end time.Time) ([]model.Candle, error)
- func (b *BacktestFeed) CandlesSubscription(ctx context.Context, pair, timeframe string) (chan model.Candle, chan error)
- func (b *BacktestFeed) LastQuote(ctx context.Context, pair string) (float64, error)
- func (b *BacktestFeed) Now() time.Time
- func (b *BacktestFeed) SetAssetsInfo(pair string, info model.AssetInfo)
- func (b *BacktestFeed) SetNow(now time.Time)
- type CSVFeed
- func (c CSVFeed) AssetsInfo(pair string) model.AssetInfo
- func (c *CSVFeed) CandlesByLimit(_ context.Context, pair, timeframe string, limit int) ([]model.Candle, error)
- func (c CSVFeed) CandlesByPeriod(_ context.Context, pair, timeframe string, start, end time.Time) ([]model.Candle, error)
- func (c CSVFeed) CandlesSubscription(_ context.Context, pair, timeframe string) (chan model.Candle, chan error)
- func (c CSVFeed) LastQuote(_ context.Context, _ string) (float64, error)
- func (c *CSVFeed) Limit(duration time.Duration) *CSVFeed
- type DataFeed
- type DataFeedConsumer
- type DataFeedSubscription
- type MT5
- func (m *MT5) Account() (model.Account, error)
- func (m *MT5) AccountCurrency() string
- func (m *MT5) AccountSummary() (service.AccountSummary, bool)
- func (m *MT5) AssetsInfo(pair string) model.AssetInfo
- func (m *MT5) Cancel(order model.Order) error
- func (m *MT5) CandlesByLimit(ctx context.Context, pair, period string, limit int) ([]model.Candle, error)
- func (m *MT5) CandlesByPeriod(ctx context.Context, pair, period string, start, end time.Time) ([]model.Candle, error)
- func (m *MT5) CandlesSubscription(ctx context.Context, pair, period string) (chan model.Candle, chan error)
- func (m *MT5) ClosedProfit(close, entry model.Order) (float64, bool)
- func (m *MT5) ClosesProtected() bool
- func (m *MT5) Comment() string
- func (m *MT5) ContractSize(pair string) float64
- func (m *MT5) CreateOrderLimit(side model.SideType, pair string, size float64, limit float64) (model.Order, error)
- func (m *MT5) CreateOrderLimitProtected(side model.SideType, pair string, size, limit, stop, profit float64) ([]model.Order, error)
- func (m *MT5) CreateOrderMarket(side model.SideType, pair string, size float64) (model.Order, error)
- func (m *MT5) CreateOrderMarketProtected(side model.SideType, pair string, size, stop, profit float64) ([]model.Order, error)
- func (m *MT5) CreateOrderMarketQuote(side model.SideType, pair string, quote float64) (model.Order, error)
- func (m *MT5) CreateOrderMarketReduce(side model.SideType, pair string, size float64) (model.Order, error)
- func (m *MT5) CreateOrderOCO(side model.SideType, pair string, size, price, stop, _ float64) ([]model.Order, error)
- func (m *MT5) CreateOrderStop(pair string, size float64, stop float64) (model.Order, error)
- func (m *MT5) CreateOrderStopProtected(side model.SideType, pair string, size, level, stop, profit float64) ([]model.Order, error)
- func (m *MT5) DataOnly() bool
- func (m *MT5) ExitsAwaited(pair string) (since time.Time, ok bool)
- func (m *MT5) FillPositions(fill model.Order) (opened int64, closed []int64, ok bool)
- func (m *MT5) HeldPosition(pair string) (side model.SideType, quantity float64, ok bool)
- func (m *MT5) LastQuote(ctx context.Context, pair string) (float64, error)
- func (m *MT5) Leverage(string) float64
- func (m *MT5) LiveProtection(leg model.Order) (model.Order, bool, error)
- func (m *MT5) Login() int64
- func (m *MT5) Lots(pair string, units float64) float64
- func (m *MT5) Magic() int64
- func (m *MT5) OpenPosition(pair string) (MT5OpenPosition, bool)
- func (m *MT5) Order(pair string, id int64) (model.Order, error)
- func (m *MT5) OrderSince(pair string, id int64, since time.Time) (model.Order, error)
- func (m *MT5) PointValue(pair string) (float64, error)
- func (m *MT5) Position(pair string) (asset, quote float64, err error)
- func (m *MT5) PositionCosts(pair string) service.PositionCosts
- func (m *MT5) ProtectionLimits(pair string) (service.ProtectionLimits, bool)
- func (m *MT5) SetStop(side model.SideType, pair string, size, stop float64) ([]model.Order, error)
- func (m *MT5) Units(pair string, lots float64) float64
- func (m *MT5) UpdateLimit(order model.Order, limit float64) (model.Order, error)
- func (m *MT5) UpdateProtection(leg model.Order, level float64) (model.Order, error)
- type MT5Error
- type MT5OpenPosition
- type MT5Option
- func WithMT5BaseURL(baseURL string) MT5Option
- func WithMT5Comment(comment string) MT5Option
- func WithMT5DataOnly() MT5Option
- func WithMT5Deviation(points int) MT5Option
- func WithMT5HTTPClient(client *http.Client) MT5Option
- func WithMT5Leverage() MT5Option
- func WithMT5Magic(magic int64) MT5Option
- func WithMT5PollInterval(interval time.Duration) MT5Option
- func WithMT5Real() MT5Option
- func WithMT5Symbols(symbols ...string) MT5Option
- func WithMT5Token(token string) MT5Option
- type MT5PositionLevels
- type MT5ProtectionError
- type OrderError
- type PairFeed
- type PaperExecution
- type PaperWallet
- func (p *PaperWallet) Account() (model.Account, error)
- func (p *PaperWallet) AssetValues(asset string) []AssetValue
- func (p *PaperWallet) AssetsInfo(pair string) model.AssetInfo
- func (p *PaperWallet) Cancel(order model.Order) error
- func (p *PaperWallet) CandlesByLimit(ctx context.Context, pair, period string, limit int) ([]model.Candle, error)
- func (p *PaperWallet) CandlesByPeriod(ctx context.Context, pair, period string, start, end time.Time) ([]model.Candle, error)
- func (p *PaperWallet) CandlesSubscription(ctx context.Context, pair, timeframe string) (chan model.Candle, chan error)
- func (p *PaperWallet) CreateOrderLimit(side model.SideType, pair string, size float64, limit float64) (model.Order, error)
- func (p *PaperWallet) CreateOrderLimitProtected(side model.SideType, pair string, size, limit, stop, profit float64) ([]model.Order, error)
- func (p *PaperWallet) CreateOrderMarket(side model.SideType, pair string, size float64) (model.Order, error)
- func (p *PaperWallet) CreateOrderMarketProtected(side model.SideType, pair string, size, stop, profit float64) ([]model.Order, error)
- func (p *PaperWallet) CreateOrderMarketQuote(side model.SideType, pair string, quoteQuantity float64) (model.Order, error)
- func (p *PaperWallet) CreateOrderMarketReduce(side model.SideType, pair string, size float64) (model.Order, error)
- func (p *PaperWallet) CreateOrderOCO(side model.SideType, pair string, size, price, stop, stopLimit float64) ([]model.Order, error)
- func (p *PaperWallet) CreateOrderStop(pair string, size float64, limit float64) (model.Order, error)
- func (p *PaperWallet) CreateOrderStopProtected(side model.SideType, pair string, size, level, stop, profit float64) ([]model.Order, error)
- func (p *PaperWallet) Equity() float64
- func (p *PaperWallet) EquityValues() []AssetValue
- func (p *PaperWallet) ID() int64
- func (p *PaperWallet) LastClose(pair string) (float64, bool)
- func (p *PaperWallet) LastQuote(ctx context.Context, pair string) (float64, error)
- func (p *PaperWallet) LiveProtection(leg model.Order) (model.Order, bool, error)
- func (p *PaperWallet) MaxDrawdown() (float64, time.Time, time.Time)
- func (p *PaperWallet) OnCandle(candle model.Candle)
- func (p *PaperWallet) Order(_ string, id int64) (model.Order, error)
- func (p *PaperWallet) Pairs() []string
- func (p *PaperWallet) Position(pair string) (asset, quote float64, err error)
- func (p *PaperWallet) Protect(side model.SideType, pair string, size, stop, profit float64) ([]model.Order, error)
- func (p *PaperWallet) SetStop(side model.SideType, pair string, size, stop float64) ([]model.Order, error)
- func (p *PaperWallet) Summary()
- func (p *PaperWallet) UpdateLimit(order model.Order, limit float64) (model.Order, error)
- func (p *PaperWallet) UpdateProtection(leg model.Order, level float64) (model.Order, error)
- type PaperWalletOption
- type Subscription
Constants ¶
const ( // MT5DefaultBaseURL is the address of the bridge by default, the one // tools/mt5bridge/mt5bridge.py listens at. MT5DefaultBaseURL = "http://127.0.0.1:18812" // MT5TokenHeader is the header carrying the token of the bridge, see // WithMT5Token. MT5TokenHeader = "X-Bridge-Token" // MT5DeadlineHeader is the header carrying the deadline of a trade request, // in Unix milliseconds: the bridge never sends it to the terminal after it, // refusing it with "sent": false. MT5DeadlineHeader = "X-Bridge-Deadline" // MT5TimeoutHeader is the header carrying the same deadline as the time // left until it when the request is sent, in milliseconds: the bridge takes // the earliest of the two, this one counted by its own clock from the // receipt of the request, so that a clock of the bridge behind the one of // the agent, eg: on another host, never makes it send a request later. MT5TimeoutHeader = "X-Bridge-Timeout" )
Variables ¶
var ( ErrInvalidQuantity = errors.New("invalid quantity") ErrInsufficientFunds = errors.New("insufficient funds or locked") ErrInvalidAsset = errors.New("invalid asset") ErrOrderNotFound = errors.New("order not found") // ErrOrderNotOpen is returned when an order can't be canceled because it // has already been filled or canceled. ErrOrderNotOpen = errors.New("order is not open") // ErrNotSupported is returned by the operations an exchange doesn't offer. ErrNotSupported = errors.New("operation not supported by the exchange") // ErrInvalidProtection is returned for a stop loss or take profit on the // wrong side of the position they protect. ErrInvalidProtection = errors.New("invalid stop loss or take profit") // ErrNothingToReduce is returned by a reduce-only order when nothing is // held against its side, see service.ReduceOnlyBroker: flat, eg: closed by // its stop loss meanwhile, or held on the side of the order. ErrNothingToReduce = errors.New("no position to reduce") )
var ( // ErrMT5AccountChanged is the error of the trading calls while the terminal // is logged in another account than the one NewMT5 connected to, or the // account turned real without WithMT5Real, eg: switched by hand. ErrMT5AccountChanged = errors.New("mt5: the terminal is not logged in the account of the bot") // ErrMT5OutcomeUnknown is the error of a trade request whose answer was lost // and that the adapter could neither find in the account nor confirm as not // executed: it may have been executed, so it must not be sent again before // the account is checked. ErrMT5OutcomeUnknown = errors.New("mt5: the outcome of the trade request is unknown") // ErrMT5Unsettled is the error of a trade request opening or closing a // position of a pair while the outcome of another one of the pair is // unknown, the account unreadable since (see ErrMT5OutcomeUnknown): not // sent, until a read of the account tells it. ErrMT5Unsettled = errors.New("mt5: the outcome of a trade request of the pair is unknown yet") )
var ErrInsufficientData = errors.New("insufficient data")
Functions ¶
func MT5ContractSize ¶
MT5ContractSize returns the contract size of a symbol registered by NewMT5 or RegisterMT5Contract, or known by the package.
func RegisterMT5Contract ¶
RegisterMT5Contract records the contract size of a symbol, the units of the base asset in a lot, eg: to convert lots in a backtest. NewMT5 registers the ones of the symbols traded.
func RegisterMT5Pair ¶
RegisterMT5Pair registers a symbol quoted in quote with its base asset as NewMT5 does, eg: to backtest candles downloaded from MT5 (XAUUSDm, XAU, USD). The asset is base, or when base is empty or the quote itself, the symbol name before the quote (XAU of XAUUSDm), or else the symbol. It returns the asset registered. See RegisterMT5Contract for the sizes.
func RegisterPair ¶
func RegisterPair(pair, asset, quote string)
RegisterPair makes SplitAssetQuote know a pair missing from the embedded list, pairs.json, the crypto pairs of the backtests and the tests. The MT5 adapter registers its symbols when it is created, before the bot validates its pairs.
func SplitAssetQuote ¶
Types ¶
type AssetQuote ¶
type AssetValue ¶
type BacktestFeed ¶
type BacktestFeed struct {
// contains filtered or unexported fields
}
BacktestFeed is the feed of a backtest: the candles of a CSVFeed handed to the bot in their order (CandlesSubscription), and, to whatever asks for candles meanwhile (CandlesByPeriod, CandlesByLimit: eg: the protection of the positions, the higher timeframes of an LLM), only the ones closed by the simulated now (SetNow), never a future one, the feed itself untouched. A timeframe the feed doesn't hold is resampled from the candles of the file. AssetsInfo returns the infos set (SetAssetsInfo), else the CSVFeed's.
func NewBacktestFeed ¶
func NewBacktestFeed(csv *CSVFeed) *BacktestFeed
NewBacktestFeed returns the feed of a backtest over csv, see BacktestFeed.
func (*BacktestFeed) AssetsInfo ¶
func (b *BacktestFeed) AssetsInfo(pair string) model.AssetInfo
func (*BacktestFeed) CandlesByLimit ¶
func (b *BacktestFeed) CandlesByLimit(_ context.Context, pair, timeframe string, limit int) ([]model.Candle, error)
CandlesByLimit returns the last limit candles of pair on timeframe closed by the simulated now, ErrInsufficientData with fewer: the feed untouched.
func (*BacktestFeed) CandlesByPeriod ¶
func (b *BacktestFeed) CandlesByPeriod(_ context.Context, pair, timeframe string, start, end time.Time) ([]model.Candle, error)
CandlesByPeriod returns the candles of pair on timeframe from start until end, closed by the simulated now.
func (*BacktestFeed) CandlesSubscription ¶
func (*BacktestFeed) Now ¶
func (b *BacktestFeed) Now() time.Time
Now returns the simulated now, see SetNow.
func (*BacktestFeed) SetAssetsInfo ¶
func (b *BacktestFeed) SetAssetsInfo(pair string, info model.AssetInfo)
SetAssetsInfo sets the infos of pair, eg: the volume step and the least volume of its symbol.
func (*BacktestFeed) SetNow ¶
func (b *BacktestFeed) SetNow(now time.Time)
SetNow sets the simulated now: the end of the data known, eg: the close of the candle being processed.
type CSVFeed ¶
func NewCSVFeed ¶
NewCSVFeed creates a new data feed from CSV files and resample
func (*CSVFeed) CandlesByLimit ¶
func (CSVFeed) CandlesByPeriod ¶
func (CSVFeed) CandlesSubscription ¶
type DataFeedConsumer ¶
type DataFeedSubscription ¶
type DataFeedSubscription struct {
Feeds *set.LinkedHashSetString
DataFeeds map[string]*DataFeed
SubscriptionsByDataFeed map[string][]Subscription
// contains filtered or unexported fields
}
func NewDataFeed ¶
func NewDataFeed(exchange service.Exchange) *DataFeedSubscription
func (*DataFeedSubscription) Connect ¶
func (d *DataFeedSubscription) Connect()
func (*DataFeedSubscription) Preload ¶
func (d *DataFeedSubscription) Preload(pair, timeframe string, candles []model.Candle)
func (*DataFeedSubscription) Start ¶
func (d *DataFeedSubscription) Start(loadSync bool)
Start connects the feeds and hands their candles to their consumers, until the feeds close. With loadSync, eg: a backtest, the consumers take each candle in turn and Start returns once the feeds closed; else each consumer takes the candles from a queue of its own (see candleQueue), so that a slow one, eg: the chart of a bot serving a snapshot, holds itself only, never the feed nor the other consumers, eg: the bot.
func (*DataFeedSubscription) Subscribe ¶
func (d *DataFeedSubscription) Subscribe(pair, timeframe string, consumer DataFeedConsumer, onCandleClose bool)
type MT5 ¶
type MT5 struct {
// contains filtered or unexported fields
}
MT5 trades a MetaTrader 5 account through tools/mt5bridge, a local HTTP bridge running with the terminal, logged in the account, which wraps the official MetaTrader5 Python package.
The pairs are the symbols of the terminal, eg: XAUUSDm, quoted in their profit currency (currency_profit) whatever the currency of the account. Every quantity crossing the adapter is in units of the base asset (units = lots x trade_contract_size, eg: 100 ounces in a lot of XAUUSDm), floored to the volume step; see ContractSize, Lots and Units.
The account must be hedging, the only mode of Exness. The adapter nets the positions of the bot, the ones of its magic number (WithMT5Magic), as the order controller expects: a market order against the bot's net closes its opposite positions first in, first out, and a pending order filled against it is closed by them (close-by). Manual trades and the other bots, of other magic numbers, are ignored, so they share the account.
Candles are bid prices, as MT5 draws them, timed at their open in UTC: the server time of the account must be UTC, as the one of Exness. CandlesSubscription polls the latest candles every poll interval.
The positions and the pending orders are polled every poll interval into a local book, and the history (deals and orders) is read when something left the book: Order and OrderSince, asked every second by the order controller, answer from the book.
A trade request is sent once, with a deadline the bridge never sends it to the terminal after; one whose answer is lost is looked for in the account before failing (reconcile), the trading of its pair only waiting meanwhile. While the terminal is logged in another account than the one NewMT5 connected to, or the account turned real without WithMT5Real, nothing is traded (ErrMT5AccountChanged).
func NewMT5 ¶
NewMT5 connects to the bridge, checks the terminal and the account, loads the symbols, registering them as pairs, and, unless WithMT5DataOnly, starts the book of the account, polled until ctx is done:
- the options: at least one symbol, a positive poll interval, a comment of 1 to 31 printable characters not starting with "[" (MT5 comments the exits by the levels "[sl x]"), and a positive magic number to trade;
- GET /health: a terminal disconnected from its server fails, and one with AlgoTrading off is a warning (every order would be refused), as is a read-only bridge an error, when trading;
- GET /account: a real account needs WithMT5Real; trading needs a hedging account (margin_mode 2);
- GET /symbol of every symbol: unknown ones are ErrInvalidAsset, disabled ones fail when trading; each is registered (RegisterMT5Pair, RegisterMT5Contract);
- when trading, the symbols converting the account currency into the quote of every symbol (Position), and the book: a first poll and the history of mt5HistoryLookback, synchronous, then the netting of the fills missed while the bot was off, and the poll loop.
func (*MT5) Account ¶
Account returns the cash available for new positions as a free balance and the amount the positions commit as locked, in the account currency, and the net size of the bot on each traded symbol as a balance of its base asset (the symbols sharing a base summed), with the leverage of the account when trading with leverage. See wallet.
func (*MT5) AccountCurrency ¶
AccountCurrency returns the currency of the account, eg: BRL.
func (*MT5) AccountSummary ¶
func (m *MT5) AccountSummary() (service.AccountSummary, bool)
AccountSummary returns the account as the terminal reports it, in its currency (the one read within the poll interval, else read again). It implements service.AccountReporter.
func (*MT5) Cancel ¶
Cancel removes a pending order and the legs protecting the position it would open, or removes the protection of the positions or of the pending order of a leg (both legs: SLTP with both levels 0 on each position, or MODIFY of the pending order keeping its price and expiry). A pending order executed in part keeps its legs, protecting its position: the order reports what it executed (see OrderSince), PENDING_CANCEL while unknown, eg: the account unread after the removal (see executedBeforeRemoval). A filled or canceled order is ErrOrderNotOpen, in an OrderError.
func (*MT5) CandlesByLimit ¶
func (m *MT5) CandlesByLimit(ctx context.Context, pair, period string, limit int) ([]model.Candle, error)
CandlesByLimit returns the last limit complete candles, oldest first: the latest limit+1 (the candle in progress dropped), read backwards by pages of mt5MaxRates from the positions of /rates, until enough candles or the start of the history. The latest one, over on the clock only, is complete when the terminal confirms it (confirmsClose, the state of the terminal read first); otherwise it is dropped as in progress. It records the last complete candle, where CandlesSubscription starts.
func (*MT5) CandlesByPeriod ¶
func (m *MT5) CandlesByPeriod(ctx context.Context, pair, period string, start, end time.Time) ([]model.Candle, error)
CandlesByPeriod returns the complete candles opened between start and end, oldest first, read in ranges of mt5RangeRates periods. Up to now, the latest one is complete as for CandlesByLimit.
func (*MT5) CandlesSubscription ¶
func (m *MT5) CandlesSubscription(ctx context.Context, pair, period string) (chan model.Candle, chan error)
CandlesSubscription polls the latest candles (and the tick, for the ask of the candle in progress) every poll interval: the candle in progress is sent as partial each time it changes, and every candle once complete, the ones missed during an outage included. The latest candle over on the clock only stays in progress until the terminal confirms it (confirmsClose), eg: while it is disconnected from its server, logged after mt5HeldWarn. The stream starts after the last candle returned by CandlesByLimit, which the bot preloads; without one, after the candles already complete at the first poll. A candle the terminal changes after it was sent complete is logged, never sent again: the strategies ran on it. Errors go to the error channel without stopping the stream; both channels are closed when ctx is done.
func (*MT5) ClosedProfit ¶
ClosedProfit returns the profit the account booked for close, a fill of the bot closing (a part of) the position entry opened, from the deals of the history kept (mt5HistoryLookback at the start): the profit, swap, commission and fee, in the account currency, of
- a leg: the exits of the position by its level, SL for the stop loss, TP for the take profit;
- a market order: the exits of the position by its closing orders (see marketExits);
- a pending order, eg: a stop of CreateOrderStop: the close of its fill by the position (close-by, see closedBy).
Unknown while none is in the book, or while one is only known from the answer of the close, not from the history yet: the history is read again meanwhile (awaitedExits). It implements service.AccountReporter; it reads the book only.
func (*MT5) ClosesProtected ¶
ClosesProtected reports that a market order closes a protected position with its stop loss and take profit in place, see service.ProtectedCloser: it closes the bot's opposite positions by their tickets (marketNet), and the levels go with them, the legs reported CANCELED. A close refused leaves the position protected.
func (*MT5) ContractSize ¶
ContractSize returns the units of the base asset in a lot of pair, eg: 100 ounces for XAUUSDm, or 0 when unknown.
func (*MT5) CreateOrderLimit ¶
func (m *MT5) CreateOrderLimit(side model.SideType, pair string, size float64, limit float64) (model.Order, error)
CreateOrderLimit places a buy limit or a sell limit of size units at limit. Its fill against the bot's net is netted with close-by (settlePair).
func (*MT5) CreateOrderLimitProtected ¶
func (m *MT5) CreateOrderLimitProtected(side model.SideType, pair string, size, limit, stop, profit float64) ([]model.Order, error)
CreateOrderLimitProtected places a limit order at limit opening a position with its stop loss and take profit, see service.ProtectionBroker: the entry pending, then the legs, anchored to its ticket.
func (*MT5) CreateOrderMarket ¶
func (m *MT5) CreateOrderMarket(side model.SideType, pair string, size float64) (model.Order, error)
CreateOrderMarket buys or sells size units of pair at the market, netted against the bot's positions: its opposite positions are closed first in, first out, and only the rest opens a position. The order returned is FILLED at the average price of its fills, with the ticket of the position opened, or else of the first closing order. When a step fails after others were done, the order returned is FILLED with the quantity done and the error is logged, so the order controller's position matches the broker's; when the first one fails, the error is returned.
func (*MT5) CreateOrderMarketProtected ¶
func (m *MT5) CreateOrderMarketProtected(side model.SideType, pair string, size, stop, profit float64) ([]model.Order, error)
CreateOrderMarketProtected opens a position at the market with its stop loss and take profit in the same request, see service.ProtectionBroker: the entry FILLED, then the legs, anchored to the ticket of the position. Refused against the bot's net (checkEntry).
func (*MT5) CreateOrderMarketQuote ¶
func (m *MT5) CreateOrderMarketQuote(side model.SideType, pair string, quote float64) (model.Order, error)
CreateOrderMarketQuote buys or sells the size worth quote, an amount in the account currency, at the current price, the ask for a buy and the bid for a sell, valued by the point value of pair (see Position).
func (*MT5) CreateOrderMarketReduce ¶
func (m *MT5) CreateOrderMarketReduce(side model.SideType, pair string, size float64) (model.Order, error)
CreateOrderMarketReduce closes up to size units of the bot's positions against side on pair, first in, first out, by their tickets, and never opens a position with the rest, see service.ReduceOnlyBroker: a position closed meanwhile, eg: by its stop loss, is refused by the terminal rather than opening the other side. Their stop loss and take profit go with them, as with CreateOrderMarket. exchange.ErrNothingToReduce when the bot holds none.
func (*MT5) CreateOrderOCO ¶
func (m *MT5) CreateOrderOCO(side model.SideType, pair string, size, price, stop, _ float64) ([]model.Order, error)
CreateOrderOCO protects the bot's open positions of pair with a take profit at price and a stop loss at stop, the levels MT5 attaches to each position (TRADE_ACTION_SLTP): once they close the positions the other leg goes with them, as the other leg of an OCO order. The bot's positions of pair must be on the side opposite to side and sum size units (within half a step), and have no level yet: otherwise ErrNotSupported or ErrInvalidQuantity. The legs are anchored to the oldest position. The stop loss closes at the market, so stopLimit is not used.
func (*MT5) CreateOrderStop ¶
CreateOrderStop places a sell stop of size units at stop, which closes a long position once the price falls to it: its fill opens a short position, netted at once with the long ones by close-by (settlePair).
func (*MT5) CreateOrderStopProtected ¶
func (m *MT5) CreateOrderStopProtected(side model.SideType, pair string, size, level, stop, profit float64) ([]model.Order, error)
CreateOrderStopProtected places a stop order triggered at level opening a position with its stop loss and take profit, see service.ProtectionBroker.
func (*MT5) DataOnly ¶
DataOnly reports whether the adapter reads the market data only, see WithMT5DataOnly.
func (*MT5) ExitsAwaited ¶
ExitsAwaited reports whether a position of the bot on pair left the book, eg: closed by its stop loss, without its exits in the history yet: its close and its profit (see ClosedProfit) unknown to the bot meanwhile, its legs NEW (see legState), the history read again for them up to mt5AwaitMax; also one closed before the adapter started (see awaitClosed). since is when the bot noticed the oldest close, by its clock: the close is not later, eg: the start for one closed before. It reads the book only.
func (*MT5) FillPositions ¶
FillPositions returns the positions of the account the fill of an order of the bot opened, by its ticket (0 for none), and closed (a part of), as the book and the history kept tell them (mt5HistoryLookback at the start), for the trades of the bot to be told apart by position:
- a leg closes the positions it protects;
- a market order closes the ones of its closing orders (its ticket, or the ones the adapter sent it with), and opens the one of its ticket;
- a pending order opens the one of its ticket, and closes the older ones it was netted with by close-by (see settlePair).
False when unknown, eg: a fill older than the history, a leg of a previous run, a market order of a previous run that opened a position, the ones it closed first unknown, or one of this run while the exit of one of its closing orders isn't in the book yet. It reads the book only.
func (*MT5) HeldPosition ¶
HeldPosition returns the net position of the bot on pair, its positions of the magic number of the bot as last polled from the terminal (no request), netted in volume steps, as Position nets them: the side and the units held, 0 when flat; false for a pair the bot doesn't trade, or without the book (WithMT5DataOnly). It implements service.PositionReporter.
func (*MT5) Leverage ¶
Leverage returns the leverage of the account, the same on every symbol of pair ("unlimited" counts as 1:2000): the value of the positions it can open is the margin they commit times the leverage. See WithMT5Leverage.
func (*MT5) LiveProtection ¶
LiveProtection returns leg as the book holds it now, see service.ProtectionReader: at the level of its pending entry, false; or at the most protective level of its open positions (see mt5Protective), true. A leg canceled, of an older protection, or of positions closed is ErrOrderNotOpen. It sends no request.
func (*MT5) Lots ¶
Lots converts units of the base asset of pair into lots, eg: 1 ounce of XAUUSDm is 0.01 lot. It is 0 for a pair of unknown contract size.
func (*MT5) OpenPosition ¶
func (m *MT5) OpenPosition(pair string) (MT5OpenPosition, bool)
OpenPosition returns the net position of the bot's positions of pair, as last polled from the terminal (no request), false when flat.
func (*MT5) OrderSince ¶
OrderSince returns an order created at since, from the book, see service.OrderHistory:
- canceled by Cancel: CANCELED, unless a part of it was executed, or may have been (step 4);
- a leg (known, or rebuilt: a hashed id matching mt5LegID with a ticket of the bot in the book, see findLeg): legOrder;
- a market order known: FILLED as returned;
- a ticket: pending while in the book (NEW or PARTIALLY_FILLED); FILLED when a position of its ticket, or its deals, are known, at the average price of its deals (or the open price of its position), UpdatedAt the time of the last one, PARTIALLY_FILLED while the rest of a pending order executed in part may have been executed too, then FILLED with what was (see partialFill); PENDING_CANCEL while a part of a pending order removed by Cancel may have been executed, unknown (see maybeExecuted); else CANCELED, EXPIRED or REJECTED as its state in the orders of the history;
- a ticket the book doesn't know: ensureHistory(since), one read at most, then step 4 again; a pending order of the adapter gone from the book stays NEW while its outcome is awaited (mt5ResolveWait), then CANCELED; any other is ErrOrderNotFound.
Orders rebuilt for a previous run are remembered. Only step 5 may send requests.
func (*MT5) PointValue ¶
PointValue returns the value in the account currency of a move of 1 of the price of pair for 1 unit of its asset, see service.PointValuer.
func (*MT5) Position ¶
Position returns the net size of the bot's positions of pair in units, negative when short, and the cash available for new positions in the account currency: its point value (PointValue) turns a move of the price into it.
func (*MT5) PositionCosts ¶
func (m *MT5) PositionCosts(pair string) service.PositionCosts
PositionCosts returns the costs known of the position of the bot on pair, see service.PositionCostReader: its negative swap, and the commission and the fee of its entry deals twice (the exit taken as the same), in the account currency, turned into a distance of the price by the units held and the point value of the symbol. Known is false when an entry deal isn't in the history read yet (its commission unknown); the swap counts all the same. Nothing when the point value can't be read.
func (*MT5) ProtectionLimits ¶
func (m *MT5) ProtectionLimits(pair string) (service.ProtectionLimits, bool)
ProtectionLimits returns the constraints of the levels of pair, see service.ProtectionLimiter: the tick of its symbol, and its stops and freeze levels in price, as read at the start.
func (*MT5) SetStop ¶
SetStop puts a stop loss at stop on the positions of the bot held on side of pair, none with one, their take profit kept, see service.StopSetter: one TRADE_ACTION_SLTP each, the levels set before removed on a failure (see changeLevels). The protection moves to a new generation when it has legs already (eg: a take profit, or a stop loss removed by hand), so that the old ones end CANCELED, and the legs of both levels are returned anew, the take profit first, as CreateOrderOCO returns them.
func (*MT5) Units ¶
Units converts lots of pair into units of its base asset, eg: 0.01 lot of XAUUSDm is 1 ounce. It is 0 for a pair of unknown contract size.
func (*MT5) UpdateLimit ¶
UpdateLimit moves a pending limit order to limit, see service.ProtectionBroker: TRADE_ACTION_MODIFY with its levels as they are, good till canceled. Only the limit orders: the others are ErrNotSupported.
func (*MT5) UpdateProtection ¶
UpdateProtection moves a leg to level: the stop loss or the take profit of the positions it protects, or of the pending order opening its position, see service.ProtectionBroker. MT5 sets both levels together, so the other one is sent again where it is; the levels are checked with checkProtection first. A leg whose level was removed, eg: by hand in the terminal, is reported CANCELED (legState) and is ErrOrderNotOpen here.
type MT5Error ¶
type MT5Error struct {
Method string
Path string
Status int // HTTP status of the answer
Retcode int // trade retcode, or the terminal error code, 0 when unknown
Message string // error of the bridge, or comment of the trade result
NotSent bool // a trade request the bridge refused before order_send ("sent": false)
}
MT5Error is an error answer of the bridge (HTTP status, message, and the last_error code of the terminal when it has one), or a trade request the terminal did not execute (HTTP 200, the retcode and comment of order_send).
func (*MT5Error) Unwrap ¶
Unwrap maps the retcodes to the errors of the package: invalid volume to ErrInvalidQuantity, invalid stops to ErrInvalidProtection, no money to ErrInsufficientFunds, a bridge refusing the trading (read-only, HTTP 403) to ErrNotSupported, and refusing it on another account (HTTP 409) to ErrMT5AccountChanged.
type MT5OpenPosition ¶
type MT5OpenPosition struct {
Side model.SideType
Quantity float64
Entry float64
Profit float64
Currency string
}
MT5OpenPosition is the net position of the bot on a symbol as the terminal reports it: its side, its size in units of the asset, the average open price of its positions on that side, and their profit in the account currency, the swap included, at the price they close at (the bid of a long, the ask of a short), as the terminal shows it.
type MT5Option ¶
type MT5Option func(*MT5)
MT5Option configures NewMT5.
func WithMT5BaseURL ¶
WithMT5BaseURL sets the address of the bridge, MT5DefaultBaseURL by default.
func WithMT5Comment ¶
WithMT5Comment sets the comment of the bot's orders, a readable tag of at most 31 characters, "xtrader" by default. Ownership is decided by the magic number, not by the comment. Each order is commented with it followed by "#" and a tag of its own, eg: "xtrader#k3f9a2", cut to make room when needed: an order whose answer is lost is found by it (see trade).
func WithMT5DataOnly ¶
func WithMT5DataOnly() MT5Option
WithMT5DataOnly reads the market data only, eg: for the paper mode or a download: the adapter starts no book, never nets nor closes a position, and every trading call returns ErrNotSupported before any request.
func WithMT5Deviation ¶
WithMT5Deviation sets the deviation of the market orders, the most the fill may slip from the requested price, in points, 20 by default.
func WithMT5HTTPClient ¶
WithMT5HTTPClient sets the HTTP client of the requests to the bridge, one with a 30s timeout by default.
func WithMT5Leverage ¶
func WithMT5Leverage() MT5Option
WithMT5Leverage trades with the leverage of the account: an open position commits its margin rather than its whole value, and Position returns the free margin for new positions. Without it, positions commit their whole value, as on a spot market.
func WithMT5Magic ¶
WithMT5Magic sets the magic number of the bot, required to trade: only the positions and orders of this magic number are the bot's, so bots of magic numbers of their own share an account, next to the manual trades (magic 0).
func WithMT5PollInterval ¶
WithMT5PollInterval sets how often the positions and pending orders are polled, and CandlesSubscription the candles, a second by default.
func WithMT5Real ¶
func WithMT5Real() MT5Option
WithMT5Real allows a real account, refused otherwise.
func WithMT5Symbols ¶
WithMT5Symbols sets the symbols traded, eg: XAUUSDm, BTCUSDm.
func WithMT5Token ¶
WithMT5Token sends the token the bridge requires (its --token) in the X-Bridge-Token header.
type MT5PositionLevels ¶
type MT5PositionLevels struct {
Position int64
StopLoss, TakeProfit float64
PreviousStopLoss, PreviousTakeProfit float64
Closed bool // gone from the account
Restore error // setting back the previous levels failed
}
MT5PositionLevels is the state of a position after an MT5ProtectionError: its levels, 0 for none, and the ones it had before the change.
func (MT5PositionLevels) Kept ¶
func (p MT5PositionLevels) Kept() bool
Kept reports whether the position has the levels of before, or is closed.
func (MT5PositionLevels) String ¶
func (p MT5PositionLevels) String() string
type MT5ProtectionError ¶
type MT5ProtectionError struct {
Pair string
Err error
Positions []MT5PositionLevels
Unread error // reading the account again failed
}
MT5ProtectionError is a change of the levels of the positions of a protection (CreateOrderOCO, UpdateProtection, the Cancel of a leg) failed partway, or with its outcome unknown: the levels changed were set back to the ones of before where possible. Positions has the levels of each position after it, read again from the account (as last known, when Unread). It wraps the failure of the change, Err.
func (*MT5ProtectionError) Error ¶
func (e *MT5ProtectionError) Error() string
func (*MT5ProtectionError) Kept ¶
func (e *MT5ProtectionError) Kept() bool
Kept reports whether every position has the levels of before, or is closed.
func (*MT5ProtectionError) Unwrap ¶
func (e *MT5ProtectionError) Unwrap() error
type OrderError ¶
func (*OrderError) Error ¶
func (o *OrderError) Error() string
func (*OrderError) Unwrap ¶
func (o *OrderError) Unwrap() error
Unwrap exposes the underlying cause, so callers can match it with errors.Is.
type PaperExecution ¶
type PaperExecution struct {
Spread func(model.Candle) float64
Slippage func(model.Candle) float64
GapFills bool
Conservative bool
}
PaperExecution models the costs and the uncertainties of the fills of a backtest, see WithPaperExecution. The candles are of the bid, as MT5's:
- Spread returns the spread of a candle, in price: a buy fills at the ask (the bid plus the spread), a buy limit or stop is reached by the ask;
- Slippage returns the slippage of a candle, in price: it worsens the fills at the market and of the stops;
- GapFills fills a stop on the book before a candle opening beyond it at the open, not at its stop;
- Conservative assumes the worst of what a candle can't tell: the stop loss of a legacy OCO before its take profit, and an entry filled within a candle that also crossed its stop loss stopped on it.
type PaperWallet ¶
PaperWallet simulates the wallet of an exchange. Its methods are safe for concurrent use: the bot feeds it candles and orders while the dashboard and the Telegram bot read the account and the equity.
func NewPaperWallet ¶
func NewPaperWallet(ctx context.Context, baseCoin string, options ...PaperWalletOption) *PaperWallet
func (*PaperWallet) AssetValues ¶
func (p *PaperWallet) AssetValues(asset string) []AssetValue
AssetValues returns a copy of the values of asset, one per complete candle: OnCandle keeps appending to them.
func (*PaperWallet) AssetsInfo ¶
func (p *PaperWallet) AssetsInfo(pair string) model.AssetInfo
func (*PaperWallet) Cancel ¶
func (p *PaperWallet) Cancel(order model.Order) error
Cancel cancels an open order and releases its reserved funds. Cancelling a leg of an OCO cancels the whole group, as exchanges do. It fails with ErrOrderNotOpen for orders already filled or canceled, so their balances are never touched twice.
func (*PaperWallet) CandlesByLimit ¶
func (*PaperWallet) CandlesByPeriod ¶
func (*PaperWallet) CandlesSubscription ¶
func (*PaperWallet) CreateOrderLimit ¶
func (*PaperWallet) CreateOrderLimitProtected ¶
func (p *PaperWallet) CreateOrderLimitProtected(side model.SideType, pair string, size, limit, stop, profit float64) ([]model.Order, error)
CreateOrderLimitProtected places a limit order at limit, whose position is protected by a stop loss at stop and a take profit at profit once it fills, see service.ProtectionBroker.
func (*PaperWallet) CreateOrderMarket ¶
func (*PaperWallet) CreateOrderMarketProtected ¶
func (p *PaperWallet) CreateOrderMarketProtected(side model.SideType, pair string, size, stop, profit float64) ([]model.Order, error)
CreateOrderMarketProtected fills a market order and protects the position it opens with a stop loss at stop and a take profit at profit, as the brokers placing them with the order do, see service.ProtectionBroker: the levels set are the legs of an OCO order, reserving the position.
func (*PaperWallet) CreateOrderMarketQuote ¶
func (*PaperWallet) CreateOrderMarketReduce ¶
func (p *PaperWallet) CreateOrderMarketReduce(side model.SideType, pair string, size float64) (model.Order, error)
CreateOrderMarketReduce closes up to size units of the position held against side on pair at the market, never opening the other side, see service.ReduceOnlyBroker: the legs protecting the position, which reserve it, are canceled with it, as its stop loss and take profit go with a position closed on MT5, and the size is cut to the position. ErrNothingToReduce when none is held against side.
func (*PaperWallet) CreateOrderOCO ¶
func (*PaperWallet) CreateOrderStop ¶
func (*PaperWallet) CreateOrderStopProtected ¶
func (p *PaperWallet) CreateOrderStopProtected(side model.SideType, pair string, size, level, stop, profit float64) ([]model.Order, error)
CreateOrderStopProtected places a stop order triggered at level, whose position is protected by a stop loss at stop and a take profit at profit once it fills, see service.ProtectionBroker.
func (*PaperWallet) Equity ¶
func (p *PaperWallet) Equity() float64
Equity returns the value of the wallet now: its quote plus its assets at the last close of their pair, a short at its liquidation value, as the equity values count it.
func (*PaperWallet) EquityValues ¶
func (p *PaperWallet) EquityValues() []AssetValue
EquityValues returns a copy of the equity, one per complete candle.
func (*PaperWallet) LastClose ¶
func (p *PaperWallet) LastClose(pair string) (float64, bool)
LastClose returns the close of the last candle of pair the wallet took, false before any.
func (*PaperWallet) LiveProtection ¶
LiveProtection returns leg as it is now, see service.ProtectionReader: true once it protects the position held (on the book), false while it waits for its entry to fill.
func (*PaperWallet) MaxDrawdown ¶
func (*PaperWallet) OnCandle ¶
func (p *PaperWallet) OnCandle(candle model.Candle)
func (*PaperWallet) Pairs ¶
func (p *PaperWallet) Pairs() []string
func (*PaperWallet) Position ¶
func (p *PaperWallet) Position(pair string) (asset, quote float64, err error)
func (*PaperWallet) Protect ¶
func (p *PaperWallet) Protect(side model.SideType, pair string, size, stop, profit float64) ([]model.Order, error)
Protect protects size units of the position held on side of pair with a stop loss at stop and a take profit at profit, 0 for none, see service.PositionProtector: the legs CreateOrderMarketProtected places, on the book at once, reserving the position. As a broker requires, the levels are on their side of the last price, and the position is held, free of other legs.
func (*PaperWallet) SetStop ¶
func (p *PaperWallet) SetStop(side model.SideType, pair string, size, stop float64) ([]model.Order, error)
SetStop puts a stop loss at stop on the position held on side of pair, without one, see service.StopSetter: the legs Protect places when it has none; else a stop loss joining the take profit protecting it, in its group, sharing its reservation, before it on the book (a candle touching both fills the stop loss). It returns the legs placed.
func (*PaperWallet) Summary ¶
func (p *PaperWallet) Summary()
func (*PaperWallet) UpdateLimit ¶
UpdateLimit moves a pending limit order to limit, see service.ProtectionBroker: the funds it reserves follow it, and the legs waiting for it stay where they are.
func (*PaperWallet) UpdateProtection ¶
UpdateProtection moves a leg of a protection, or of an OCO order, to level: it fills there from the next candle on. As a broker requires, the level must be on its side of the entry of a leg waiting for it, else of the last price, and of the other leg.
type PaperWalletOption ¶
type PaperWalletOption func(*PaperWallet)
func WithDataFeed ¶
func WithDataFeed(feeder service.Feeder) PaperWalletOption
func WithPaperAsset ¶
func WithPaperAsset(pair string, amount float64) PaperWalletOption
func WithPaperExecution ¶
func WithPaperExecution(execution PaperExecution) PaperWalletOption
WithPaperExecution sets the model of the fills of a backtest, see PaperExecution.
func WithPaperFee ¶
func WithPaperFee(maker, taker float64) PaperWalletOption
type Subscription ¶
type Subscription struct {
// contains filtered or unexported fields
}