Type/to search
Getting Started
Platform Basics
Writing Strategies
Strategy Structure
Programming Languages
Strategy Parameters
Interactive Controls
Template Library
Built-in Libraries
UI Text Localization
API Quick Reference
Development Tools
Backtesting System
Advanced Topics
Data and Research
Extended API Interface

Every function, structure and constant of the API reference, grouped by its category, with a one-line description; click a name for the full page. This page is generated from the reference by doc_tools/gen_api_index.py.

Built-in Functions

Global
NameDescription
VersionReturns the current system version number.
IsVirtualUsed to determine whether the strategy's runtime environment is the backtesting system.
GetOSRetrieves the operating system information of the device hosting the bot.
GetPidGet the ID of the live trading process.
GetMetaGet the Meta value written when generating the strategy registration code.
SleepPauses program execution for a specified period of time.
UnixGet the second-level timestamp of the current moment.
UnixNanoGet the nanosecond-level timestamp of the current moment.
_DConvert a millisecond-level timestamp or a Date object into a time string.
GetCommandGet the strategy's interactive command.
GetLastErrorRetrieves the most recent error message.
SetErrorFilterFilters error logs.
_NFormat a floating-point number.
_CA retry function used for fault-tolerant handling of interface calls.
_CrossReturns the number of crossover periods between array arr1 and array arr2.
JSON.parseDecodes (parses) a JSON string; a method of the ECMAScript standard built-in object JSON.
JSON.stringifyConverts JavaScript values to JSON strings; a method of the ECMAScript standard built-in object JSON.
EncodeThis function encodes data according to the parameters passed in.
MD5Calculate the MD5 hash of the parameter data.
UUIDCreate a UUID.
Log
NameDescription
LogOutputs logs.
LogStatusRefreshes the status bar of a backtest or live trading page with text, tables, buttons or component objects with a type (KPI cards, charts, tabs and more); each call replaces the previous content.
LogProfitRecords and prints the profit/loss value, and plots the equity curve based on the profit/loss value.
LogProfitResetClear all profit logs and the profit chart.
LogResetClear the logs.
LogVacuumUsed to reclaim the storage space occupied by deleted data in SQLite after clearing logs with the LogReset() function.
EnableLogEnable or disable logging of order information.
ChartCustom chart plotting function.
KLineChartThis function is used to perform custom drawing while a strategy is running, using a drawing approach similar to the Pine language.
console.logUsed to output debug information in the "Debug Info" section of the live trading page.
console.errorUsed to output error messages in the "Debug Information" section of the live trading page.
exchange.LogOutputs order placement and cancellation logs in the log column area.
Market
NameDescription
exchange.GetTickerGets the Ticker structure (market data) of a spot instrument or contract; without symbol it uses the currently set trading pair and contract code.
exchange.GetTickersRetrieves aggregated market data from the exchange (an array of Ticker structures).
exchange.GetDepthGets the Depth structure, i.e. the order book data, of the spot or contract corresponding to the currently set trading pair and contract code.
exchange.GetTradesGets the Trade structure array of the spot or futures corresponding to the currently set trading pair and contract code, i.e. the market's trade (tick) data.
exchange.GetRecordsGet the Record structure array (i.e. K-line data) of the spot or contract corresponding to the currently set trading pair or contract code.
exchange.GetMarketsRetrieves market information from the exchange.
exchange.GetRawJSONGet the raw content returned by the most recent rest request from the current exchange object (exchange, exchanges).
exchange.SetDataSets the data loaded when the strategy is running.
exchange.GetDataRetrieves data loaded by the exchange.SetData() function, or data provided by an external link.
Trade
NameDescription
exchange.BuyPlaces a buy order.
exchange.SellPlaces a sell order.
exchange.CreateOrderPlaces orders.
exchange.ModifyOrderModifies an existing regular order, allowing you to modify the order's price and quantity.
exchange.CancelOrderCancels an order.
exchange.GetOrderObtains order information.
exchange.GetOrdersObtains the current unfilled orders.
exchange.GetHistoryOrdersRetrieves the historical orders of the current trading pair or contract, and supports specifying a particular trading instrument.
exchange.CreateConditionOrderCreates a conditional order.
exchange.ModifyConditionOrderModifies an existing conditional order, allowing modification of the order amount, trigger condition, and execution price of the conditional order.
exchange.CancelConditionOrderCancels a conditional order.
exchange.GetConditionOrderRetrieves information about a specified conditional order.
exchange.GetConditionOrdersObtains unfinished conditional orders (conditional orders that have not yet been triggered or canceled).
exchange.GetHistoryConditionOrdersRetrieves the historical conditional orders (including triggered, canceled, and expired conditional orders) for the current trading pair or contract, and supports specifying a particular trading instrument.
Account
NameDescription
exchange.GetAccountRequests the exchange account information.
exchange.GetAssetsRequests the asset information of the exchange account.
Futures
NameDescription
exchange.SetContractTypeSets the current contract code of the exchange object.
exchange.GetContractTypeGets the contract code currently set for the exchange object.
exchange.SetDirectionSets the order direction when calling the exchange.Buy function or exchange.Sell function to place futures contract orders.
exchange.SetMarginLevelSets the leverage value for the trading pair or contract specified by the symbol parameter.
exchange.GetPositionsGets position information.
exchange.GetFundingsObtains the funding rate data for the current period.
Exchange
NameDescription
exchange.GetNameGets the name of the exchange bound to the current exchange object.
exchange.GetLabelObtains the custom label set when configuring the exchange object.
exchange.GetCurrencyGets the currently set trading pair.
exchange.SetCurrencySwitches the current trading pair of the exchange object exchange.
exchange.GetQuoteCurrencyGets the name of the quote currency of the current trading pair, i.e. quoteCurrency.
exchange.GetPeriodRetrieves the K-line period configured on the FMZ Quant Trading platform website page when running a strategy in backtesting or live trading, i.e., the default K-line period used when calling the exchange.GetRecords() function without…
exchange.SetMaxBarLenSet the maximum length of the K-line (candlestick chart).
exchange.SetPrecisionSets the precision of the price and order amount for the exchange object.
exchange.GetRateGet the exchange rate currently set for the exchange object.
exchange.SetRateSet the current exchange rate of the exchange object.
exchange.SetBaseSets the base URL of the exchange API interface used by the exchange object.
exchange.GetBaseGets the base address of the current exchange API interface.
exchange.SetProxySets the proxy configuration of the exchange object.
exchange.SetTimeoutSets the timeout for rest requests of the exchange object.
exchange.EncodePerforms signature and encryption computations.
IO
NameDescription
exchange.IOCalls other interfaces related to the exchange object.
exchange.IO("api", ...)Calls a raw REST endpoint of the exchange that has no wrapper function; the platform signs the request.
exchange.IO("currency", ...)Switches the current trading pair of the exchange object at runtime.
exchange.IO("base", ...)Queries or switches the base address of the exchange API.
exchange.IO(mode, value)Switches the trading mode of an exchange, including demo/live trading, cross/isolated margin, hedge/one-way position mode, unified account, margin trading mode and self-trade prevention.
exchange.IO("rate", ...)Limits how often each API function is called: rate for smoothed limiting, quota for quota limiting.
Network
NameDescription
HttpQuerySends an HTTP request.
HttpQuery_GoSends an Http request.
DialUsed for raw Socket access, supporting the tcp and tls (also written as ssl) protocols as well as the WebSocket ws and wss protocols.
MailSend an email.
Mail_GoAsynchronous version of the Mail function.
Storage
NameDescription
_GPersistently store data.
DBExecDatabase interface function.
SetChannelDataPublishes the latest status data to a channel.
GetChannelDataSubscribes to the channel data of a specified live trading bot.
Threads
NameDescription
exchange.GoMulti-threaded asynchronous support function that can convert the operations of all supported functions into asynchronous concurrent execution.
EventLoopListens for events and returns when any WebSocket has readable data, or when concurrent tasks such as exchange.Go() or HttpQuery_Go() complete.
ctx.subscribeSubscribes to market data pushes for one instrument of an account, or to the order updates of an account, and returns an event stream ID.
ctx.pollTakes the next subscription event, optionally waiting with a timeout.
ctx.bookReads the order book maintained by the docker.
Threads/threading
NameDescription
threading.ThreadCreates concurrent threads.
threading.getThreadGets a thread object based on the specified thread ID.
threading.mainThreadGets the thread object of the main thread, which is the thread where the main() function in the strategy is located.
threading.currentThreadGets the thread object of the current thread.
threading.LockCreates a thread lock object.
threading.ConditionCreates a condition variable object, which is used to implement synchronization and communication between threads in a multi-threaded concurrent environment.
threading.EventCreates a thread event object, which is used for synchronization between threads, allowing one thread to wait for notification or signal from another thread.
threading.DictCreates a dictionary object for passing and sharing data between concurrent threads.
threading.ServeStarts an HTTP, TCP or WebSocket (over HTTP) service inside the strategy process and returns a Server object.
threading.pendingGets the number of concurrent threads currently running in the strategy program.
Threads/Thread
NameDescription
Thread.peekMessageReceives messages from a thread.
Thread.postMessageSends messages to a thread.
Thread.joinWaits for a thread to exit and reclaims its system resources.
Thread.terminateForcibly terminates a thread and releases the hardware resources occupied when the thread was created.
Thread.getDataAccesses variables recorded in the thread environment.
Thread.setDataStores variables in the thread environment.
Thread.idReturns the threadId of the current multi-threaded object instance.
Thread.nameReturns the name of the current multi-threaded object instance.
Thread.eventLoopListens for events received by the current thread (the thread of the caller).
Threads/ThreadLock
NameDescription
ThreadLock.acquireRequests a thread lock (acquire lock).
ThreadLock.releaseReleases a thread lock (unlock).
Threads/ThreadEvent
NameDescription
ThreadEvent.setSets an event signal.
ThreadEvent.clearClears the signal.
ThreadEvent.waitSets event (signal) waiting, which will block until the event (signal) is set; supports setting timeout parameters.
ThreadEvent.isSetDetermines whether an event (signal) has been set.
Threads/ThreadCondition
NameDescription
ThreadCondition.notifyWakes up one waiting thread (if any exists).
ThreadCondition.notifyAllWakes up all waiting threads.
ThreadCondition.waitPuts a thread into a waiting state under specific conditions.
ThreadCondition.acquireRequests a thread lock (acquire lock).
ThreadCondition.releaseReleases the thread lock (unlock).
Threads/ThreadDict
NameDescription
ThreadDict.getRetrieves the value of a key recorded in a dictionary object.
ThreadDict.setSets key-value pairs.
Threads/Server
NameDescription
Server.addrReturns the address and port the service actually listens on.
Server.closeStops accepting new connections; handlers already running finish normally (graceful shutdown).
Server.stopCloses the service (as close()) and then terminates every handler thread that is still running.
Server.joinWaits until the service is closed and no handler is running.
Server.pendingReturns the number of handlers currently running, i.e. connections or requests being handled.
TA
NameDescription
TA.MACDCalculates the Moving Average Convergence Divergence (MACD) indicator.
TA.KDJCalculates the Stochastic Oscillator (KDJ).
TA.RSICalculates the Relative Strength Index (RSI).
TA.ATRCalculates the Average True Range indicator (ATR).
TA.OBVCalculates the On-Balance Volume (OBV).
TA.MACalculates the Moving Average indicator (Moving Average).
TA.EMACalculates the Exponential Moving Average (EMA) indicator.
TA.BOLLCalculates the Bollinger Bands indicator.
TA.AlligatorCalculates the Alligator indicator.
TA.CMFCalculates the Chaikin Money Flow (CMF) indicator.
TA.HighestCalculates the highest price within a period.
TA.LowestCalculates the lowest price over a period.
TA.SMACalculates the Simple Moving Average (SMA) indicator.
Talib/OverlapStudies
NameDescription
talib.ACCBANDSCalculates the Acceleration Bands and returns the upper band, middle band and lower band.
talib.BBANDSCalculates the Bollinger Bands and returns the upper band, middle band and lower band.
talib.DEMACalculates the Double Exponential Moving Average.
talib.EMACalculates the Exponential Moving Average.
talib.HT_TRENDLINECalculates the Hilbert Transform - Instantaneous Trendline.
talib.KAMACalculates the Kaufman Adaptive Moving Average.
talib.MACalculates the Moving Average.
talib.MAMACalculates the MESA Adaptive Moving Average and returns the MAMA and FAMA.
talib.MAVPCalculates the Moving Average with Variable Period.
talib.MIDPOINTCalculates the MidPoint over Period.
talib.MIDPRICECalculates the Midpoint Price over Period.
talib.SARCalculates the Parabolic SAR.
talib.SAREXTCalculates the Parabolic SAR - Extended.
talib.SMACalculates the Simple Moving Average.
talib.T3Calculates the Triple Exponential Moving Average (T3).
talib.TEMACalculates the Triple Exponential Moving Average.
talib.TRIMACalculates the Triangular Moving Average.
talib.WMACalculates the Weighted Moving Average.
Talib/MomentumIndicators
NameDescription
talib.ADXCalculates the Average Directional Movement Index.
talib.ADXRCalculates the Average Directional Movement Index Rating.
talib.APOCalculates the Absolute Price Oscillator.
talib.AROONCalculates the Aroon and returns the Aroon Down and Aroon Up.
talib.AROONOSCCalculates the Aroon Oscillator.
talib.BOPCalculates the Balance Of Power.
talib.CCICalculates the Commodity Channel Index.
talib.CMOCalculates the Chande Momentum Oscillator.
talib.DXCalculates the Directional Movement Index.
talib.IMICalculates the Intraday Momentum Index.
talib.MACDCalculates the Moving Average Convergence/Divergence and returns the MACD line, signal line and histogram.
talib.MACDEXTCalculates the MACD with Controllable MA Type and returns the MACD line, signal line and histogram.
talib.MACDFIXCalculates the Moving Average Convergence/Divergence Fix 12/26 and returns the MACD line, signal line and histogram.
talib.MFICalculates the Money Flow Index.
talib.MINUS_DICalculates the Minus Directional Indicator.
talib.MINUS_DMCalculates the Minus Directional Movement.
talib.MOMCalculates the Momentum.
talib.PLUS_DICalculates the Plus Directional Indicator.
talib.PLUS_DMCalculates the Plus Directional Movement.
talib.PPOCalculates the Percentage Price Oscillator.
talib.ROCCalculates the Rate of Change, defined as ((price/prevPrice)-1)*100.
talib.ROCPCalculates the Rate of Change Percentage, defined as (price-prevPrice)/prevPrice.
talib.ROCRCalculates the Rate of Change Ratio, defined as price/prevPrice.
talib.ROCR100Calculates the Rate of Change Ratio 100 Scale, defined as (price/prevPrice)*100.
talib.RSICalculates the Relative Strength Index.
talib.STOCHCalculates the Stochastic and returns the slow %K and slow %D.
talib.STOCHFCalculates the Stochastic Fast and returns the fast %K and fast %D.
talib.STOCHRSICalculates the Stochastic Relative Strength Index and returns the fast %K and fast %D.
talib.TRIXCalculates the 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA.
talib.ULTOSCCalculates the Ultimate Oscillator.
talib.WILLRCalculates the Williams' %R.
Talib/VolumeIndicators
NameDescription
talib.ADCalculates the Chaikin A/D Line.
talib.ADOSCCalculates the Chaikin A/D Oscillator.
talib.OBVCalculates the On Balance Volume.
Talib/VolatilityIndicators
NameDescription
talib.ATRCalculates the Average True Range.
talib.NATRCalculates the Normalized Average True Range.
talib.TRANGECalculates the True Range.
Talib/CycleIndicators
NameDescription
talib.HT_DCPERIODCalculates the Hilbert Transform - Dominant Cycle Period.
talib.HT_DCPHASECalculates the Hilbert Transform - Dominant Cycle Phase.
talib.HT_PHASORCalculates the Hilbert Transform - Phasor Components and returns the in-phase component and quadrature component.
talib.HT_SINECalculates the Hilbert Transform - SineWave and returns the sine and lead sine.
talib.HT_TRENDMODECalculates the Hilbert Transform - Trend vs Cycle Mode.
Talib/PriceTransform
NameDescription
talib.AVGDEVCalculates the Average Deviation.
talib.AVGPRICECalculates the Average Price.
talib.MEDPRICECalculates the Median Price.
talib.TYPPRICECalculates the Typical Price.
talib.WCLPRICECalculates the Weighted Close Price.
Talib/StatisticFunctions
NameDescription
talib.BETACalculates the Beta.
talib.CORRELCalculates the Pearson's Correlation Coefficient (r).
talib.LINEARREGCalculates the Linear Regression.
talib.LINEARREG_ANGLECalculates the Linear Regression Angle.
talib.LINEARREG_INTERCEPTCalculates the Linear Regression Intercept.
talib.LINEARREG_SLOPECalculates the Linear Regression Slope.
talib.STDDEVCalculates the Standard Deviation.
talib.TSFCalculates the Time Series Forecast.
talib.VARCalculates the Variance.
Talib/MathTransform
NameDescription
talib.ACOSCalculates the arc cosine of each element (Vector Trigonometric ACos).
talib.ASINCalculates the arc sine of each element (Vector Trigonometric ASin).
talib.ATANCalculates the arc tangent of each element (Vector Trigonometric ATan).
talib.CEILRounds each element up to an integer (Vector Ceil).
talib.COSCalculates the cosine of each element (Vector Trigonometric Cos).
talib.COSHCalculates the hyperbolic cosine of each element (Vector Trigonometric Cosh).
talib.EXPCalculates the exponential (e to the power of x) of each element (Vector Arithmetic Exp).
talib.FLOORRounds each element down to an integer (Vector Floor).
talib.LNCalculates the natural logarithm of each element (Vector Log Natural).
talib.LOG10Calculates the base-10 logarithm of each element (Vector Log10).
talib.SINCalculates the sine of each element (Vector Trigonometric Sin).
talib.SINHCalculates the hyperbolic sine of each element (Vector Trigonometric Sinh).
talib.SQRTCalculates the square root of each element (Vector Square Root).
talib.TANCalculates the tangent of each element (Vector Trigonometric Tan).
talib.TANHCalculates the hyperbolic tangent of each element (Vector Trigonometric Tanh).
Talib/MathOperators
NameDescription
talib.ADDAdds two arrays element by element (Vector Arithmetic Add).
talib.DIVDivides the first array by the second, element by element (Vector Arithmetic Div).
talib.MAXCalculates the Highest Value over a Specified Period.
talib.MAXINDEXCalculates the Index of Highest Value over a Specified Period.
talib.MINCalculates the Lowest Value over a Specified Period.
talib.MININDEXCalculates the Index of Lowest Value over a Specified Period.
talib.MINMAXCalculates the Lowest and Highest Values over a Specified Period and returns the minimum and maximum.
talib.MINMAXINDEXCalculates the Indexes of Lowest and Highest Values over a Specified Period and returns the minimum index and maximum index.
talib.MULTMultiplies two arrays element by element (Vector Arithmetic Mult).
talib.SUBSubtracts the second array from the first, element by element (Vector Arithmetic Subtraction).
talib.SUMCalculates the Summation.
Talib/PatternRecognition
NameDescription
talib.CDL2CROWSDetects the Two Crows candlestick pattern.
talib.CDL3BLACKCROWSDetects the Three Black Crows candlestick pattern.
talib.CDL3INSIDEDetects the Three Inside Up/Down candlestick pattern.
talib.CDL3LINESTRIKEDetects the Three-Line Strike candlestick pattern.
talib.CDL3OUTSIDEDetects the Three Outside Up/Down candlestick pattern.
talib.CDL3STARSINSOUTHDetects the Three Stars In The South candlestick pattern.
talib.CDL3WHITESOLDIERSDetects the Three Advancing White Soldiers candlestick pattern.
talib.CDLABANDONEDBABYDetects the Abandoned Baby candlestick pattern.
talib.CDLADVANCEBLOCKDetects the Advance Block candlestick pattern.
talib.CDLBELTHOLDDetects the Belt-hold candlestick pattern.
talib.CDLBREAKAWAYDetects the Breakaway candlestick pattern.
talib.CDLCLOSINGMARUBOZUDetects the Closing Marubozu candlestick pattern.
talib.CDLCONCEALBABYSWALLDetects the Concealing Baby Swallow candlestick pattern.
talib.CDLCOUNTERATTACKDetects the Counterattack candlestick pattern.
talib.CDLDARKCLOUDCOVERDetects the Dark Cloud Cover candlestick pattern.
talib.CDLDOJIDetects the Doji candlestick pattern.
talib.CDLDOJISTARDetects the Doji Star candlestick pattern.
talib.CDLDRAGONFLYDOJIDetects the Dragonfly Doji candlestick pattern.
talib.CDLENGULFINGDetects the Engulfing Pattern candlestick pattern.
talib.CDLEVENINGDOJISTARDetects the Evening Doji Star candlestick pattern.
talib.CDLEVENINGSTARDetects the Evening Star candlestick pattern.
talib.CDLGAPSIDESIDEWHITEDetects the Up/Down-gap side-by-side white lines candlestick pattern.
talib.CDLGRAVESTONEDOJIDetects the Gravestone Doji candlestick pattern.
talib.CDLHAMMERDetects the Hammer candlestick pattern.
talib.CDLHANGINGMANDetects the Hanging Man candlestick pattern.
talib.CDLHARAMIDetects the Harami Pattern candlestick pattern.
talib.CDLHARAMICROSSDetects the Harami Cross Pattern candlestick pattern.
talib.CDLHIGHWAVEDetects the High-Wave Candle candlestick pattern.
talib.CDLHIKKAKEDetects the Hikkake Pattern candlestick pattern.
talib.CDLHIKKAKEMODDetects the Modified Hikkake Pattern candlestick pattern.
talib.CDLHOMINGPIGEONDetects the Homing Pigeon candlestick pattern.
talib.CDLIDENTICAL3CROWSDetects the Identical Three Crows candlestick pattern.
talib.CDLINNECKDetects the In-Neck Pattern candlestick pattern.
talib.CDLINVERTEDHAMMERDetects the Inverted Hammer candlestick pattern.
talib.CDLKICKINGDetects the Kicking candlestick pattern.
talib.CDLKICKINGBYLENGTHDetects the Kicking - bull/bear determined by the longer marubozu candlestick pattern.
talib.CDLLADDERBOTTOMDetects the Ladder Bottom candlestick pattern.
talib.CDLLONGLEGGEDDOJIDetects the Long Legged Doji candlestick pattern.
talib.CDLLONGLINEDetects the Long Line Candle candlestick pattern.
talib.CDLMARUBOZUDetects the Marubozu candlestick pattern.
talib.CDLMATCHINGLOWDetects the Matching Low candlestick pattern.
talib.CDLMATHOLDDetects the Mat Hold candlestick pattern.
talib.CDLMORNINGDOJISTARDetects the Morning Doji Star candlestick pattern.
talib.CDLMORNINGSTARDetects the Morning Star candlestick pattern.
talib.CDLONNECKDetects the On-Neck Pattern candlestick pattern.
talib.CDLPIERCINGDetects the Piercing Pattern candlestick pattern.
talib.CDLRICKSHAWMANDetects the Rickshaw Man candlestick pattern.
talib.CDLRISEFALL3METHODSDetects the Rising/Falling Three Methods candlestick pattern.
talib.CDLSEPARATINGLINESDetects the Separating Lines candlestick pattern.
talib.CDLSHOOTINGSTARDetects the Shooting Star candlestick pattern.
talib.CDLSHORTLINEDetects the Short Line Candle candlestick pattern.
talib.CDLSPINNINGTOPDetects the Spinning Top candlestick pattern.
talib.CDLSTALLEDPATTERNDetects the Stalled Pattern candlestick pattern.
talib.CDLSTICKSANDWICHDetects the Stick Sandwich candlestick pattern.
talib.CDLTAKURIDetects the Takuri (Dragonfly Doji with very long lower shadow) candlestick pattern.
talib.CDLTASUKIGAPDetects the Tasuki Gap candlestick pattern.
talib.CDLTHRUSTINGDetects the Thrusting Pattern candlestick pattern.
talib.CDLTRISTARDetects the Tristar Pattern candlestick pattern.
talib.CDLUNIQUE3RIVERDetects the Unique 3 River candlestick pattern.
talib.CDLUPSIDEGAP2CROWSDetects the Upside Gap Two Crows candlestick pattern.
talib.CDLXSIDEGAP3METHODSDetects the Upside/Downside Gap Three Methods candlestick pattern.
OS
NameDescription
ListFilesResultFile list object used to record directory listing information.
FileStatFile statistics information object.
OS/os
NameDescription
os.openOpen a file in the specified mode.
os.fgetsRead the entire file content at once.
os.fputsWrite content to a file.
os.mmapReads the whole file and returns its binary data as an ArrayBuffer.
os.getRootDirGet the root directory path for file operations.
os.listFilesList files and subdirectories in the specified directory.
os.existsCheck if the specified file or directory exists.
os.removeDelete the specified file or empty directory.
os.mkdirCreate a directory.
os.rmdirRemove a directory and all its contents.
os.renameRename a file or move a file.
os.statGet detailed statistics information of a file.
os.exitExit the program.
OS/File
NameDescription
File.closeClose the file and release associated resources.
File.putsWrite one or more strings to a file.
File.printfWrite formatted data to file.
File.flushFlush the file buffer to ensure data is written to disk.
File.tellGet the current file pointer position.
File.seekMove the file pointer to a specified position.
File.eofCheck if the file pointer has reached the end of file.
File.readRead data from a file.
File.writeWrite string data to a file.
File.getlineRead the next line from the file.
File.toStringGet the string representation of the file object.

