Type/to search
Built-in Functions
Global
Version
Sleep
IsVirtual
Mail
Mail_Go
SetErrorFilter
GetPid
GetLastError
GetCommand
GetMeta
Dial
HttpQuery
HttpQuery_Go
Encode
UnixNano
Unix
GetOS
MD5
DBExec
UUID
EventLoop
__Serve
_G
_D
_N
_C
_Cross
JSON.parse
JSON.stringify
SetChannelData
GetChannelData
Log
Market
Trade
Account
Futures
NetSettings
Threads
threading
Thread
getThread
mainThread
currentThread
Lock
Condition
Event
Dict
pending
Thread
ThreadLock
ThreadEvent
ThreadCondition
ThreadDict
Web3
TA
Talib
talib.CDL2CROWS
talib.CDL3BLACKCROWS
talib.CDL3INSIDE
talib.CDL3LINESTRIKE
talib.CDL3OUTSIDE
talib.CDL3STARSINSOUTH
talib.CDL3WHITESOLDIERS
talib.CDLABANDONEDBABY
talib.CDLADVANCEBLOCK
talib.CDLBELTHOLD
talib.CDLBREAKAWAY
talib.CDLCLOSINGMARUBOZU
talib.CDLCONCEALBABYSWALL
talib.CDLCOUNTERATTACK
talib.CDLDARKCLOUDCOVER
talib.CDLDOJI
talib.CDLDOJISTAR
talib.CDLDRAGONFLYDOJI
talib.CDLENGULFING
talib.CDLEVENINGDOJISTAR
talib.CDLEVENINGSTAR
talib.CDLGAPSIDESIDEWHITE
talib.CDLGRAVESTONEDOJI
talib.CDLHAMMER
talib.CDLHANGINGMAN
talib.CDLHARAMI
talib.CDLHARAMICROSS
talib.CDLHIGHWAVE
talib.CDLHIKKAKE
talib.CDLHIKKAKEMOD
talib.CDLHOMINGPIGEON
talib.CDLIDENTICAL3CROWS
talib.CDLINNECK
talib.CDLINVERTEDHAMMER
talib.CDLKICKING
talib.CDLKICKINGBYLENGTH
talib.CDLLADDERBOTTOM
talib.CDLLONGLEGGEDDOJI
talib.CDLLONGLINE
talib.CDLMARUBOZU
talib.CDLMATCHINGLOW
talib.CDLMATHOLD
talib.CDLMORNINGDOJISTAR
talib.CDLMORNINGSTAR
talib.CDLONNECK
talib.CDLPIERCING
talib.CDLRICKSHAWMAN
talib.CDLRISEFALL3METHODS
talib.CDLSEPARATINGLINES
talib.CDLSHOOTINGSTAR
talib.CDLSHORTLINE
talib.CDLSPINNINGTOP
talib.CDLSTALLEDPATTERN
talib.CDLSTICKSANDWICH
talib.CDLTAKURI
talib.CDLTASUKIGAP
talib.CDLTHRUSTING
talib.CDLTRISTAR
talib.CDLUNIQUE3RIVER
talib.CDLUPSIDEGAP2CROWS
talib.CDLXSIDEGAP3METHODS
talib.AD
talib.ADOSC
talib.OBV
talib.ACOS
talib.ASIN
talib.ATAN
talib.CEIL
talib.COS
talib.COSH
talib.EXP
talib.FLOOR
talib.LN
talib.LOG10
talib.SIN
talib.SINH
talib.SQRT
talib.TAN
talib.TANH
talib.MAX
talib.MAXINDEX
talib.MIN
talib.MININDEX
talib.MINMAX
talib.MINMAXINDEX
talib.SUM
talib.HT_DCPERIOD
talib.HT_DCPHASE
talib.HT_PHASOR
talib.HT_SINE
talib.HT_TRENDMODE
talib.ATR
talib.NATR
talib.TRANGE
talib.BBANDS
talib.DEMA
talib.EMA
talib.HT_TRENDLINE
talib.KAMA
talib.MA
talib.MAMA
talib.MIDPOINT
talib.MIDPRICE
talib.SAR
talib.SAREXT
talib.SMA
talib.T3
talib.TEMA
talib.TRIMA
talib.WMA
talib.LINEARREG
talib.LINEARREG_ANGLE
talib.LINEARREG_INTERCEPT
talib.LINEARREG_SLOPE
talib.STDDEV
talib.TSF
talib.VAR
talib.ADX
talib.ADXR
talib.APO
talib.AROON
talib.AROONOSC
talib.BOP
talib.CCI
talib.CMO
talib.DX
talib.MACD
talib.MACDEXT
talib.MACDFIX
talib.MFI
talib.MINUS_DI
talib.MINUS_DM
talib.MOM
talib.PLUS_DI
talib.PLUS_DM
talib.PPO
talib.ROC
talib.ROCP
talib.ROCR
talib.ROCR100
talib.RSI
talib.STOCH
talib.STOCHF
talib.STOCHRSI
talib.TRIX
talib.ULTOSC
talib.WILLR
talib.AVGPRICE
talib.MEDPRICE
talib.TYPPRICE
talib.WCLPRICE
OS
Structures
Built-in Variables

