### Lua Loops Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/AGENT.md Shows examples of forward, backward, and array iteration loops in Lua. ```lua -- Forward loop for i = 1, 10, 1 do -- code end -- Backward loop for i = 10, 1, -1 do -- code end -- Array iteration local myArray = {1, 2, 3, 4, 5} for i = 1, #myArray do Log(myArray[i]) end ``` -------------------------------- ### Implementing a Simple RSI Strategy Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/HAASSCRIPT.md A complete example showing the initialization of input fields and the update phase logic for generating long and short signals. ```lua -- Simple RSI strategy local period = Input("period", 14) -- Initialization local prices = GetClosePrices() -- Update phase local rsi = RSI(prices, period) if rsi.Value < 30 then DoLong() -- Buy signal elseif rsi.Value > 70 then DoShort() -- Sell signal end ``` -------------------------------- ### HaasScript AI Example Template Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/AGENT.md A template for a HaasScript AI strategy, including input parameters, indicator calculation, entry conditions, and trade execution. ```lua -- Input parameters local rsiLength = Input("RSI Length", 14) local rsiBuyLevel = Input("RSI Buy Level", 30) local rsiSellLevel = Input("RSI Sell Level", 70) -- Calculate indicators local rsi = RSI(ClosePrices(), rsiLength) -- Define entry conditions local enterLong = rsi < rsiBuyLevel local enterShort = rsi > rsiSellLevel -- Execute trades (managed trading) if enterLong then DoLong("RSI Oversold") elseif enterShort then DoShort("RSI Overbought") end ``` -------------------------------- ### Lua Array (Table) Operations Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/AGENT.md Demonstrates creating, accessing elements, and getting the size of arrays (tables) in Lua. ```lua -- Array creation local prices = {100, 101, 102} -- Access by index (1-based) local firstPrice = prices[1] -- Get array size local size = #prices ``` -------------------------------- ### Timer Functions Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/data-and-prices.md Functions to start and retrieve elapsed time for timers. ```APIDOC ## StartTimer ### Description Starts a timer. ### Parameters #### Query Parameters - **key** (string) - Optional - Optional key if using multiple timers. ## GetTimer ### Description Gets the elapsed time for a timer. ### Parameters #### Query Parameters - **key** (string) - Optional - Optional key if using multiple timers. ### Response - **Returns** (number) - Elapsed time in milliseconds. ``` -------------------------------- ### InputAccount Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/advanced.md Generates an account selection field that returns the selected account GUID. ```lua InputAccount(label, [tooltip], [group]) ``` -------------------------------- ### TakersFee Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/trading.md Gets the takers fee of the market. ```APIDOC ## TakersFee ### Description Gets takers fee of the market. ### Parameters #### Path Parameters - **market** (string) - Optional - The market returned by PriceMarket(), InputAccountMarket() or InputMarket() for example. ### Response - **Returns** (number) - Takers fee of the market. ``` -------------------------------- ### Library Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/advanced.md Acts as a wrapper for executing custom commands. ```lua Library(arg) ``` -------------------------------- ### GetLow Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/helpers.md Gets the lowest value from a collection. ```APIDOC ## GetLow(prices, depth, [offset]) ### Description Gets the lowest value. ### Parameters #### Path Parameters - **prices** (HaasNumberCollection) - Required - Source data. - **depth** (number) - Required - Number of records to include. - **offset** (number) - Optional - Number of records to skip. ### Response - **Returns** (number) - Returns the lowest value. ``` -------------------------------- ### GetHigh Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/helpers.md Gets the highest value from a collection. ```APIDOC ## GetHigh(prices, depth, [offset]) ### Description Gets the highest value. ### Parameters #### Path Parameters - **prices** (HaasNumberCollection) - Required - Source data. - **depth** (number) - Required - Number of records to include. - **offset** (number) - Optional - Number of records to skip. ### Response - **Returns** (number) - Returns the highest value. ``` -------------------------------- ### ArrayIndex Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/helpers.md Gets the value on a specific index. ```APIDOC ## ArrayIndex ### Description Gets the value on a specific index. A negative index will take from the end of the array. Aliased as ArrayGet. ### Parameters - **input** (dynamic) - Required - Source data. - **index** (number) - Required - The index to get. ### Response - **Returns** (dynamic) - Return the value on that index. ``` -------------------------------- ### Library Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/advanced.md Wrapper for custom command execution. ```APIDOC ## Library ### Description Wrapper for custom command. ### Parameters #### Path Parameters - **arg** (...dynamic) - Required - Execution arguments. ``` -------------------------------- ### GetBotROI Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/data-and-prices.md Gets the return on investment for a bot. ```APIDOC ## GetBotROI ### Description Gets the return on investment. The ROI is calculated by dividing the total realized profits by the average position size. ### Parameters #### Query Parameters - **market** (string) - Optional - The guid returned by AccountGuid(), InputAccount or InputAccountMarket for example. ### Response - **Returns** (number) - Return the ROI percentage. ``` -------------------------------- ### Place Orders with PlaceBuyOrder and PlaceSellOrder Source: https://context7.com/haasonline/haasscript-ai-reference/llms.txt Executes direct limit orders with control over price, amount, and order type. Ensure no existing orders are open before placement to avoid unintended behavior. ```lua -- Unmanaged limit order strategy local close = ClosePrices() local atr = ATR(HighPrices(), LowPrices(), close, 14) local currentPrice = close[1] -- Calculate limit prices using ATR local buyPrice = currentPrice - (atr[1] * 0.5) local sellPrice = currentPrice + (atr[1] * 0.5) -- Place orders only if no orders open if not IsAnyOrderOpen() then local amount = 0.01 -- Trade amount -- Place limit buy order local buyOrderId = PlaceBuyOrder(buyPrice, amount) Log("Buy order placed at " .. buyPrice) -- Or place with specific order type local sellOrderId = PlaceSellOrder(sellPrice, amount, PriceMarket(), LimitOrderType()) end ``` -------------------------------- ### AverageEnterPrice Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/trading.md Gets the average entry price for a position. ```APIDOC ## AverageEnterPrice ### Description Gets the average enter price. ### Parameters #### Query Parameters - **positionId** (string) - Optional - Optional unique identifier. Required when the bot is trading multiple position at once. - **includeClosed** (boolean) - Optional - True for total position amount (default), false for only open amount. ### Response - **Returns** (number) - Returns the average enter price. ``` -------------------------------- ### Offset Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/helpers.md Gets an offset amount of the given array. ```APIDOC ## Offset ### Description Gets an offset amount of the given array. ### Parameters #### Request Body - **input** (dynamic) - Required - Source data. - **offset** (number) - Required - Number of record to remove. ### Response - **Returns** (dynamic) - Returns the given array with the offset amount of data removed from it. ``` -------------------------------- ### InputAccountMarket Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/advanced.md Creates a dropdown for selecting an account, market, and leverage, returning a combined string. ```lua InputAccountMarket(label, [tooltip], [group]) ``` -------------------------------- ### Implement EasyICHIMOKU Strategy Source: https://context7.com/haasonline/haasscript-ai-reference/llms.txt Uses EasyICHIMOKU for automated signal generation and logging. ```lua -- Ichimoku cloud strategy local ichimokuSignal = EasyICHIMOKU(0, "Ichimoku", 0) -- Process signal with managed trading DoSignal(ichimokuSignal) -- Log signal state if ichimokuSignal == SignalLong() then Log("Ichimoku: Bullish signal", "Green") elseif ichimokuSignal == SignalShort() then Log("Ichimoku: Bearish signal", "Red") end ``` -------------------------------- ### Time Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/data-and-prices.md Gets the current UTC unix timestamp. ```APIDOC ## Time() ### Description Gets the current unix timestamp. Based on UTC. ### Response - **Returns** (number) - Returns the current unix timestamp. ``` -------------------------------- ### CurrentPrice Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/data-and-prices.md Gets all the price data from the current candle. ```APIDOC ## CurrentPrice ### Description Gets all the price data from the current candle. ### Parameters #### Path Parameters - **market** (string) - Optional - The market of the tick. Default is the selected main market. ### Response - **Returns** (dynamic) - Returns the price data in an array. ``` -------------------------------- ### Implement Stop Loss and Take Profit Source: https://context7.com/haasonline/haasscript-ai-reference/llms.txt Applies percentage-based risk management and monitors for triggered exits. ```lua -- Basic risk management setup local stopLossPerc = Input("Stop Loss %", 2) local takeProfitPerc = Input("Take Profit %", 5) -- Apply stop loss and take profit local slTriggered = StopLoss(stopLossPerc) local tpTriggered = TakeProfit(takeProfitPerc) if slTriggered then Log("Stop Loss triggered!", "Red") elseif tpTriggered then Log("Take Profit reached!", "Green") end -- Entry logic with position check local rsi = RSI(ClosePrices(), 14) if GetPositionDirection() == NoPosition() then if rsi[1] < 30 then DoLong("RSI Buy") elseif rsi[1] > 70 then DoShort("RSI Sell") end end ``` -------------------------------- ### ShortAmount Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/trading.md Gets the total amount open in a short position. ```APIDOC ## ShortAmount ### Description Gets the total amount open in a short position. ### Parameters #### Query Parameters - **market** (string) - Optional - The market returned by PriceMarket(), InputAccountMarket() or InputMarket() for example. ### Response - **Returns** (number) - Returns the total amount open in a short position. ``` -------------------------------- ### EasyIMI Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/technical-analysis.md Automatically defines input fields, calculates IMI, plots the chart, and returns the signal. ```APIDOC ## EasyIMI ### Description Automatically defines the input fields, calculates the IMI, plots the chart and returns the signal. ### Method N/A (Function Call) ### Endpoint N/A (Local Function) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```lua EasyIMI(chartIndex, [name], [interval]) ``` ### Response #### Success Response (200) - **signal** (enum) - Returns a signal based on IMI, it's MA and selected signal type. #### Response Example N/A (Function Return Value) ``` -------------------------------- ### Lua Comments Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/AGENT.md Demonstrates single-line and multi-line comment syntax in Lua. ```lua -- Single line comment --[[ Multi-line comment ]] ``` -------------------------------- ### LongAmount Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/trading.md Gets the total amount open in a long position. ```APIDOC ## LongAmount ### Description Gets the total amount open in a long position. ### Parameters #### Query Parameters - **market** (string) - Optional - The market returned by PriceMarket(), InputAccountMarket() or InputMarket() for example. ### Response - **Returns** (number) - Returns the total amount open in a long position. ``` -------------------------------- ### Regenerate HaasScript Documentation Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/README.md Executes the documentation generator tool using the .NET CLI. ```bash dotnet run --project Source/Tools/HaasScriptDocGenerator ``` -------------------------------- ### GetLows Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/helpers.md Gets the lowest values within a lookback period. ```APIDOC ## GetLows(array, depth) ### Description Gets the lowest values within lookback period. ### Parameters #### Path Parameters - **array** (HaasNumberCollection) - Required - Source data. - **depth** (number) - Required - Number of records to include. ### Response - **Returns** (HaasNumberCollection) - Returns the lowest values within lookback period. ``` -------------------------------- ### GetHighs Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/helpers.md Gets the highest values within a lookback period. ```APIDOC ## GetHighs(array, depth) ### Description Gets the highest values within lookback period. ### Parameters #### Path Parameters - **array** (HaasNumberCollection) - Required - Source data. - **depth** (number) - Required - Number of records to include. ### Response - **Returns** (HaasNumberCollection) - Returns the highest values within lookback period. ``` -------------------------------- ### EasyPPO Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/technical-analysis.md Calculates PPO, plots it, and returns a signal. ```APIDOC ## EasyPPO ### Description Automatically defines input fields, calculates the PPO, plots the chart, and returns a signal based on PPO and selected signal type. ### Parameters #### Path Parameters - **chartIndex** (number) - Required - Chart index on which to plot. - **name** (string) - Optional - Unique name of the indicator. - **interval** (number) - Optional - Used interval for price data. Default is 0. ### Response - **Returns** (enum) - A signal based on PPO and selected signal type. ``` -------------------------------- ### EasyAlice Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/technical-analysis.md Calculates the Alice signal based on the Haasonline Intelli Alice bot. ```APIDOC ## EasyAlice ### Description Automatically defines the input fields, calculates the Alice signal based on the Haasonline Intelli Alice bot. By default Alice works on a 2 minute interval., plots the chart and returns the signal. ### Parameters #### Path Parameters - **interval** (number) - Optional - Used interval for price data. Default is 0 and the main interval will be used. ### Response - **Returns** (enum) - Returns a signal based on the Intelli-Bot Alice. ``` -------------------------------- ### ArrayLast Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/helpers.md Gets the last value of the array with an optional offset. ```APIDOC ## ArrayLast ### Description Gets the last value of the array with an optional offset. ### Parameters - **input** (dynamic) - Required - Source data. - **offset** (number) - Optional - The offset from the last index. ### Response - **Returns** (dynamic) - Return the last value of the array taking the offset into account. ``` -------------------------------- ### GetBotProfit Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/data-and-prices.md Gets total realized profits on a specific market. ```APIDOC ## GetBotProfit ### Description Total realized profits on a specific market. Unrealized profits are included when 'includeUnrealized' is set on true. ### Parameters #### Query Parameters - **market** (string) - Optional - The guid returned by AccountGuid(), InputAccount or InputAccountMarket for example. - **includeUnrealized** (boolean) - Optional - Set on true to include the unrealized profits. By default false. ### Response - **Returns** (number) - Return total realized profit. ``` -------------------------------- ### InputSignalManagement Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/advanced.md Creates multiple dropdown options for signal management and mapping. ```APIDOC ## InputSignalManagement ### Description Creates multiple dropdown options for signal management and mapping. ### Parameters - **label** (string) - Required - The field label text. - **signal** (enum) - Required - The default value for the field. - **tooltip** (string) - Optional - The tooltip text for the field. - **group** (string) - Optional - The group of the input field. ### Returns - **enum** - The baked signal based on settings. ``` -------------------------------- ### StringIndexOf Function Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/helpers.md Gets the zero-based index of the first occurrence of a substring. ```APIDOC ## StringIndexOf StringIndexOf ### Description Gets the zero-based index of the first occurrence of the specified string in the current. ### Parameters #### Path Parameters - **value** (string) - Required - The main string. - **searchValue** (string) - Required - The search value. - **ignoreCase** (boolean) - Optional - Ignoring the case of the scripts being compared. ### Response #### Success Response (200) - **index** (number) - A zero-based index of the first occurrence of the specified string. #### Response Example ```json { "index": 5 } ``` ``` -------------------------------- ### Create Dropdown Selections with InputOptions and InputMaTypes Source: https://context7.com/haasonline/haasscript-ai-reference/llms.txt Provides dropdown menus for user selection of predefined strategy modes or technical indicator types. ```lua -- Custom dropdown local strategy = InputOptions("Strategy", "Aggressive", {"Conservative", "Moderate", "Aggressive"}) -- MA type selection local maType = InputMaTypes("MA Type", SmaType()) local maPeriod = Input("MA Period", 20) -- Apply selected MA type local ma = MA(ClosePrices(), maPeriod, maType) -- Strategy-based parameters local stopLoss = 2 if strategy == "Conservative" then stopLoss = 1 elseif strategy == "Aggressive" then stopLoss = 3 end StopLoss(stopLoss) ``` -------------------------------- ### Count Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/helpers.md Gets the length of an array or the number of occurrences of a specific value. ```APIDOC ## Count ### Description Gets the length of an array or the number of occurrences within the array of a specific value. ### Parameters #### Request Body - **input** (dynamic) - Required - Source data. - **value** (dynamic) - Optional - Optional value to match. ### Response - **Returns** (number) - Returns the length of an array or the number of occurrences within the array of a specific value. ``` -------------------------------- ### EasyWILLR Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/technical-analysis.md Automatically defines input fields, calculates WILLR, plots the chart, and returns a signal. ```APIDOC ## EasyWILLR ### Description Automatically defines the input fields, calculates the WILLR, plots the chart and returns the signal. ### Parameters #### Path Parameters - **chartIndex** (number) - Required - Chart index on which to plot. - **name** (string) - Optional - Unique name of the indicator. - **interval** (number) - Optional - Used interval for price data. Default is 0 and the main interval will be used. ### Response - **Returns** (enum) - Returns a signal based on the GetBuySellLevelSignal() template. ``` -------------------------------- ### Get field value by index Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/helpers.md Retrieves the value at a specific index. ```lua ArrayIndexField(input, index) ``` -------------------------------- ### EasyKST Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/technical-analysis.md Automatically defines input fields, calculates KST, plots the chart, and returns the signal. ```APIDOC ## EasyKST ### Description Automatically defines the input fields, calculates the KST, plots the chart and returns the signal. ### Method N/A (Function Call) ### Endpoint N/A (Local Function) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```lua EasyKST(chartIndex, [name], [interval]) ``` ### Response #### Success Response (200) - **signal** (enum) - Returns a signal based on KST and selected signal type. #### Response Example N/A (Function Return Value) ``` -------------------------------- ### PlotStackedArea Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/advanced.md Creates a stacked area chart from a collection of line guids. ```APIDOC ## PlotStackedArea ### Description Creates a stacked area chart from a line guid collection. ### Parameters #### Path Parameters - **lineGuids** (dynamic) - Required - Line guid collection returned by multiple Plot()'s. ### Response - **void** - Returns nothing. ``` -------------------------------- ### Define Strategy Parameters with Input Source: https://context7.com/haasonline/haasscript-ai-reference/llms.txt Creates configurable fields for strategy optimization without modifying the underlying code. ```lua -- Define strategy parameters local rsiPeriod = Input("RSI Period", 14) local rsiBuy = Input("RSI Buy Level", 30) local rsiSell = Input("RSI Sell Level", 70) local enableTrailing = Input("Enable Trailing", true) local stopLossPerc = Input("Stop Loss %", 2) -- Use inputs in strategy local rsi = RSI(ClosePrices(), rsiPeriod) if enableTrailing then TrailingStopLoss(stopLossPerc) else StopLoss(stopLossPerc) end if rsi[1] < rsiBuy then DoLong("RSI " .. rsiPeriod .. " Buy") elseif rsi[1] > rsiSell then DoShort("RSI " .. rsiPeriod .. " Sell") end ``` -------------------------------- ### Enter Positions with PlaceGoLongOrder and PlaceGoShortOrder Source: https://context7.com/haasonline/haasscript-ai-reference/llms.txt Used for leverage or margin market entries. Requires a defined market and order type. ```lua -- Leverage trading with limit orders local market = PriceMarket() local close = ClosePrices() local amount = Input("Position Size", 100) -- Grid entry for long position local entryPrice = close[1] * 0.995 -- 0.5% below current price if GetPositionDirection() == NoPosition() and not IsAnyOrderOpen() then local orderId = PlaceGoLongOrder( entryPrice, amount, market, LimitOrderType(), "Grid Long Entry" ) if orderId ~= nil then Log("Long limit order placed: " .. orderId, "Green") end end ``` -------------------------------- ### PlotStackedArea Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/advanced.md Creates a stacked area chart from a line guid collection. ```lua PlotStackedArea(lineGuids) ``` -------------------------------- ### Settings Commands Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/HAASSCRIPT.md Commands for configuring script settings and behavior. ```APIDOC ## Settings Commands ### Description Commands for configuring script settings and behavior. ### Commands - `DeactivateBot([reason], [cancelOpenOrders])` - Deactivates the bot. Once the bot is deactivated, it can not be restarted. - `DisableIndicatorContainerLogs()` - Disables IndicatorContainer log messages. - `EnableHighSpeedUpdates([updateOnFilledOrders], [guaranteeInterval])` - Enables high-speed script execution. - `EnableOrderPersistence()` - Enables order persistence for managed trading. - `Finalize([callback])` - Only executes on the last update cycle of a backtest. Saves data and performs final calculations. ``` -------------------------------- ### GetCurrentProfit Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/data-and-prices.md Gets unrealized plus realized profits of the current open position. ```APIDOC ## GetCurrentProfit ### Description Gets unrealized plus realized profits of the current open position. Optional parameters fall back to main bot settings. ### Parameters #### Query Parameters - **direction** (enum) - Optional - Bot position enum. PositionLong, PositionShort or NoPosition. - **market** (string) - Optional - The guid returned by AccountGuid(), InputAccount or InputAccountMarket for example. ### Response - **Returns** (number) - Returns the total profit. ``` -------------------------------- ### EasyBBANDS Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/technical-analysis.md Calculates Bollinger Bands, plots the chart, and returns a signal. ```APIDOC ## EasyBBANDS ### Description Automatically defines the input fields, calculates the BBANDS, plots the chart and returns the signal. ### Parameters #### Path Parameters - **chartIndex** (number) - Required - Chart index on which to plot. - **name** (string) - Optional - Unique name of the indicator. - **interval** (number) - Optional - Used interval for price data. Default is 0 and the main interval will be used. ### Response - **Returns** (enum) - Returns a signal based on the GetBuySellLevelSignal() template. Signals are generated when price breaks above Upper and below Lower band. ``` -------------------------------- ### Implement a simple RSI trading strategy Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/README.md Basic strategy template using RSI indicator inputs to trigger long or short positions. ```lua -- Simple RSI strategy local rsiLength = Input("RSI Length", 14) local buyLevel = Input("Buy Level", 30) local sellLevel = Input("Sell Level", 70) local rsi = RSI(ClosePrices(), rsiLength) if rsi < buyLevel then DoLong("RSI Oversold") elseif rsi > sellLevel then DoShort("RSI Overbought") end ``` -------------------------------- ### SubString Function Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/helpers.md Retrieves a substring from a string based on start index and length. ```APIDOC ## SubString SubString ### Description Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length. ### Parameters #### Path Parameters - **value** (string) - Required - The main string. - **start** (number) - Required - Start index, zero based. - **length** (number) - Required - The length of the substring. ### Response #### Success Response (200) - **substring** (string) - Substring of the main value. #### Response Example ```json { "substring": "extracted part" } ``` ``` -------------------------------- ### EasyOBV Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/technical-analysis.md Calculates OBV, plots it, and returns a signal. ```APIDOC ## EasyOBV ### Description Automatically defines input fields, calculates the OBV, plots the chart, and returns a signal based on OBV, its MA, and selected signal type. ### Parameters #### Path Parameters - **chartIndex** (number) - Required - Chart index on which to plot. - **name** (string) - Optional - Unique name of the indicator. - **interval** (number) - Optional - Used interval for price data. Default is 0. ### Response - **Returns** (enum) - A signal based on OBV, its MA, and selected signal type. ``` -------------------------------- ### Get last array element Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/helpers.md Retrieves the last element of the array, with an optional offset. ```lua ArrayLast(input, [offset]) ``` -------------------------------- ### InputAccountMarket Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/advanced.md Creates an account, market & leverage dropdown. ```APIDOC ## InputAccountMarket ### Description Creates an account, market & leverage dropdown. ### Parameters #### Path Parameters - **label** (string) - Required - The field label text. - **tooltip** (string) - Optional - The tooltip text for the field. - **group** (string) - Optional - The group of the input field. ``` -------------------------------- ### EasyBBANDSW Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/technical-analysis.md Calculates Bollinger Bands %W, plots the chart, and returns a signal. ```APIDOC ## EasyBBANDSW ### Description Automatically defines the input fields, calculates the BBANDS %W, plots the chart and returns the signal. ### Parameters #### Path Parameters - **chartIndex** (number) - Required - Chart index on which to plot. - **name** (string) - Optional - Unique name of the indicator. - **interval** (number) - Optional - Used interval for price data. Default is 0 and the main interval will be used. ### Response - **Returns** (enum) - Returns a signal based on the GetBuySellLevelSignal() template. Signals are generated when price breaks above Upper and below Lower band. ``` -------------------------------- ### Display repository structure Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/README.md Visual representation of the documentation directory layout. ```text ├── AGENT.md # AI assistant guidance & best practices ├── HAASSCRIPT.md # Technical reference overview └── haasscript/ ├── technical-analysis.md # 157 indicator commands ├── trading.md # 139 trading & position commands ├── helpers.md # 121 utility commands ├── enumerations.md # 197 constant values ├── data-and-prices.md # 62 price & market data commands └── advanced.md # 97 advanced feature commands ``` -------------------------------- ### Get Current Unix Timestamp Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/data-and-prices.md Retrieves the current Unix timestamp based on UTC time. ```lua Time() ``` -------------------------------- ### DefineOutputIndex Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/advanced.md Creates an index-based output connection for use in the visual editor. ```lua DefineOutputIndex(index, type, name, description, [outputSuggestions]) ``` -------------------------------- ### Get Last Entry Prices Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/trading.md Retrieves the last recorded entry price for long or short positions. ```lua LastLongPrice() ``` ```lua LastShortPrice() ``` -------------------------------- ### Implement EasyRSI and Multi-Indicator Consensus Source: https://context7.com/haasonline/haasscript-ai-reference/llms.txt Demonstrates using Easy Indicators for automated signals and combining them for consensus trading. ```lua -- EasyRSI automatically handles inputs, calculation, plotting, and signals local rsiSignal = EasyRSI(1, "RSI Strategy") -- Process the signal DoSignal(rsiSignal) -- Combine multiple Easy Indicators local macdSignal = EasyMACD(2, "MACD") local bbandsSignal = EasyBBANDS(0, "Bollinger") -- Consensus trading - only trade when multiple indicators agree if rsiSignal == SignalLong() and macdSignal == SignalLong() then DoLong("Multi-indicator Long") elseif rsiSignal == SignalShort() and macdSignal == SignalShort() then DoShort("Multi-indicator Short") end ``` -------------------------------- ### Get value by index Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/helpers.md Retrieves the value at a specific index. Negative indices count from the end of the array. ```lua ArrayIndex(input, index) ``` -------------------------------- ### EasySSTOCH Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/technical-analysis.md Automatically defines input fields, calculates SSTOCH, plots the chart, and returns the signal. ```APIDOC ## EasySSTOCH ### Description Automatically defines the input fields, calculates the SSTOCH, plots the chart and returns the signal. ### Method N/A (Function Call) ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```lua EasySSTOCH(chartIndex, [name], [interval]) ``` ### Response #### Success Response (200) - **return value** (enum) - Returns a signal based on the GetBuySellLevelSignal() template. ``` -------------------------------- ### Stop a Timer Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/data-and-prices.md Stops a previously started timer. An optional key can be provided if multiple timers are in use. ```lua StopTimer([key]) ``` -------------------------------- ### Execute Position Management with DoExitPosition and DoFlipPosition Source: https://context7.com/haasonline/haasscript-ai-reference/llms.txt Use these functions to exit or reverse existing positions based on technical indicators like EMA crossovers. ```lua -- Exit and flip strategy local ema9 = EMA(ClosePrices(), 9) local ema21 = EMA(ClosePrices(), 21) local position = GetPositionDirection() -- Check for crossover signals local bullishCross = CrossOver(ema9, ema21) local bearishCross = CrossUnder(ema9, ema21) if bullishCross then if position == PositionShort() then DoFlipPosition("EMA Flip to Long") elseif position == NoPosition() then DoLong("EMA Long Entry") end elseif bearishCross then if position == PositionLong() then DoFlipPosition("EMA Flip to Short") elseif position == NoPosition() then DoShort("EMA Short Entry") end end ``` -------------------------------- ### Get Average Exit Price Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/trading.md Retrieves the average exit price, optionally filtered by a specific position identifier. ```lua AverageExitPrice([positionId]) ``` -------------------------------- ### PlotVolume Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/advanced.md Creates volume bars with configurable colors and fill styles. ```lua PlotVolume(chartId, [upColor], [downColor], [upFill], [downFill], [side]) ``` -------------------------------- ### InputPriceSource Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/advanced.md Creates a price source dropdown. ```APIDOC ## InputPriceSource ### Description Creates a price source dropdown. ### Parameters - **label** (string) - Required - The field label text. - **defaultValue** (string) - Optional - The default value for the field. - **tooltip** (string) - Optional - The tooltip text for the field. - **group** (string) - Optional - The group of the input field. ### Returns - **string** - The selected price source (e.g., BITSTAMP). ``` -------------------------------- ### Calculating Technical Indicators Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/HAASSCRIPT.md Examples of common technical indicator functions including RSI, MACD, and Moving Averages. ```lua -- RSI (Relative Strength Index) local rsi = RSI(GetClosePrices(), 14) -- MACD local macd = MACD(GetClosePrices(), 12, 26, 9) local macdValue = macd.Value local signalLine = macd.Signal -- Moving Averages local sma = SMA(GetClosePrices(), 20) local ema = EMA(GetClosePrices(), 20) ``` -------------------------------- ### InputMarket Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/advanced.md Creates a dropdown for selecting markets. ```APIDOC ## InputMarket ### Description Creates a market dropdown. The market options are related to the main account selection. ### Parameters #### Request Body - **label** (string) - Required - The field label text. - **defaultValue** (string) - Optional - The default value for the field. - **tooltip** (string) - Optional - The tooltip text for the field. - **group** (string) - Optional - The group of the input field. ### Response - **string** - Returns the selected market. ``` -------------------------------- ### Get Last Exit Prices Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/trading.md Functions to retrieve the last recorded exit prices for long, short, or combined positions. ```lua LastExitLongPrice() ``` ```lua LastExitPositionPrice() ``` ```lua LastExitShortPrice() ``` -------------------------------- ### NeverExitWithLoss Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/trading.md Compares the average enter price to the target price or current price to prevent exiting at a loss. ```APIDOC ## NeverExitWithLoss ### Description Compares the average enter price to the targetPrice or current price. ### Parameters #### Path Parameters - **acceptedLoss** (number) - Optional - The accepted loss in percentage. Default is 0. This also affects user-defined targetPrice. - **targetPrice** (number) - Optional - The target price of the trade. Can be used when placing orders beforehand in unmanaged trading. - **positionId** (string) - Optional - Optional unique identifier. Required when the bot is trading multiple position at once. ### Response - **Returns** (boolean) - Returns true if the trade is allowed. ``` -------------------------------- ### Get Last Trade ROI Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/trading.md Retrieves the Return on Investment for the last long or short position, optionally filtered by position ID. ```lua LastLongROI([positionId]) ``` ```lua LastShortROI([positionId]) ``` -------------------------------- ### Get Last Trade Profit Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/trading.md Retrieves the profit from the last long or short exit trade, optionally filtered by position ID. ```lua LastLongProfit([positionId]) ``` ```lua LastShortProfit([positionId]) ``` -------------------------------- ### Compress Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/helpers.md Calculates the average values of every 2 values in an array. For example, when the input is [10, 20, 30, 40], the result will be [15, 35]. ```APIDOC ## Compress ### Description Calculates the average values of every 2 values in an array. When the input is [10, 20, 30, 40] the result will be [15, 35]. ### Method N/A (Function Call) ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```lua Compress(input) ``` ### Response #### Success Response (200) - **return_value** (HaasNumberCollection) - The compressed array. #### Response Example ```json { "return_value": "HaasNumberCollection" } ``` ``` -------------------------------- ### EasyMOM Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/technical-analysis.md Calculates MOM, plots it, and returns a signal. ```APIDOC ## EasyMOM ### Description Automatically defines input fields, calculates the MOM, plots the chart, and returns a signal based on MOM, its MA, and selected signal type. ### Parameters #### Path Parameters - **chartIndex** (number) - Required - Chart index on which to plot. - **name** (string) - Optional - Unique name of the indicator. - **interval** (number) - Optional - Used interval for price data. Default is 0. ### Response - **Returns** (enum) - A signal based on MOM, its MA, and selected signal type. ``` -------------------------------- ### EasyBBANDSB Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/technical-analysis.md Calculates Bollinger Bands %B, plots the chart, and returns a signal. ```APIDOC ## EasyBBANDSB ### Description Automatically defines the input fields, calculates the BBANDS %B, plots the chart and returns the signal. ### Parameters #### Path Parameters - **chartIndex** (number) - Required - Chart index on which to plot. - **name** (string) - Optional - Unique name of the indicator. - **interval** (number) - Optional - Used interval for price data. Default is 0 and the main interval will be used. ### Response - **Returns** (enum) - Returns a signal based on the GetBuySellLevelSignal() template. Signals are generated when price breaks above Upper and below Lower band. ``` -------------------------------- ### EasyAO Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/technical-analysis.md Calculates the Awesome Oscillator (AO), plots the chart, and returns a signal. ```APIDOC ## EasyAO ### Description Automatically defines the input fields, calculates the AO, plots the chart and returns the signal. ### Parameters #### Path Parameters - **chartIndex** (number) - Required - Chart index on which to plot. - **name** (string) - Optional - Unique name of the indicator. - **interval** (number) - Optional - Used interval for price data. Default is 0 and the main interval will be used. ### Response - **Returns** (enum) - Returns a signal based on AO, it's MA and selected signal type. ``` -------------------------------- ### DeactivateAfterXIdleMinutes Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/trading.md Deactivates the bot if the last completed order is a number of minutes in the past. Timeout starts after the first completed order. Returns true when the bot has been deactivated. ```APIDOC ## DeactivateAfterXIdleMinutes ### Description Deactivates the bot if the last completed order is a number of minutes in the past. Timeout starts after the first completed order. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```lua DeactivateAfterXIdleMinutes(minutes) ``` ### Response #### Success Response (200) - **return value** (boolean) - Returns true when the bot has been deactivated. #### Response Example ```lua true ``` ``` -------------------------------- ### EasyDynamicLongShortLevels Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/technical-analysis.md Calculates and plots the DynamicBuySellLevel, returning a trading signal based on dynamic short/long levels. ```APIDOC ## EasyDynamicLongShortLevels ### Description Automatically defines input fields, calculates the DynamicBuySellLevel, plots the chart, and returns a trading signal. ### Method N/A (Function Call) ### Endpoint N/A (Local Script Function) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```lua EasyDynamicLongShortLevels(chartIndex, name, interval) ``` ### Response #### Success Response (200) - **signal** (enum) - Returns a signal based on dynamic short/long level. #### Response Example N/A (Function Return Value) ``` -------------------------------- ### EasySTOCH Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/technical-analysis.md Automatically defines input fields, calculates STOCH, plots the chart, and returns the signal. ```APIDOC ## EasySTOCH ### Description Automatically defines the input fields, calculates the STOCH, plots the chart and returns the signal. ### Method N/A (Function Call) ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```lua EasySTOCH(chartIndex, [name], [interval]) ``` ### Response #### Success Response (200) - **return value** (enum) - Returns a signal based on %K, %D and selected signal type. ``` -------------------------------- ### Get Wallet Balance Details Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/data-and-prices.md Retrieves the available, locked, and total balance for a specific coin within a given account. This function does not work in backtests or for simulated accounts. Optional parameters allow specifying the account ID, coin, and market. ```lua Balance([accountId], [coin], [market]) ``` -------------------------------- ### TakeProfit Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/trading.md Calculates the current percentage change from the average enter price and compares it with the take profit value. ```APIDOC ## TakeProfit ### Description Calculates the current percentage change from the average enter price and compares it with the take profit value. ### Parameters - **percentage** (number) - Required - Take profit percentage. - **positionId** (string) - Optional - Optional unique identifier. - **direction** (enum) - Optional - The direction of the position. ### Response - **Returns** (boolean) - Returns true if the take profit has been reached. ``` -------------------------------- ### Get Total Wallet Balance Value Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/data-and-prices.md Returns the total value of a specific currency in the wallet, including margin for orders and positions. This function is not compatible with backtests or simulated accounts. Optional parameters allow specifying the account ID, coin, and market. ```lua BalanceAmount([accountId], [coin], [market]) ``` -------------------------------- ### PriceStep Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/trading.md Returns the minimum allowed price step for a market. ```APIDOC ## PriceStep ### Description Returns the minimum allowed price step for market. Aliases: QuoteStep. ### Parameters #### Path Parameters - **market** (string) - Optional - The market returned by PriceMarket(), InputAccountMarket() or InputMarket() for example. ### Response - **Returns** (number) - The price step size. ``` -------------------------------- ### Input Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/advanced.md Creates a script input field. ```APIDOC ## Input ### Description Creates a script input field. The type is depending on the default value. ### Parameters #### Path Parameters - **label** (string) - Required - The field label text. - **defaultValue** (dynamic) - Optional - The default value for the field. - **tooltip** (string) - Optional - The tooltip text for the field. - **group** (string) - Optional - The group of the input field. ``` -------------------------------- ### DefineOutputIndex Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/advanced.md Creates an index based output connection for the visual editor. ```APIDOC ## DefineOutputIndex ### Description Creates an index based output connection to be used in the visual editor. ### Parameters #### Path Parameters - **index** (number) - Required - The array index of this value/output. - **type** (enum) - Required - The parameter type enum. - **name** (string) - Required - The output name. - **description** (string) - Required - The output description. - **outputSuggestions** (string) - Optional - The output suggestions. ``` -------------------------------- ### InputOptions Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/advanced.md Creates a dropdown with custom options. ```APIDOC ## InputOptions ### Description Creates a dropdown with custom options. ### Parameters - **label** (string) - Required - The field label text. - **defaultValue** (string) - Required - The default value for the field. - **options** (dynamic) - Required - Options list/array. - **tooltip** (string) - Optional - The tooltip text for the field. - **group** (string) - Optional - The group of the input field. ### Returns - **string** - The selected value. ``` -------------------------------- ### EasySTOCHF Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/technical-analysis.md Automatically defines input fields, calculates STOCHF, plots the chart, and returns the signal. ```APIDOC ## EasySTOCHF ### Description Automatically defines the input fields, calculates the STOCHF, plots the chart and returns the signal. ### Method N/A (Function Call) ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```lua EasySTOCHF(chartIndex, [name], [interval]) ``` ### Response #### Success Response (200) - **return value** (enum) - Returns a signal based on the GetCrossOverUnderSignal() template. ``` -------------------------------- ### DynamicTakeProfit Source: https://github.com/haasonline/haasscript-ai-reference/blob/main/haasscript/trading.md Calculates the dynamic take profit price and compares it with the current exit price. ```APIDOC ## DynamicTakeProfit ### Description Calculates the dynamic take profit price and compares it with the current exit price. ### Parameters - **percentage** (number) - Required - Price pump percentage. - **depth** (number) - Optional - Read depth. Default is 30 ticks. - **positionId** (string) - Optional - Optional unique identifier. Required when the bot is trading multiple position at once. - **direction** (enum) - Optional - The direction of the position. PositionLong or PositionShort. By default both. ### Response - **Returns** (boolean) - Returns true is the take profit price has been breached. ```