Structures

NameDescription
TickerMarket data returned by exchange.GetTicker(): high, low, best ask, best bid, last price, open, volume and open interest.
DepthMarket depth returned by exchange.GetDepth(): the asks Asks and bids Bids (OrderBook arrays) and a timestamp.
OrderBookOne price level of the asks or bids in market depth (Depth): price and amount.
TradeReturned by exchange.GetTrades(): a market trade's ID, time, price, amount and side.
RecordData structure for candlestick bars in standard OHLC format, used for charting candlesticks and calculating technical indicators.
MarketReturned by exchange.GetMarkets(): an instrument's base and quote assets, price and amount steps and precisions, order quantity and notional limits, and contract value.
OrderReturned by exchange.GetOrder(), exchange.GetOrders() and similar: order ID, price, amount, filled amount, average price, status, type, offset, contract code and conditional order settings.
ConditionConditional order settings: the conditional order type and the take-profit and stop-loss trigger and order prices, used to set the trigger conditions and execution prices of conditional orders.
AccountReturned by exchange.GetAccount(): the available and frozen amounts of the quote and base currencies, plus equity and unrealized profit and loss on futures.
AssetOne item of the array returned by exchange.GetAssets(): the available and frozen amounts of one currency.
PositionReturned by exchange.GetPositions(): instrument, leverage, amount and frozen amount, average price, unrealized profit, direction, contract code and margin.
FundingReturned by exchange.GetFundings(): instrument, settlement interval, time and funding rate; only cryptocurrency perpetual contracts have funding rates.
OtherStruct
NameDescription
HttpQuery-optionsThis JSON structure is used to configure various parameters for HTTP requests sent by HttpQuery and HttpQuery_Go functions.
HttpQuery-returnThis JSON structure is the data structure returned by the HttpQuery function in debug mode, when the debug field is set to true in the options parameter structure while calling the HttpQuery function.
LogStatus-tableStatus bar table output with LogStatus: columns can set number formats, up/down colors and units; cells can be merged or hold buttons; several tables can be shown as tabs.
LogStatus-btnTypeOneOlder form of the status bar button structure (input controls without settings), still supported.
LogStatus-btnTypeTwoJSON structure of a status bar button (current form, with settings on input controls).
Chart-optionsThis JSON is used to configure chart settings for the custom plotting function Chart().
Chart-returnThe chart object returned by Chart, used to write data, update the configuration and clear the chart.
KLineChart-optionsThis JSON is used to configure the chart settings for the custom drawing function KLineChart.
KLineChart-returnThe chart object returned by KLineChart, which draws on K-lines in a Pine-like way.
SetData-dataThis JSON is used to set the data to be loaded by the exchange.SetData() function.
EventLoop-returnThis JSON is the data structure returned by the EventLoop() function.
exchange.Go-returnThe concurrent object returned by exchange.Go; its wait() method returns the result of the concurrent call.
DBExec-returnThis JSON is the data structure returned by the DBExec() function; this JSON data structure is also returned when executing SQL statements using the exec() method of objects created by the Dial() function.
Dial-returnThe connection object returned by Dial.
Thread.join-returnThis JSON is the data structure returned by the join() member function of the Thread object, used to store information related to concurrent threads in JavaScript language strategies.
OtherStruct/LogStatus-display
NameDescription
gridArranges components in columns and drops columns automatically when the container gets narrow.
tabsGroups components into tabs; the selected tab is kept when the status bar refreshes.
kpiShows one prominent number with optional unit, change and hint, for equity, returns or the last price.
statLists label and value pairs, for details such as balances, frozen funds, leverage or liquidation price.
progressShows a ratio, or current value / total, as a bar.
gaugeShows where a value sits in a range on a half-circle dial, with optional threshold colors; for RSI, exposure or risk.
sparklineShows a number with a small trend line, colored by the first-to-last change by default.
chartDraws line, bar or area charts with several series, a right axis and buy/sell marks; use Chart for more options.
heatmapShades a 2D grid by value, for returns by period and symbol or correlation matrices.
calendarShows returns as daily heat cells (like a contribution graph) or as a year × month table.
histogramBins raw data automatically and shows the counts with sample size, mean, median and share of positive values.
pieShows the share of each part in the total; a donut by default with the total in the center.
timelineLists events in order, for fills, trading signals or risk events.
markdownRenders Markdown text with headings, lists, bold and tables, for strategy notes and market commentary.
alertShows an info, success, warning or error message with an icon, for risk and error notices.
badgeShows small labels with a dot inline, so they can follow a line of text.