The threading object serves as a global multi-threading management tool, providing functions for creating concurrent threads, thread locks, condition variables, and more. This section introduces the member functions of the threading object. Only JavaScript language strategies support this object.

The Thread() function is used to create concurrent threads.

Thread(func, ...args)
Thread(...items)

Examples

  • Create a concurrent thread with both a custom function and an anonymous function simultaneously.

    javascript
    function test1(a, b, c) { Log("test1:", a, b, c) } function main() { var t1 = threading.Thread(test1, 1, 2, 3) var t2 = threading.Thread(function (msg) { Log("msg:", msg) }, "Hello thread2") t1.join() t2.join() }
  • Use Thread(...items) format to create concurrent threads that execute multiple functions sequentially.

    javascript
    function test1(msg) { Log("msg:", msg) test2("Hello test2") } function main() { var t1 = threading.Thread( [function(a, b, c) {Log(a, b, c)}, 1, 2, 3], [test1, "Hello test1"], [`function test2(msg) {Log("msg:", msg)}`]) t1.join() }
  • Support passing functions as parameters to concurrently executing functions.

    javascript
    function testFunc1(p) { Log("testFunc1 p:", p) } function main() { threading.Thread(function(pfn) { var threadName = threading.currentThread().name() var threadId = threading.currentThread().id() pfn(`in thread threadName: ${threadName}, threadId: ${threadId}`) }, testFunc1).join() }
  • Support passing function strings to dynamically import external libraries for concurrent computation.

    javascript
    function ml(input) { const net = new brain.NeuralNetwork() net.train([ { input: [0, 0], output: [0] }, { input: [0, 1], output: [1] }, { input: [1, 0], output: [1] }, { input: [1, 1], output: [0] }, ]) return net.run(input) } function main() { var ret = threading.Thread([ml, [1, 0]], [HttpQuery("https://unpkg.com/brain.js")]).join() // ret: {"id":1,"terminated":false,"elapsed":337636000,"ret":{"0":0.9339330196380615}} Log(ret) }

Returns

TypeDescription

Thread object

The Thread() function returns a Thread object for managing created concurrent threads, thread communication, etc.

Arguments

NameTypeRequiredDescription

func

function

Yes

The parameter func is a function for concurrent execution (passed by reference), supporting anonymous functions. func can accept multiple parameters, which will be passed through ...args during concurrent execution. Therefore, the parameter list of func needs to be consistent with ...args.

arg

string / number / bool / object / array / function / any (any type supported by the platform)

No

The parameter arg is the actual parameter passed to func (the concurrent thread execution function) during callback execution; there can be multiple arg parameters, and the parameter list of func needs to be consistent with ...args.

item

array

Yes

The parameter item is an array containing the function reference to be executed concurrently and its parameters. When calling the Thread function, multiple sets of item parameters can be passed.

See Also

Remarks

The thread function func passed to the Thread() function for concurrent execution runs in an isolated environment, so it cannot directly reference variables outside the thread, which will cause compilation failure when referenced. Additionally, referencing other closure functions is not supported within the thread. All APIs provided by the platform can be called inside the thread, but user-defined functions cannot be called.

When a thread completes execution and is not continuously referenced, the system will automatically reclaim thread-related resources at the underlying level, without the need to explicitly call the join() function to release resources. If there are continuous references preventing resource release, an error will be reported when the number of concurrent threads exceeds 2000: InternalError: too many routine wait, max is 2000.

Supports backtesting system and live trading environment; all concurrent thread-related functions in the backtesting system are only provided for code compatibility support and will not actually execute concurrent threads, which will not be elaborated further in this chapter.

The getThread() function is used to get a thread object based on the specified thread ID.

getThread(threadId)

Examples

Get the specified thread object by threadId.

javascript
function main() { var t1 = threading.Thread(function () { // Thread object has method: id(), used to get the thread's Id, you can check the documentation for the corresponding Thread object section var id = threading.currentThread().id() var thread1 = threading.getThread(id) Log("id:", id, ", thread1.id():", thread1.id()) Log(`id == thread1.id():`, id == thread1.id()) }) t1.join() }

Returns

TypeDescription

Thread object

The getThread() function returns the Thread object specified by the parameter threadId

Arguments

NameTypeRequiredDescription

threadId

number

Yes

The parameter threadId is the thread object ID, which is used to get the corresponding thread object.

See Also

Remarks

Supports backtesting system and live trading environment.

If the target thread has finished executing and been released, the thread object cannot be obtained through threading.getThread(threadId).

The mainThread() function is used to get the thread object of the main thread, which is the thread where the main() function in the strategy is located.

mainThread()

Examples

  • Get the Thread object of the main thread and output the threadId of the main thread.

    javascript
    function main() { Log("Main thread ID:", threading.mainThread().id()) }
  • The thread object of the main thread can also be obtained in concurrent threads.

    javascript
    function test() { Log("Main thread ID output in test function:", threading.mainThread().id()) } function main() { var t1 = threading.Thread(test) t1.join() }

Returns

TypeDescription

Thread object

The mainThread() function returns the thread object of the main thread.

See Also

Remarks

Supported in backtesting system and live trading environment.

The currentThread() function is used to get the thread object of the current thread.

currentThread()

Examples

Get the Thread object of the current thread and output the threadId of the current thread.

javascript
function test() { Log("Current thread ID:", threading.currentThread().id()) } function main() { var t1 = threading.Thread(test) t1.join() }

Returns

TypeDescription

Thread object

The currentThread() function returns the thread object of the current thread.

See Also

Remarks

Supports backtesting system and live trading environment.

The Lock() function is used to create a thread lock object.

Lock()

Examples

Two concurrent threads accessing shared resources.

javascript
function consumer(productionQuantity, dict, lock) { for (var i = 0; i < productionQuantity; i++) { lock.acquire() var count = dict.get("count") Log("consumer:", count) Sleep(1000) lock.release() } } function producer(productionQuantity, dict, lock) { for (var i = 0; i < productionQuantity; i++) { lock.acquire() dict.set("count", i) Log("producer:", i) Sleep(1000) lock.release() } } function main() { var dict = threading.Dict() dict.set("count", -1) var lock = threading.Lock() var productionQuantity = 10 var producerThread = threading.Thread(producer, productionQuantity, dict, lock) var consumerThread = threading.Thread(consumer, productionQuantity, dict, lock) consumerThread.join() producerThread.join() }

Returns

TypeDescription

ThreadLock object

The Lock() function returns a thread lock object.

See Also

Remarks

Supports backtesting system and live trading environment.

The Condition() function is used to create a condition variable object, which is used to implement synchronization and communication between threads in a multi-threaded concurrent environment. Through Condition(), a thread can enter a waiting state when specific conditions are not met, until another thread signals that the conditions have been met.

Condition()

Examples

Two concurrent threads accessing shared resources.

javascript
function consumer(productionQuantity, dict, condition) { for (var i = 0; i < productionQuantity; i++) { condition.acquire() while (dict.get("array").length == 0) { condition.wait() } var arr = dict.get("array") var count = arr.shift() dict.set("array", arr) Log("consumer:", count, ", array:", arr) condition.release() Sleep(1000) } } function producer(productionQuantity, dict, condition) { for (var i = 0; i < productionQuantity; i++) { condition.acquire() var arr = dict.get("array") arr.push(i) dict.set("array", arr) Log("producer:", i, ", array:", arr) condition.notify() condition.release() Sleep(1000) } } function main() { var dict = threading.Dict() dict.set("array", []) var condition = threading.Condition() var productionQuantity = 10 var producerThread = threading.Thread(producer, productionQuantity, dict, condition) var consumerThread = threading.Thread(consumer, productionQuantity, dict, condition) consumerThread.join() producerThread.join() }

Returns

TypeDescription

ThreadCondition object

The Condition() function returns a ThreadCondition object.

See Also

Remarks

The backtesting system does not currently support this feature, only the interface definition is provided.

The Event() function is used to create a thread event object, which is used for synchronization between threads, allowing one thread to wait for notification or signal from another thread.

Event()

Examples

Two concurrent threads accessing shared resources.

javascript
function consumer(productionQuantity, dict, pEvent, cEvent) { for (var i = 0; i < productionQuantity; i++) { while (dict.get("array").length == 0) { pEvent.wait() } if (pEvent.isSet()) { pEvent.clear() } var arr = dict.get("array") var count = arr.shift() dict.set("array", arr) Log("consumer:", count, ", array:", arr) cEvent.set() Sleep(1000) } } function producer(productionQuantity, dict, pEvent, cEvent) { for (var i = 0; i < productionQuantity; i++) { while (dict.get("array").length != 0) { cEvent.wait() } if (cEvent.isSet()) { cEvent.clear() } var arr = dict.get("array") arr.push(i) dict.set("array", arr) Log("producer:", i, ", array:", arr) pEvent.set() Sleep(1000) } } function main() { var dict = threading.Dict() dict.set("array", []) var pEvent = threading.Event() var cEvent = threading.Event() var productionQuantity = 10 var producerThread = threading.Thread(producer, productionQuantity, dict, pEvent, cEvent) var consumerThread = threading.Thread(consumer, productionQuantity, dict, pEvent, cEvent) consumerThread.join() producerThread.join() }

Returns

TypeDescription

ThreadEvent object

The Event() function returns a ThreadEvent object.

See Also

Remarks

Supports backtesting system and live trading environment.

The Dict() function is used to create a dictionary object for passing and sharing data between concurrent threads.

Dict()

Examples

  • Pass a regular object to concurrent thread execution function, test whether modifying object key values will affect object key values in other threads.

    javascript
    function threadFun1(obj) { obj["age"] = 100 while (true) { Log("threadFun1 obj:", obj) Sleep(5000) } } function threadFun2(obj) { while (true) { Log("threadFun2 obj:", obj) Sleep(5000) } } function main() { var obj = {"age": 10} var t1 = threading.Thread(threadFun1, obj) var t2 = threading.Thread(threadFun2, obj) t1.join() t2.join() }
  • Pass a ThreadDict object created by the Dict() function to concurrent thread execution function, test whether modifying object key values will affect object key values in other threads.

    javascript
    function threadFun1(threadDict) { threadDict.set("age", 100) while (true) { Log(`threadFun1 threadDict.get("age"):`, threadDict.get("age")) Sleep(5000) } } function threadFun2(threadDict) { while (true) { Log(`threadFun2 threadDict.get("age"):`, threadDict.get("age")) Sleep(5000) } } function main() { var threadDict = threading.Dict() threadDict.set("age", 10) var t1 = threading.Thread(threadFun1, threadDict) var t2 = threading.Thread(threadFun2, threadDict) t1.join() t2.join() }

Returns

TypeDescription

ThreadDict object

The Dict() function returns a ThreadDict object.

See Also

Remarks

When passing regular objects to concurrent thread functions, deep copy is used. Modifying key values in concurrent threads will not affect dictionaries in other threads.

Supports backtesting system and live trading environment.

The pending function is used to get the number of concurrent threads currently running in the strategy program.

pending()

Examples

Create two concurrently running threads and call the pending() function at different time points.

javascript
function threadFun1() { Log("threadFun1") Sleep(3000) } function threadFun2() { for (var i = 0; i < 3; i++) { LogStatus(_D(), "print from threadFun2") Sleep(3000) } } function main() { Log(`begin -- threading.pending():`, threading.pending()) var t1 = threading.Thread(threadFun1) var t2 = threading.Thread(threadFun2) Log(`after threading.Thread -- threading.pending():`, threading.pending()) t1.join() t2.join() Log(`after thread.join -- threading.pending():`, threading.pending()) }

Returns

TypeDescription

number

The pending() function returns the number of concurrent threads currently running in the strategy program.

See Also

Remarks

When the strategy's main() function starts running, directly calling pending() will return 1, because the main thread where main() function is located is also counted as a running thread.

Supports both backtesting system and live trading environment.