LogoLogo
Back to HaasOnline.comSwitch to Developer API
3.x
3.x
  • Welcome
  • Getting Started
    • What is Haas Trade Server?
    • System Requirements
    • Installation
      • Windows
      • Linux
        • Downgrading Mono
      • MacOS
    • Configuration
      • License Key
        • Upgrading Your License
      • Price Drivers & Accounts
      • Exchanges
        • Binance
        • Binance USDT Futures
        • Binance COIN Futures
        • Binance US
        • Bitfinex
        • BitMEX
        • Bitpanda Pro
        • Bitstamp
        • Bittrex
        • Bybit
        • (Unsupported) C-Cex
        • Cex.IO
        • (Unsupported) CobinHood
        • Coinbase PRO
        • Deribit
        • (Unsupported) FTX
        • Gemini
        • HitBTC
        • Huobi
        • Ionomy
        • Kraken
        • Kraken Futures
        • KuCoin
        • (Unsupported) NovaExchange
        • OKCoin
        • OKEX
        • OKEX-Futures
        • OKEX-Swap
        • Poloniex
        • Scripted Driver
    • Updating HTS
      • Stable Update
      • Beta Update
    • Apps
      • Discord
      • Telegram
    • Security
      • Two-factor Authentication (2FA)
    • Troubleshooting
      • Frequently Asked Questions
      • Two-factor Authentication (2FA)
      • Debugging & Logs
      • Exchange API
      • Invalid License
      • Lost Login Credentials
      • Orders Being Rejected
      • Unresponsive HTS UI
      • Using Safe Mode
    • Tips & Tricks
      • Keyboard Shortcuts
      • Migrating Your HTS
      • Never Logout
      • Reactivate Bots on Startup
      • Used Symbols
  • Trade Bots
    • Getting Started
    • General Settings
    • Trade Settings
    • Bot Charts
    • Indicators
      • Candlestick Patterns
        • Advance Block
        • Belt Hold
          • Belt Hold Bearish
          • Belt Hold Bullish
        • Break Away
          • Breakaway Bearish
          • Breakaway Bullish
        • Closing Marubozu
        • Concealing Baby Swallow
        • Counter Attack
          • Counter Attack Bullish
          • Counter Attack Bearish
        • Doji
        • Doji Star
        • Dragon Fly Doji
        • Engulfing Bearish
        • Engulfing Bullish
        • Gap Side-by-Side White Lines
        • Gravestone Doji
        • Hammer
        • Hanging Man
        • Harami
          • Harami Bearish
          • Harami Bullish
        • Harami Cross
          • Harami Cross Bearish
          • Harami Cross Bullish
        • High Wave
        • Hikkake
          • Hikkake Bearish
          • Hikkake Bullish
        • Homing Pigeon
        • Identical Three Crows
        • In Neck
        • Inverted Hammer
        • Kicking Bearish
        • Kicking Bullish
        • Ladder Bottom
        • Long Legged Doji
        • Long Line
        • Matching Low
        • Marubozu
          • Marubozu Bearish
          • Marubozu Bullish
        • On Neck
        • Rickshaw Man
        • Rise Fall Three Methods
        • Separating Lines
        • Shooting Star
        • Short Line
        • Simple Double Down Candle
        • Simple Double Up Candle
        • Simple Down Candle
        • Simple Up Candle
        • Spinning Top
        • Stalled Pattern
        • Stick Sandwich Down
        • Stick Sandwich Up
        • Tasuki Gap
        • Three Black Crows
        • Three Inside Down
        • Three Inside Up
        • Three Line Strike
          • Three Line Strike Bearish
          • Three Line Strike Bullish
        • Three Outside Down
        • Three Outside Up
        • Three Stars in North
        • Three Stars in South
        • Three White Soldiers
        • Tristar
        • Thrusting
        • Two Crows
      • Aroon
      • Aroon Oscillator
      • Awesome Oscillator
      • Balance of Power (BOP)
      • Blind Indicator
      • Bollinger Bands
      • Bollinger Bands %B
      • Bollinger Bands %W
      • Commodity Channel Index (CCI)
      • Chande Momentum Oscillator (CMO)
      • Connors RSI (CRSI)
      • Coppock Curve
      • Detrended Price Oscillator (DPO)
      • Donchian Channels
      • Double Exponential Moving Average (DEMA)
      • Dynamic Buy/Sell
      • Elliot Wave Prediction
      • Exponential Moving Average (EMA)
      • Fast RSI
      • Fibonacci Retracements
      • Fixed Buy/Sell
      • Fractals
      • Ichi Clouds
      • Kaufmans Adaptive Moving Average (KAMA)
      • Keltner Channels
      • Momentum
      • Money Flow Index
      • Moving Average Convergence Divergence (MACD)
      • Parabolic SAR
      • Percentage Price Oscillator
      • Rate Of Change (ROC)
      • Rate Of Change Percent (Alternative) (ROC)
      • Regression Slope Cross
      • Relative Strength Index (RSI)
      • Script Indicator (C#)
      • Simple Moving Average (SMA)
      • Slow RSI
      • Small Fractals
      • Stochastic Oscillator
      • StochRSI
      • Stochastic^2
      • Timed Blind Indicator
      • Tom Demark Sequential (TD)
      • Triangular Moving Average (TRIMA)
      • Triple Exponential Average (TRIX)
      • Triple Exponential Moving Average (TEMA)
      • Ultimate Oscillator
      • Weighted Moving Average (WMA)
      • Williams %R
    • Safeties
      • Stop Loss
        • Stop Loss
        • Stop Loss (Fixed)
        • Stop Loss (Dynamic)
        • Stop Loss (Trailing)
        • Close position below % loss
      • Take Profit
        • Take Profit
        • Take Profit (Fixed)
        • Take Profit (Dynamic)
        • Close position above x% profit
      • Roof-In
        • Roof-In
        • Roof-In (Fixed)
        • Roof-In (Dynamic)
        • Roof-In (Trailing)
      • Disable Bot
        • Deactivate bot after buy
        • Deactivate bot after sell
        • Deactivate after X Minutes
        • Deactivate after X Idle Trades
        • Deactivate After X Trades
      • Others
        • Close Before Settlement
        • Force Bot to stay Bought/Long
        • Force Bot to Stay Sold/Short
        • Price Dump
        • Price Pump
        • Reset last buy price
        • Reset last sell price
        • Trade On Trend Lines
      • Script
        • Script Safety (C#)
    • Insurances
      • Fee
        • Overcome Double The Fee Costs
        • Overcome Fee Costs
      • Script
        • Script Insurance (C#)
      • Others
        • Wait after order
      • Price
        • Never Buy Higher
        • Never Sell Lower
        • Absolute Price Change
        • Percentage Price Change
      • Profit/Loss
        • Be Profitable In X Trades
        • Disable on Losses
        • Stay Profitable
      • Trend
        • Trade Only Sideways
        • Trade Only Trending
  • Custom Bots
    • Accumulation Bot
    • Advanced Index Bot
    • C# Script Bot
    • Crypto Index Bot
    • Email Bot
      • Email provider guide
      • Tradingview alert guide
      • Troubleshooting
    • Flash Crash Bot
      • Setup guide
      • Profit calculation
      • Price spread examples
      • Full screen mode
      • Follow the trend
      • Deactivation safety
      • Order management
      • Amount calculator
    • Intelli Alice Bot
    • Inter-Exchange Arbitrage Bot
    • MadHatter Bot
      • Setup Guide
      • Full screen mode
    • Market Making Bot
    • Order Bot
      • Full screen mode
      • Template Manager
    • Ping Pong Bot
    • Scalper Bot
      • Replicating the Scalper Bot in a Trade Bot
    • Trend Lines Bot
    • Zone Recovery Bot
  • Bot Tools
    • Backtesting & Paper Trading
    • Bot Dashboard
    • Bot List
    • Bot Performance Analyzer
    • Haas Labs
  • Bot Extensions
    • Deactivate After Order
    • Deactivate On Safety
    • Flash Crash Bot Manager
    • Manage Bots On Email Alarm
    • Manage Bots On Price Alarm
    • Manage Bots On Indicator
    • Order Persistence
    • Panic Move
    • Trailing Stop
  • Asset Management
    • Portfolio
      • Settings
      • History Synchronisation
      • Dashboard
      • Asset Information
      • Asset Location
      • Asset Trends
      • Trade Profit
      • Trade Volume
      • Trade Frequency
      • Balance Per Day
      • Trade History
      • Deposit & Withdrawal History
      • Position History
    • External Wallet
  • Other Features
    • Advanced Orders
      • Stop Loss
      • Take Profit
      • Trailing Stop
    • Dashboard
      • Alarms
      • Bots Related
      • Bulk Widgets
      • Account Related
      • Calculators
      • Charts
      • Clocks
      • News & Media
      • Order book & Trades
      • Portfolio
      • Tickers
    • Indicator Scanner
    • Manual Trading
    • Marketview
    • Market Compare
    • Order Templates
    • Technical Analysis
  • Changelog
    • Stable Release
    • Beta Release
  • Other Resources
    • YouTube
    • Guides & Tutorials
    • Questions & Answers
    • Community Projects
  • Need Help?
    • Ask on Discord
    • Submit support ticket
Powered by GitBook
On this page
  • Supported license & Trade types
  • Settings
  • Language
  • Interface
  • Name
  • TicksBack
  • Init
  • GetResult
  • GetChartLines
  • GetChartData
  • SetParameters
  • TA-Lib
  • Creating classes
  • Debugging
  • Writing to log-file
  • Step-by-step debugging
  • Example script

Was this helpful?

  1. Trade Bots
  2. Indicators

Script Indicator (C#)

PreviousRelative Strength Index (RSI)NextSimple Moving Average (SMA)

Last updated 5 years ago

Was this helpful?

HTS's Script Indicator is a custom Indicator for the Trade Bot. This feature allows you to create and share your own indicators.

Check out Pshai's scripts for a set of pre-made custom indicators for use with your custom bot.

Supported license & Trade types

Supported License

Supported Trade Types

Spot trading

Simple license

Margin trading

Advanced license

Leverage trading

Settings

The Script Indicator has only one setting: the full path to the script.

Language

Interface

All indicator scripts must fully implement the IndicatorScript-interface:

    public interface IIndicatorScript
    {
        string Name { get; }
        int TicksBack { get; }
        void Init();
        IndicatorResult GetResult(IndicatorContext context);
        List<ChartRecord> GetChartLines();
        List<decimal> GetChartData();
        List<ScriptParameter> GetParameters();
        void SetParameters(Dictionary<string,object> parameters);
    }

Name

This property returns the name of the indicator. Haasbot will use this name for the indicator, instead of the general "Script Indicator", so it is clear for the user which script is being used.

    string Name { get { return "My Indicator"; } }

TicksBack

With this property you can configure how much price data (Bid, Ask, High, Low, Volume) must be kept in memory by the IndicatorContext. Make sure this is big enough to have enough data to do the necessary calculations in your script, while keeping it small enough to reduce memory usage and unnecessary CPU load when doing these calculations.

    using TicTacTec.TA.Library;
    // ...
    int TicksBack { get { return Core.SmaLookback(sma_length); } }

Init

This method is executed after creating the script-object the first time. You can use this to do any necessary initialization. The created script-object will stay in memory and will be used until the script is recompiled. An indicator-script is recompiled when Haasbot starts and when the Script Indicator settings-window is closed.

GetResult

This method will be executed every time Haasbot checks the indicator. It should return an IndicatorResult (Stay, Buy or Sell). An IndicatorContext-object is passed, containing current price details and a reference to the IndicatorAPI, giving access to historical price data for all supported platforms and currency pairs. The default behavior of this method is to always return Stay.

GetChartLines

GetChartLines is a property defining the chart lines which will be shown on the indicator chart. This property has to return a list of ChartRecord-objects, which define the properties of one chart line. For each line in the chart, you have to define a name, on which chart it has to be shown (0 on main chart - 1,2 and 3 will create their own charts) and optionally a color. When no color is defined, Haasbot assigns a color automatically. For an example, see lines 65 to 76 in the example script.

GetChartData

This method returns the data points which have to be shown in the chart(s). It should return a list of decimal's, in the same order as the ChartRecords returned by the GetChartLines-property. The length of the list returned by the GetChartLines-property should be the same length as the list returned by GetChartData. This method is called after calling GetResult(), so if any chart data is generated in the GetResult-method, you can store it in a class member, and return it in GetChartData to be shown on the indicator chart.GetParametersThis method returns the parameters the user can configure for this script. It should return a list ScriptParameter objects. These ScriptParameter objects define for each parameter the name, current value, type and optionally some info text shown to the user. The user will be able to configure these parameters in the Haasbot user interface. The current value has to be cast into string.

    List<ScriptParameter> GetParameters()
    {
        return new List<ScriptParameter>
            {
                new ScriptParameter("SMA Length", ScriptParameterType.Integer, sma_length.ToString()),
                new ScriptParameter("A Useless Decimal", ScriptParameterType.Decimal, (123.456M).ToString()),
                new ScriptParameter("Foo", ScriptParameterType.String, "Bar")
            }
    }

SetParameters

This method is called when the script parameters are modified in the Haasbot user interface. The argument is a dictionary with the parameter names as dictionary-keys, and the parameter values as dictionary-values. The type of the values is object, so you need to cast them to the correct type (the same type as you defined in the ScriptParameter in GetParameters). When only specific values or range of values is valid for a certain parameter, you can do the checks here and revert to the previous value if an invalid value was set by the user.After SetParameters is called, the name of the script (the Name-property) is retrieved again. This way, when parameters are used in the name, the name is updated when the parameters are updated.

    void SetParameters(Dictionary<string, object> parameters)
    {
        sma_length = Convert.ToInt32( parameters["SMA Length"] );
    }

TA-Lib

In an indicator script you have access to TA-Lib for calculating any technical analysis indicators. All functions are static members of the static class Core in the namespace TicTacTec.TA.Library. It is not necessary to include external references to use TA-Lib, but having them allows the of your IDEs intellisense.

The PriceInstrument property in the IndicatorContext contains multiple arrays of doubles (Asks, Bids, High, Low, Volume), which can directly be used as input for the TA-Lib-functions.

Creating classes

You can define your own classes and structs in a script. You only have to make sure the class implementing the IIndicatorScript-interface is the first class in the file.

Debugging

Writing to log-file

You can write debug-info to a log file, by calling Logger.LogToFile(message) on the IndicatorContext-object. The message will be written (together with a timestamp) to a log-file. The log-file has the name of the script and is located at the Haasbot execution path.

Step-by-step debugging

Coming soon

Example script

// The reference files (found in Haasbot installation folder):
//  - TradeServer.ScriptingDriver.dll
//  - TradeServer.Interfaces.dll
//  - TA-Lib-Core.dll
using TradeServer.ScriptingDriver.DataObjects;
using TradeServer.ScriptingDriver.Interfaces;
using TicTacTec.TA.Library;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System;
 
public class ExampleScript : IIndicatorScript
{
    //Data to be shown in the indicator-chart:
    private double buyPrice;
    private double emaShort;
    private double emaLong;
 
    //Parameters:
    private int emaShortLength = 7;
    private int emaLongLength = 30;
 
    public string Name
    {
        get{ return string.Format("Script: EMA {0}-{1}", emaShortLength, emaLongLength); }
    }
 
 
    public int TicksBack
    {
        get { return Core.EmaLookback(emaLongLength) + 1; }
    }
 
    public List<ScriptParameter> GetParameters()
    {
        return new List<ScriptParameter>(){
            new ScriptParameter(){Name = "EMA short length", 
                                  Type = ScriptParameterType.Integer, 
                                  Value = emaShortLength.ToString(),
                                  Info = "The length of the shorter/faster EMA."},
            new ScriptParameter(){Name = "EMA long length", Type = ScriptParameterType.Integer, Value = emaLongLength.ToString()}
        };
    }
 
    public void SetParameters(Dictionary<string, object> parameters)
    {
        emaShortLength = Convert.ToInt32(parameters["EMA short length"]);
        emaLongLength = Convert.ToInt32(parameters["EMA long length"]);
    }
 
 
 
    public IndicatorResult GetResult(IndicatorContext context)
    {
        PriceInstrument instrument = context.PriceInstrument;
        int dataCount = instrument.Close.Length;
 
        int beginIndexShort, outNBElementsShort;
        int beginIndexLong, outNBElementsLong;
        double[] emaShortValues = new double[dataCount];
        double[] emaLongValues = new double[dataCount];
 
        var emaShortReturnCode = Core.Ema(0, dataCount - 1, instrument.Close, emaShortLength, out beginIndexShort, out outNBElementsShort, emaShortValues);
        var emaLongReturnCode = Core.Ema(0, dataCount - 1, instrument.Close, emaLongLength, out beginIndexLong, out outNBElementsLong, emaLongValues);
 
        if (emaShortReturnCode == Core.RetCode.Success && emaLongReturnCode == Core.RetCode.Success){    
 
            buyPrice = instrument.Close[dataCount - 1]; //Take current (last) value
 
            if(outNBElementsShort == 0 || outNBElementsLong == 0){
                // Something went wrong
                emaShort = buyPrice;
                emaLong = buyPrice;
                return IndicatorResult.Stay;
            }else{
                emaShort = emaShortValues[outNBElementsShort - 1]; //Take current EMA (last one of the valid values)
                emaLong = emaLongValues[outNBElementsLong - 1]; //Take current EMA (last one of the valid values)
 
                context.Logger.LogToFile("EMA Short: " + emaShort + "\tEMA Long:" + emaLong); //Log to file
 
                //Determine indicator signal
                if(emaShort > emaLong)
                    return IndicatorResult.Buy;
                else if(emaLong > emaShort)
                    return IndicatorResult.Sell;
                else
                    return IndicatorResult.Stay;
            }
        }else{
            context.Logger.LogToFile("EMA calculation failed."); //Log to file
            return IndicatorResult.Stay;
        }
    }
 
    public List<ChartRecord> GetChartLines()
    {
        return new List<ChartRecord>()
        {
            new ChartRecord(ChartIndex = 1, Name = "Buy Price", HexLineColor = "#00FF00"),
            new DataSerie(Name = "EMA Short", ChartIndex = 1, HexLineColor = "#FF0000"),
            new DataSerie(Name = "EMA Long", ChartIndex = 1, HexLineColor = "#FFFF00")
        };
    }
 
    public List<double> GetChartData()
    {
            return new List<double>()
            {
                buyPrice,
                emaShort,
                emaLong
            };
    }
}

The scripts are C#-scripts, using the CLR.

CS-Script
VisualStudioIntellisense1.png
Pshai Scripts (C#)Developer Center
Logo