Built-in Variables and Constants

EXCHANGE
NameDescription
exchangeThe first exchange object added in the strategy live trading settings and backtesting settings.
exchangesAn array of exchange objects that contains all the exchange objects added in the strategy's live trading settings or backtesting settings, where exchanges[0] is exchange.
ORDER_STATE
NameDescription
ORDER_STATE_PENDINGThe order is pending (open, possibly partially filled); the value is 0.
ORDER_STATE_CLOSEDThe order is completed (fully filled); the value is 1.
ORDER_STATE_CANCELEDThe order is canceled; the value is 2.
ORDER_STATE_UNKNOWNThe order status is unknown (any other status); the value is 3.
ORDER_TYPE
NameDescription
ORDER_TYPE_BUYA buy order; the value is 0.
ORDER_TYPE_SELLA sell order; the value is 1.
ORDER_CONDITION_TYPE
NameDescription
ORDER_CONDITION_TYPE_OCOAn OCO order (One-Cancels-the-Other): take-profit and stop-loss conditions are set together, and when one triggers the other is canceled automatically; the value is 0.
ORDER_CONDITION_TYPE_TPA take-profit order: an order is placed when the price reaches the take-profit trigger price; the value is 1.
ORDER_CONDITION_TYPE_SLA stop-loss order: an order is placed when the price reaches the stop-loss trigger price, to limit losses; the value is 2.
ORDER_CONDITION_TYPE_GENERICA generic conditional order: its behavior depends on the exchange, and it only appears in query results; the value is 3.
POSITION_DIRECTION
NameDescription
PD_LONGA long position; the value is 0.
PD_SHORTA short position; the value is 1.
ORDER_OFFSET
NameDescription
ORDER_OFFSET_OPENAn opening order; the value is 0.
ORDER_OFFSET_CLOSEA closing order; the value is 1.
PERIOD
NameDescription
PERIOD_M11-minute K-line period; the value is 60.
PERIOD_M33-minute K-line period; the value is 180.
PERIOD_M55-minute K-line period; the value is 300.
PERIOD_M1515-minute K-line period; the value is 900.
PERIOD_M3030-minute K-line period; the value is 1800.
PERIOD_H11-hour K-line period; the value is 3600.
PERIOD_H22-hour K-line period; the value is 7200.
PERIOD_H44-hour K-line period; the value is 14400.
PERIOD_H66-hour K-line period; the value is 21600.
PERIOD_H1212-hour K-line period; the value is 43200.
PERIOD_D11-day K-line period; the value is 86400.
PERIOD_D33-day K-line period; the value is 259200.
PERIOD_W11-week K-line period; the value is 604800.
LOG_TYPE
NameDescription
LOG_TYPE_BUYA buy order log; the value is 0.
LOG_TYPE_SELLA sell order log; the value is 1.
LOG_TYPE_CANCELAn order cancellation log; the value is 2.

Conventions

NameDescription
SymbolsFunctions of exchange objects specify an instrument with the string parameter symbol.
Failures and null values### Failed calls return a null value

Exchanges

NameDescription
Capability MatrixSupport of the standard functions and trading-mode commands per exchange object.