HTClient Documentation
Introduction
HTClient is the HedgeTech app. It can be operated in order to customize, run and monitor trading algorithms.
This documentation helps naviguating through the infrastructure of HTClient and its User Interface (UI). We recommend reading this document while having HTClient opened.
Target Audience and Target Markets
HTClient is particularly suitable for token issuers, exchanges, market makers and broker/dealers.
Token issuers can operate the systems within their company, on all exchanges they are listed on.
Exchanges can operate the systems in-house for their main pairs as well as all other altcoins listed on their platform.
Market makers can chose to either use the algorithms designed by HedgeTech or to design their own custom scripts, benefiting from our integration capabilities and server infrastructure.
Broker/dealers can add to the services they offer with an all-in-one liquidity provision system.
The scripts are suitable for any market environment: major coins, altcoins, utility tokens, security tokens, futures, perpetual contracts, swaps, ETFs and all other digital assets.
Installation
After registering a HedgeTech account, the username
, password
and secretkey
can be used to access HTClient. Each of these should be carefully saved and securely stored.
Windows
After downloading HTClient at https://www.hedgetech.io, the first time HTClient.exe is opened, a message might show up saying that Windows Defender Smartscreen has protected the PC. If that is the case, please click More info
and if the developer shows HedgeTech LLC
, safely select Run Anyway
. Windows may run a security scan. The next times HTClient.exe is opened, this extra step is not required.
Mac OS X
After downloading HTClient at https://www.hedgetech.io, drag the app to your Applications folder. The first time HTClient.app is opened, an error message may appear saying that this app cannot be opened. If that is the case, simply run the following code in your Mac Terminal:
sudo xattr -rd com.apple.quarantine
Followed by a space, and then drag the app file in the Terminal. Hit Enter
, enter the password of the device (note: the password will not be displayed on the screen) and hit Enter
. The next times HTClient.app is opened, this extra step is not required.
Installation Q&A
Below are a list of situations encountered on the users' end and corresponding fixes.
For Mac OS users:
- HTClient does not request to receive keystrokes, nor is input monitoring permission required to run the app. Simply decline if prompted by your system. This is a problem that other mainstream apps such as Adobe encounter and that is due to certain keyboard drivers.
For Windows users:
- If you encounter an error saying Open GL outdated but your graphics drivers are up-to-date, you can change multisamples=2 to multisample=0 in the file %HOMEPATH%\.kivy\config.ini
Syntax
Please make sure to follow accurately the syntax such as upper and lower cases.
str
: text, e.g. some text
int
: integer number, e.g. 1
float
: decimal number, e.g. 1.1
bool
: True
or False
expression
: the expression of a function that is calculated with the following operators: +
, -
, *
, /
, (
, )
and the following components:
-
ask
: The lowest ask price -
bid
: The highest bid price -
unit
: The base price increment -
last
: The last traded price -
mid
: The middle price between the lowest ask and the highest bid (only applies toschedule
) -
unitR
: A random integer among -1, 0 or 1 (only applies toschedule
) -
uniformR
: A random float between 0 and 1 (only applies toschedule
)
e.g. bid+unit
will return the price that is one base price increment higher than the highest bid
IP Adresses
For security reasons, our servers use non-static IPs. In order to use HTClient, make sure to whitelist all IPs on your exchange accounts by not filling any IP under the exchange website IP whitelist field. If the exchange does not provide this feature on their website, please get in touch with the exchange directly.
API Permissions
For your own security, please make sure to manage permissions if the exchange offers this feature. In order to use HTClient read/write permissions for everything except withdrawal/deposit should be enabled.
Python Library
HedgeTech has developed and maintains htwrapper, its official Python Library. It allows users to interact with HedgeTech's API that gives access to all of HTClient's functionalities and more. Installation is available via the command pip install htwrapper
. A detailed documentation is available via the command help(htwrapper)
.
Strategy Catalog
Market Making
Script class symbol: maker
Purpose: The maker
script class provides liquidity to the market, it narrows the market spread and it makes profits from the spread when the price fluctuates.
Details: It maintains a number of orders on both the buy and sell sides for a currency pair. It lets the price behave according to supply and demand in the market, it adjusts the maintained orders automatically: when people sell, the price will move down; when people buy, the price will move up.
Use cases: Provide liquidity on any market and offer a competitive spread in price to achieve an efficient market environment where traders can enter and exit at fair prices.
Account(s): Main account only.
Parameters | Description | Type |
---|---|---|
base | Market symbol of the base currency |
str , e.g. eth for the market ETH/USDT |
quote | Market symbol of the quote currency |
str , e.g. usdt for the market ETH/USDT |
levels | Number of orders maintained on each side of the order book | int |
density | The distance between orders placed within the same side of the order book |
float , percentage, e.g. 0.002 means 0.2% |
aveVolume | Average amount of each order. By default in quote currency (optionally can be set in base currency). | float for average volume in quote currency (default); str starting with # and followed by a number for average volume in base currency |
randomness | Desired degree of randomness of the order amount around aveVolume |
float , between 0 and 1: 0 is no randomess; 1 is maximum randomness |
spread | Distance between the first ask order and the first bid order to be placed. It is recommended to set a spread of at least (3 x density) and that (spread - density) > (2 x trading fees) |
float , percentage, e.g. 0.01 means 1% |
manualInitPrice (Optional) | To specify an initiation price manually | float |
initPriority (Optional) | The order of in which different elements are taken into consideration to determine the initiation price. Can be any combination of the following elements: gecko (for CoinGecko price if available), last (for last traded price), mid (for mid price between ask1 and bid1), manual (for manually entered price). Seperated by comma, from the first element to be considered to the last. Default is gecko,last,mid. | str , can be any combination of the following elements: gecko (for CoinGecko price if available), last (for last traded price), mid (for mid price between ask1 and bid1), manual (for manually entered price) |
initFillPrevention (Optional) | Turn on to prevent the first order to be placed when initiating to fill an external order on the orderbook. Default is False | bool , input True to turn it on |
baseName (Optional) | Full name of the base currency. Must specify if multiple currencies listed as the same symbol on CoinGecko. Case sensitive | str |
quoteName (Optional) | Full name of the quote currency. Must specify if multiple currencies listed as the same symbol on CoinGecko. Case sensitive | str |
stopConditionBase (Optional) | The stop condition for base currency. By default, hard stop condition for total balance; if triggered (total balance under threshold), the script will be paused and orders will be cancelled. Alternatively, soft stop can be set for available balance; if triggered (available balance under threshold), the script will pause but orders will not be cancelled | float for total balance hard stop condition; str starting with # and followed by a number for available balance soft stop condition |
stopConditionQuote (Optional) | The stop condition for quote currency. By default, hard stop condition for total balance; if triggered (total balance under threshold), the script will be paused and orders will be cancelled. Alternatively, soft stop can be set for available balance; if triggered (available balance under threshold), the script will pause but orders will not be cancelled | float for total balance hard stop condition; str starting with # and followed by a number for available balance soft stop condition |
Note: after putting maker online, if you need to change the following parameters: levels, aveVolume, randomness, spread, density, the script will automatically clear storage, clear orders and restart with the desired parameters.
Stable Market Making (or Market Making with Price Matching)
Script class symbol: stable
Purpose: The stable
script class provides liquidity to the market and narrows the market spread, while matching the price to a desired index.
Details: It maintains a number of orders on both the buy and sell sides for a currency pair around a given price. Such a price is defined by the base value and/or quote value. You can define the base value and the quote value to be set values, or use the market price that is reported by CoinGecko.
Warning: It can place taker orders to match the price to the index value. As a result, there are situations in which external orders can be actively filled. Please reach out if more information is necessary.
Use cases: Provide liquidity and narrow spread on stablecoin markets or tokens that are pegged to a specific value.
Account(s): Main account only.
Parameters | Description | Type |
---|---|---|
base | Market symbol of the base currency |
str , e.g. eth for the market ETH/USDT |
quote | Market symbol of the quote currency |
str , e.g. usdt for the market ETH/USDT |
baseValue | The USD value of the base currency | Pass int or float to define a stable value; pass market for the value to be automatically adjusted to the price reported by CoinGecko; pass an api expression to automatically read a value from a third party api; pass a stableExpression that resolves to a float value, see Stable Expression. |
quoteValue | The USD value of the quote currency | Pass int or float to define a stable value; pass market for the value to be automatically adjusted to the price reported by CoinGecko; pass an api expression to automatically read a value from a third party api; pass a stableExpression that resolves to a float value, see Stable Expression.. |
askNum | Number of ask orders to be maintained | int |
bidNum | Number of bid orders to be maintained | int |
density | The distance between orders placed within the same side of the order book |
float , percentage, e.g. 0.002 means 0.2% |
aveVolume | Average amount in quote currency of each order | float |
randomness | Desired degree of randomness of the order amount around aveVolume |
float , between 0 and 1: 0 is no randomess; 1 is maximum randomness |
spread | Distance between the first ask order and the first bid order to be placed. It is recommended to set a spread of at least (3 x density) and that (spread - density) > (2 x trading fees) |
float , percentage, e.g. 0.01 means 1% |
baseName (Optional) | Full name of the base currency. Must specify if multiple currencies listed as the same symbol on CoinGecko. Case sensitive | str |
quoteName (Optional) | Full name of the quote currency. Must specify if multiple currencies listed as the same symbol on CoinGecko. Case sensitive | str |
preventTaker (Optional) | Turn on to prevent filling external orders on the orderbook while attempting to match price to index value. Default is False | bool , input True to turn it on |
apis (Optional) | A sequence of external APIs that can be used in smartswapExpression
|
Sequence of apiExpression separated by , , see API Expression
|
stopConditionBase (Optional) | The stop condition for base currency: if the total base currency balance is lower than the threshold, the script will pause | float |
stopConditionQuote (Optional) | The stop condition for quote currency: if the total quote currency balance is lower than the threshold, the script will pause | float |
Stable Expression
stableExpression
is a special expression that is used for the stable
script class. It follows standard python
syntax and can use the following expression variables:
Expression Variables | Description | Type |
---|---|---|
apiValues | A list of values that are retrieved from third party APIs defined in the config parameter apis
|
list |
Create an API Expression
An API expression is used to assign the baseValue
and/or quoteValue
to a value automatically read from a third party API. Only REST APIs with a json
response body are allowed.
To create an API expression, the first step is to construct a json
object that has the following attributes:
Key | Description | Type |
---|---|---|
url | The full url of the API from which the value will be read (including the query string) | str |
method | The API request method |
str , available values: "get", "post", "delete", "put" |
keyChain | A list of keys that resolve the raw response into a single value. See this example | array |
headers (Optional) | The headers of the API request constructed in json format if any |
json |
data (Optional) | The request body of the API if any | str |
Once the json
object is constructed, convert it to str
and encode it with base64
.
Finally, add REST-
at the beginning of the base64
encoded string. The API expression should look like this: REST-eyJ1cmwiOiAiaHR0cHM6Ly9hcGkuYmluYW5jZS5jb20vYXBpL3YzL3RpY2tlci8yNGhyP3N5bWJvbD1CTkJCVEMiLCAibWV0aG9kIjogImdldCIsICJrZXlDaGFpbiI6IFsibGFzdFByaWNlIl19
Keychain Example
Assuming the raw response of the API is as follows:
{
"key1": {
"key11": 6,
"key12": [
1,
3,
7
]
},
"key2": 10
}
The keyChain
should be an array
of keys that leads to the value to be resolved. If the value to be resolved is 3
, the keyChain
should be ["key1", "key12", 1]
(note that the index of an array
starts from 0
). If the value to be resolved is 10
, the keyChain
should be ["key2"]
.
Orderbook Replication
Script class symbol: replication
Purpose: The orderbook replication
strategy replicates the liquidity from an exchange with more liquidity to an exchange with less liquidity, in order to provide liquidity on the exchange with less liquidity. This strategy makes profits from strictly hedging the risk.
Details: Whenever the orders maintained on the exchange with less liquidity are filled, it will hedge the position by placing market orders and take the liquidity from the exchange with more liquidity.
Warning: This is a relatively advanced script class, please reach out if more information is necessary before implementing it.
Use cases: Provide liquidity and narrow spread on major pairs on exchanges with little liquidity, pairs with little liquidity for a given token.
Account(s): Both main account and secondary account. Main account is the account on the exchange on which liquidity will be added (the one with less liquidity), secondary account is the account on the exchange on which liquidity will be taken from (the one with more liquidity).
Parameters | Description | Type |
---|---|---|
base | Market symbol of the base currency |
str , e.g. eth for the market ETH/USDT |
quote | Market symbol of the quote currency |
str , e.g. usdt for the market ETH/USDT |
levels | Number of orders maintained on each side of the order book on the exchange with less liquidity | int |
divergence | The price distance between the orders placed on the exchange with less liquidity and the existing orders on the exchange with more liquidity. The larger divergence is, the higher the maintained spread and the lower the maintained order density will be on the exchange with less liquidity. However density has to be large enough to cover the trading fees on both exchanges combined and the transaction fee when transfering balance from one exchange to the other. Divergence must be greater than the maximum between (2 x base price unit) and (2 x trading fees + withdrawal fee) |
float , percentage, e.g. 0.01 means 1% |
percentage | The percentage of liquidity to be replicated from the exchange with more liquidity to the exchange with less liquidity |
float , percentage, e.g. 0.01 means 1%. In order to hedge the position effectively, it is recommended to limit this parameter to a maximum of 0.2 |
volumeCap | A hard maximum on the amount of each order in quote currency on the exchange with less liquidity | float |
randomness | When the order amount exceeds the volumeCap for a given order, instead of placing an order exactly at the volumeCap , it will place an order around volumeCap with a degree of randomness. |
float , between 0 and 1: 0 is no randomess; 1 is maximum randomnesss |
quoteSecondary (Optional) | Symbol of the quote currency of the secondary account. Sepcify if the hedging market pair has a different quote currency | str , e.g. usdt for the market ETH/USDT |
settlementModel (Optional) | The parameter determines how to place the hedging orders on the secondary account. Default is feeAdjustedfillPrice
|
<marketPrice : hedging orders will be market orders with a maximum slippage of divergence. fillPrice : hedging orders will be limit orders at the price where the orders on the main account are filled. feeAdjustedfillPrice : hedging orders will be limit orders at the price where the orders on the main account are filled, plus a markup of both exchange fees combined. divergenceAdjustedFillPrice : hedging orders will be limit orders at the price where the orders on the main account are filled, plus a markup of divergence. |
exchangeFeeRateMain (Optional) | Maker fee on the exchange (main account). Default is 0.2% |
float , percentage, e.g. 0.01 means 1% |
exchangeFeeRateSecondary (Optional) | Taker fee on the exchange (secondary account). Default is 0.2% |
float , percentage, e.g. 0.01 means 1% |
stopConditionBaseMain (Optional) | The stop condition for base currency for the main account: if the total base currency balance is lower than the threshold, the script will pause. Same value applies to both main and secondary | float |
stopConditionQuoteMain (Optional) | The stop condition for quote currency for the main account: if the total quote currency balance is lower than the threshold, the script will pause. Same value applies to both main and secondary | float |
stopConditionBaseSecondary (Optional) | The stop condition for base currency for the secondary account: if the total base currency balance is lower than the threshold, the script will pause. Same value applies to both main and secondary | float |
stopConditionQuoteSecondary (Optional) | The stop condition for quote currency for the secondary account: if the total quote currency balance is lower than the threshold, the script will pause. Same value applies to both main and secondary | float |
Pool Liquidity Migration
Purpose: The migrate
strategy builds and maintains a dense tradeable orderbook on an exchange by taking liquidity provided by the community from a liquidity pool. This strategy makes profits from strictly hedging the risk.
Details: Whenever the orders maintained on the exchange are filled, it will hedge the position by swapping and thus taking liquidity from liquidity pool.
Warning: This is a relatively advanced script class, please reach out if more information is necessary before implementing it.
Use cases: Build and maintain a tradeable orderbook on an exchange while fully hedging the risk against a liquidity pool and realizing profits.
Account(s): Both main account and swap wallet. Main account is the account on the exchange on which liquidity will be added (orderbook will be built), swap wallet is the wallet connected to the liquidity pool. The swap account first needs to follow the instructions on the liquidity pool to approve swaping for the desired pair.
Parameters | Description | Type |
---|---|---|
base | Market symbol of the base currency on the exchange |
str , e.g. token for the market TOKEN/BTC |
quote | Market symbol of the quote currency on the exchange |
str , e.g. btc for the market TOKEN/BTC |
route | A comma separated sequence of token addresses from base asset to quote asset. The route can be found on the liquidity pool's user interface. On Uniswap, if the base or quote asset is ETH, input eth as either the begining or the end of the route. On Pancakeswap, if the base or quote asset is BNB, input bnb as either the begining or the end of the route |
Sequence of str separated by , . On Uniswap: if ETH is a base or quote, input eth ; if ETH is found along the route, input the WETH address instead. On Pancakeswap: if BNB is a base or quote, input bnb ; if BNB is found along the route, input the WBNB address instead |
tickSize | The distance between orders placed within the same side of the order book |
float , percentage, e.g. 0.002 means 0.2% |
divergenceMultiplier | Integer multiplier of tickSize to set divergence. Divergence is the price distance between the orders placed on the exchange and the corresponding price levels on the liquidity pool. The larger divergence is, the higher the maintained spread (spread will be (1 + 2 x divergenceMultiplier) x tickSize) and the lower the maintained order density will be on the exchange. However density has to be large enough to cover the trading fees on the exchange, the swap (network) fees as well as transfer fees between the liquidity pool and the exchange. |
int |
maxGasPrice | Maximum gas price in GWEI. If the gas price exeeds this amount, the script will pause |
float or int |
percentUpper | The highest percentage of liquidity to be migrated from the liquidity pool to the exchange. If the liquidity between price levels on the liquidity pool exceeds the volume of orders on the exchange by that percentage, resize the orders on the exchange |
float , percentage, e.g. 0.01 means 1%. In order to hedge the position effectively, it is recommended to limit this parameter to a maximum of 0.5 |
percentLower | The lowest percentage of liquidity to be migrated from the liquidity pool to the exchange. If the liquidity between price levels on the liquidity pool is lower than the volume of orders on the exchange by that percentage, resize the orders on the exchange |
float , percentage, e.g. 0.01 means 1%. In order to hedge the position effectively, it is recommended to limit this parameter to a maximum of half of the percentUpper value |
volumeCap | A hard maximum on the amount of each order in quote currency on the exchange. It is recommended to set a volumeCap that has a higher USD value than the minSwapVolume USD value | float |
levels | Number of orders maintained on each side of the orderbook on the exchange | int |
randomness | When the order amount exceeds the volumeCap for a given order, instead of placing an order exactly at the volumeCap , it will place an order around volumeCap with a degree of randomness |
float , between 0 and 1: 0 is no randomess; 1 is maximum randomnesss |
swapTimeOut (Optional) | A swap will revert if the number of seconds specified has elapsed without confirmation. The recommended value for non ethereum based liquidity pools is 180 to 300. Default is 1200 |
int , e.g. 300 will make the swap retry after 5 minutes |
tolerance (Optional) | If the price changes by more than the tolerance within the confirmation window, the swap will revert to ensure no losses (to frontrunning using gaz price auction for example). Default is half of divergence |
float , percentage, e.g. 0.01 means 1% |
forceSettle (Optional) | If True and swap cannot settle opened position at a profit (due to price change during confirmation for example), instead of waiting for an oppotunity to settle for profit, it will force settling the position immediately (attention: may result in losses). Default is False |
bool |
exchangeFeeRate (Optional) | Maker fee on the exchange (main account). Default is 0.2% |
float , percentage, e.g. 0.01 means 1% |
gasMultiplier (Optional) | Defines a multiple of the gas fee that should be covered by the profit margin when determining minimum swap volume. Default is 3 |
float , e.g. 2 means twice |
nativeToTokenRoute (Optional) | A comma separated sequence of token addresses from wrapped native token to base asset. The route can be found on the liquidity pool's user interface. On Uniswap, must start with eth as the begining of the nativeToTokenRoute. On Pancakeswap, must start with bnb as the begining of the nativeToTokenRoute |
Sequence of str separated by , |
avoidSwing (Optional) | Whether to turn on the price swing protection mechanism. The mechanism aims at protecting from adverse consequences during large price movements while a swap is confirming. Default is False |
bool |
avoidSwingN (Optional) | The number of price data points to calculate price moving average. Default is 60 |
int |
avoidSwingMinN (Optional) | The minimum number of price data points to detect price swings. If the number of recorded price data points is less than avoidSwingMinN, the script will not start. Default is 15 |
int |
avoidSwingFreq (Optional) | The number of seconds between recorded price data points. Default is 60 |
int |
avoidSwingRidOutlier (Optional) | The number of extreme high/low values to be ignored when calculating rolling average and standard deviation. Default is 2 |
int |
avoidSwingStdDevMulti (Optional) | The number of standard deviations away from the rolling average to be considered as price swing. Default is 2 |
float |
stopConditionBase (Optional) | The stop condition for base currency. If the total base currency balance for either the exchange account or swap waller is lower than the threshold, the script will pause and orders will be cancelled | float |
stopConditionQuote (Optional) | The stop condition for quote currency. If the total quote currency balance for the exchange account is lower than the threshold, the script will pause and orders will be cancelled | float |
Arbitrage
Script class symbol: arbitrage
Purpose: For a given base currency, the arbitrage
strategy can do same exchange cross pair arbitrage, cross exchange same pair arbitrage and cross exchange cross pair arbitrage.
Details: The script will look for all arbitrage opportunities for a given base currency. If only a main account is specified, the script will only look for cross pair arbitrage opportunities on the exchange of the account. However, if both a main and a secondary accounts are specified, the script will look for all combinations of arbitrage opportunities (i.e. cross pairs on the main account exchange, cross pairs on the secondary account exchange, same pair and cross pairs accross both exchanges). Arbitrage opportunities are defined by the threshold parameter.
Warning: For cross exchange arbitrage (whether same pair or cross pair), rebalance will be needed at times between the main and secondary accounts. Losses will be incurred if the threshold parameter is not large enough to cover fees (see below).
Use cases: Generate profits from price discrepancies between pairs for a given base currency. Works very well in combination with maker
to effectively reduce price discrepancies between pairs for a given currency, especially major pairs on small exchanges that want to reduce adverse arbitrage opportunities and pairs with price dicrepancies for a given token in order to reduce adverse arbitrage opportunities.
Account(s): Main account only for same exchange cross pair arbitrage; main account and secondary account for both same exchange and cross exchange arbitrage (whether same pair or cross pair).
Parameters | Description | Type |
---|---|---|
base | Market symbol of the base currency |
str , e.g. eth for the market ETH/USDT |
quoteListMain | All quote currencies for the pairs listed on the exchange of the main account. Seperated by comma, spaces will be ignored. |
str , e.g. eth, btc, usdt for arbitrage across the pairs base/eth, base/btc and base/usdt |
threshold | The minimum price difference for arbitrage to make profits. The threshold has to cover the trading fees - for arbitrage across the same pair (on different exchanges): the trading fee will be twice the taker fees; for cross pair arbitrage (either on the same exchange or on different exchanges), the trading fee will be three times the taker fees - and withdrawal fees combined |
float , percentage, e.g. 0.01 means 1% |
quoteListSecondary (Optional) | All quote currencies for the pairs listed on the exchange of the secondary account. Seperated by comma, spaces will be ignored. |
str , e.g. eth, btc, usdt for arbitrage across the pairs base/eth, base/btc and base/usdt |
quoteOrder (Optional) | The order in which the quote currencies are typically quoted against each other. If specified, all quotes listed in quoteListMain (and quoteListSecondary, if cross exchange arbitrage) should be included. Seperated by comma, spaces will be ignored. |
str , e.g. For arbitrage pairs base/eth, base/btc, base/usdt, since eth is quoted against btc and usdt (eth/btc, eth/usdt), and since btc is quoted against usdt only (btc/usdt), then the quoteOrder should be eth, btc, usdt
|
stopConditionMain (Optional) | The stop condition(s) for the main account. Use colon to seperate the currency symbol and the stop threshold; use comma to seperate stop conditions for different currencies. Spaces will be ignored |
str , e.g. btc: 1, eth: 30 for stop conditions to be 1 BTC and 30 ETH |
stopConditionSecondary (Optional) | The stop condition(s) for the secondary account. Use colon to seperate the currency symbol and the stop threshold; use comma to seperate stop conditions for different currencies. Spaces will be ignored |
str , e.g. btc: 1, eth: 30 for stop conditions to be 1 BTC and 30 ETH |
Liquidity Pool Arbitrage
Purpose: For a given base currency, the swaparb
strategy can do arbitrage between an exchange and a liquidity pool.
Details: The script will look for all arbitrage opportunities for a given base currency. Arbitrage opportunities are defined by the threshold parameter.
Warning: Rebalance will be needed at times between the main account and swap wallet. Losses will be incurred if the threshold parameter is not large enough to cover fees (see below).
Use cases: Generate profits from price discrepancies between pairs for a given base currency.
Account(s): Both main account and swap wallet. Main account is the account on the exchange that is not the liquidity pool, swap wallet is the wallet connected to the liquidity pool. The swap account first needs to follow the instructions on the liquidity pool to approve swaping for the desired pair.
Parameters | Description | Type |
---|---|---|
base | Market symbol of the base currency on the exchange |
str , e.g. token for the market TOKEN/BTC |
quote | Market symbol of the quote currency on the exchange |
str , e.g. btc for the market TOKEN/BTC |
route | A comma separated sequence of token addresses from base asset to quote asset. The route can be found on the liquidity pool's user interface. On Uniswap, if the base or quote asset is ETH, input eth as either the begining or the end of the route. On Pancakeswap, if the base or quote asset is BNB, input bnb as either the begining or the end of the route |
Sequence of str separated by , . On Uniswap: if ETH is a base or quote, input eth ; if ETH is found along the route, input the WETH address instead. On Pancakeswap: if BNB is a base or quote, input bnb ; if BNB is found along the route, input the WBNB address instead |
threshold | The minimum price difference for arbitrage to make profits. The threshold has to cover the trading fees - both taker fee and swap fee and liquidity providers fees on all pools along the route - and withdrawal fees combined |
float , percentage, e.g. 0.01 means 1% |
maxGasPrice | Maximum gas price in GWEI. If the gas price exeeds this amount, the script will pause |
float or int |
tolerance (Optional) | If the price changes by more than the tolerance within the confirmation window, the swap will revert to ensure no losses (to frontrunning using gaz price auction for example).Default is one half of threshold. |
float , percentage, e.g. 0.01 means 1% |
exchangeFeeRate (Optional) | Maker fee on the exchange (main account). Default is 0.2% |
float , percentage, e.g. 0.01 means 1% |
gasMultiplier (Optional) | Defines a multiple of the gas fee that should be covered by the profit margin when determining minimum swap volume. Default is 3 |
float , e.g. 2 means twice |
stopConditionBase (Optional) | The stop condition for base currency. If the total base currency balance for either the exchange account or swap waller is lower than the threshold, the script will pause and orders will be cancelled | float |
stopConditionQuote (Optional) | The stop condition for quote currency. If the total quote currency balance for the exchange account is lower than the threshold, the script will pause and orders will be cancelled | float |
Pools Arbitrage
Purpose: For a given base currency, the poolsarb
strategy can do arbitrage between liquidity pools.
Details: The script will look for all arbitrage opportunities for a given base currency. Arbitrage opportunities are defined by the threshold parameter.
Warning: Rebalance will be needed at times between the main wallet and secondary wallet. Losses will be incurred if the threshold parameter is not large enough to cover fees (see below). This is a relatively advanced script class, please reach out if more information is necessary before implementing it.
Use cases: Generate profits from price discrepancies between pools for a given base currency.
Account(s): Both main wallet and secondary wallet (note: both accounts need to be created with associated exchange evm
on HTClient as this script support liquidity pools based on EVM chains). Wallets first need to follow the instructions on the liquidity pools to approve swaping for the desired pairs. Note: must use two different wallets on the same chain on two different liquidity pools to avoid frontrunning by MEV bots and/or losses due to confirmation time (but can use 1 wallet for both accounts if on different chains).
Parameters | Description | Type |
---|---|---|
routeMain | For the main account. The AMM name and column followed by a comma separated sequence of token addresses from base asset to quote asset. The route can be found on the liquidity pool's user interface. If the base or quote asset in the route is the AMM chain native token, input the AMM chain native token token symbol as either the begining or the end of the route. However, if the AMM chain native token is found along the route, or if you would like to avoid wrapping fees with every transaction (and you provided inventory in wrapped native token), input the address of the wrapped version of this token instead. The destination currencies on both routes have to have the same value in USD (e.g. stablecoin on both). Note: for AMM based on the uniswap v3 model (allowing for liquidity concentration), specify the fee tier in between the tokens that constitute a given pool |
Sequence of str separated by , . Example for the ETH/USDT pool on Uniswap v2: uniswap: eth, 0xdac17f958d2ee523a2206206994597c13d831ec7 . Example for the 0.3% fee ETH/USDT pool on Uniswap v3: uniswap: eth, 0.0003, 0xdac17f958d2ee523a2206206994597c13d831ec7 |
routeSecondary | For the secondary account. The AMM name and column followed by a comma separated sequence of token addresses from base asset to quote asset. The route can be found on the liquidity pool's user interface. If the base or quote asset in the route is the AMM chain native token, input the AMM chain native token token symbol as either the begining or the end of the route. However, if the AMM chain native token is found along the route, or if you would like to avoid wrapping fees with every transaction (and you provided inventory in wrapped native token), input the address of the wrapped version of this token instead. The destination currencies on both routes have to have the same value in USD (e.g. stablecoin on both). Note: for AMM based on the uniswap v3 model (allowing for liquidity concentration), specify the fee tier in between the tokens that constitute a given pool |
Sequence of str separated by , . Example for the ETH/USDT pool on Uniswap v2: uniswap: eth, 0xdac17f958d2ee523a2206206994597c13d831ec7 . Example for the 0.3% fee ETH/USDT pool on Uniswap v3: uniswap: eth, 0.0003, 0xdac17f958d2ee523a2206206994597c13d831ec7 |
gasCovered (Optional) | Multiplier of gas fee (gas fee = gas spent*gas price, for both legs of and arbitrage transaction combined) to be covered during an arbitrage, default is 1. Should be greater or equal to 1 (to break even or make profits) |
float , greater or equal to 1 |
toleranceMain (Optional) | For the main account. If the price changes by more than the tolerance within the confirmation window, the swap will revert to ensure no losses (to frontrunning using gaz price auction for example). Default is 0.5% |
float , percentage, e.g. 0.01 means 1% |
toleranceSecondary (Optional) | For the secondary account. If the price changes by more than the tolerance within the confirmation window, the swap will revert to ensure no losses (to frontrunning using gaz price auction for example). Default is 0.5% |
float , percentage, e.g. 0.01 means 1% |
timeoutMain (Optional) | For the main account. Defines a time limit for a non validated swap to time out. If time out is hit, the script will look for the next available opportunity to settle the imbalance |
int , number of seconds, e.g. 0.01 means 1% |
timeoutSecondary (Optional) | For the secondary account. Defines a time limit for a non validated swap to time out. If time out is hit, the script will look for the next available opportunity to settle the imbalance |
int , number of seconds, e.g. 0.01 means 1% |
nTickGroups (Optional) | Number of words (each word having 256*tickSpacing ticks) to consider when scanning liquidity. If nTickGroups = n, the script will scan 2n+1 tick words (the current tick word, n words above, n words below). Thus, the price interval in percent that the script scans is: currentWord*1.0001^(256*tickSpacing)^n up and currentWord/1.0001^(256*tickSpacing)^n down, with tickSpacing depending on a given pool setting (the smart contract of a given pool contains tick spacing information). Should be greater or equal to 1. Default is 1 |
int , greater or equal to 1 |
forceSettle (Optional) | Turn on to force the settlement of imbalance blindly, regardless of price (i.e. potentially at a loss), in case one swap (one leg of the arbitrage transaction) succeeds but the other fails. Default is False |
bool |
imbalanceSwapMaxGasPriceMain (Optional) | For the main account. Defines the max gas price in gwei for the settlement of imbalance in case one swap (one leg of the arbitrage transaction) succeeds but the other fails. Default is 100 |
int |
imbalanceSwapMaxGasPriceSecondary (Optional) | For the secondary account. Defines the max gas price in gwei for the settlement of imbalance in case one swap (one leg of the arbitrage transaction) succeeds but the other fails. Default is 100 |
int |
gasLimitMultiplier (Optional) | The script estimates the gas limit to set for each leg of the arbitrage transaction. If the gas limit is exhausted, the transaction will fail and the gas spent is not refunded by the validator. The multiplier is the same for each leg of the arbitrage transaction. Should be greater or equal to 1. Default is 1.2 |
float , greater or equal to 1 |
Market Entry (or Buy-Back, or Accumulate)
Script class symbol: enter
Purpose: The enter
strategy is designed to efficiently purchase a large amount of tokens on the secondary market without influencing the price and suffering from a large slippage.
Details: The user specifies a certain price threshold and the script will purchase as much as possible at or under that threshold.
Use cases: Efficiently accumulate tokens at the lowest price possible, build a price support (that can be moved up gradually).
Account(s): Main account only.
Parameters | Description | Type |
---|---|---|
base | Market symbol of the base currency |
str , e.g. eth for the market ETH/USDT |
quote | Market symbol of the quote currency |
str , e.g. usdt for the market ETH/USDT |
maxPrice | The price threshold: the script will actively puchase only at a price lower than this threshold |
float for price in quote currency or str in the format of {price}-{symbol} for price in a specific currency, e.g. 0.00000135-btc to set the price to 0.00000135 in BTC |
threshold | The volume threshold: the script will actively fill an order that has an amount in base currency that is higher than this threshold only | float |
leftOver | In order to not impact the price, the script will always fill part of an order and leave a leftover amount, in base currency | float |
bidVolume | When the price is lower than the price threshold, the script will always maintain a bid order on top of the bid side of the orderbook. This parameter specifies the average amount in base currency of the maintained bid order | float |
randomness | Desired degree of randomness of the order amount around bidVolume. Also applies to leftOver |
float , between 0 and 1: 0 is no randomess; 1 is maximum randomness |
movingAverageN (Optional) | The number of periods when calculating price moving average. Needs to be specified in combination with movingAverageFreq . If the price is higher than the moving average, the script will pause |
int , e.g. 10 will calculate the 10 movingAverageFreq price moving average |
movingAverageFreq (Optional) | The number of seconds in each period when calculating price moving average. Needs to be specified in combination with movingAverageN . If the price is higher than the moving average, the script will pause |
int , e.g. 300 will calculate the 5 minutes movingAverageN price moving average |
dustValue (Optional) | The best orderbook bids will be ignored if their amount in base currency are lower than dustValue. The script will determine the best price level for the maintained bid to be right above the price of the first bid that has an amount higher than dustValue | float |
baseName (Optional) | Full name of the base currency. Must specify if multiple currencies listed as the same symbol on CoinGecko. Case sensitive | str |
quoteName (Optional) | Full name of the quote currency. Must specify if multiple currencies listed as the same symbol on CoinGecko. Case sensitive | str |
stopConditionBase (Optional) | The stop condition for base currency: if the total base currency balance is higher than the threshold, the script will pause | float |
stopConditionQuote (Optional) | The stop condition for quote currency: if the total quote currency balance is lower than the threshold, the script will pause | float |
Market Exit (or Sell-Off, or Liquidate)
Script class symbol: exit
Purpose: The exit
strategy is designed to efficiently sell a large amount of tokens on the secondary market without influencing the price and suffering from a large slippage.
Details: The user specifies a certain price threshold and the script will sell as much as possible at or above that threshold.
Use cases: Efficiently liquidate tokens at the highest price possible.
Account(s): Main account only.
Parameters | Description | Type |
---|---|---|
base | Market symbol of the base currency |
str , e.g. eth for the market ETH/USDT |
quote | Market symbol of the quote currency |
str , e.g. usdt for the market ETH/USDT |
minPrice | The price threshold: the script will actively sell only at a price higher than this threshold |
float for price in quote currency or str in the format of {price}-{symbol} for price in a specific currency, e.g. 0.00000135-btc to set the price to 0.00000135 in BTC |
threshold | The volume threshold: the script will actively fill an order that has an amount in base currency that is higher than this threshold only | float |
leftOver | In order to not impact the price, the will always fill part of an order and leave a leftover amount, in base currency | float |
askVolume | When the price is higher than the price threshold, the script will always maintain an ask order at the bottom of the sell side of the orderbook. This parameter specifies the average amount of the maintained ask order in base currency | float |
randomness | Desired degree of randomness of the order amount around askVolume. Also applies to leftOver |
float , between 0 and 1: 0 is no randomess; 1 is maximum randomness |
movingAverageN (Optional) | The number of periods when calculating price moving average. Needs to be specified in combination with movingAverageFreq. If the price is lower than the moving average, the script will pause | int , e.g. 10 will calculate the 10 movingAverageFreq price moving average |
movingAverageFreq (Optional) | The number of seconds in each period when calculating price moving average. Needs to be specified in combination with movingAverageN. If the price is lower than the moving average, the script will pause | int , e.g. 300 will calculate the 5 minutes movingAverageN price moving average |
dustValue (Optional) | The best orderbook asks will be ignored if their amount in base currency are lower than dustValue. The script will determine the best price level for the maintained ask to be right below the price of the first bid that has an amount higher than dustValue | float |
baseName (Optional) | Full name of the base currency. Must specify if multiple currencies listed as the same symbol on CoinGecko. Case sensitive | str |
quoteName (Optional) | Full name of the quote currency. Must specify if multiple currencies listed as the same symbol on CoinGecko. Case sensitive | str |
stopConditionBase (Optional) | The stop condition for base currency: if the total base currency balance is lower than the threshold, the script will pause | float |
stopConditionQuote (Optional) | The stop condition for quote currency: if the total quote currency balance is higher than the threshold, the script will pause | float |
convert (Optional) | Optionally specify to convert the initial quote received to another currency | str , e.g. usdt for USDT as final target currency |
convertDirection (Optional) | The direction in which conversion trade is happening. Must be specified if convert is specified | str , e.g. sell if initial quote needs to be sold to final target currency in convert parameter (i.e. conversion market is quote/convert), buy if final target currency in convert parameter needs to be bought with initial quote (i.e. conversion market is convert/quote) |
convertThreshold (Optional) | Specify to only convert past that value in quote balance. Must be specified if convert is specified (input 0 to convert all quote on the account to final target currency) | float |
frictionLoss (Optional) | Provide a tolerance of slippage in percent on market quote/convert or convert/quote plus trading fees. minPrice will be adjusted automatically so that the price at which base is sold at equals minPrice input in final target currency after conversion. The higher, the faster the conversion will be realized, but the more minPrice will be increased. Must be specified if convert is specified (input 0 to set no tolerance to slippage and fees, in which case the conversion order will most likely be a limit order) | float , percentage, e.g. 0.01 means 1% |
Smart Swap
Script class symbol: smartswap
Purpose: smartswap
allows to specify conditional swaps on liquidity pools.
Warning: This is a relatively advanced script class, please reach out if more information is necessary before implementing it.
Account(s): swap wallet. Swap wallet is the wallet connected to the liquidity pool. The swap account first needs to follow the instructions on the liquidity pool to approve swaping for the desired pair.
Parameters | Description | Type |
---|---|---|
route | A comma separated sequence of token addresses from base asset to quote asset. The route can be found on the liquidity pool's user interface. On Uniswap, if the base or quote asset is ETH, input eth as either the begining or the end of the route. On Pancakeswap, if the base or quote asset is BNB, input bnb as either the begining or the end of the route |
Sequence of str separated by , . On Uniswap: if ETH is a base or quote, input eth ; if ETH is found along the route, input the WETH address instead. On Pancakeswap: if BNB is a base or quote, input bnb ; if BNB is found along the route, input the WBNB address instead |
condition | The swap condition |
smartswapExpression that resolves to a bool value, see Smartswap Expression
|
aveFreq | The average sleep time in seconds between two swaps when the condition is met | int |
randomness (Optional) | Desired degree of randomness of aveFreq and aveAmount . Default is 0.
|
float , between 0 and 1: 0 is no randomess; 1 is maximum randomness |
aveAmount (Optional) | Average volume in input token per swap transaction |
smartswapExpression that resolves to a float value, see Smartswap Expression
|
maxPriceImpact (Optional) | Maximum price impact tolerated. Only applies to aveAmount
|
float , percentage, e.g. 0.01 means 1% |
toExactPrice (Optional) | Target price to be attained for each swap. aveAmount will be ignored when toExactPrice is specified |
smartswapExpression that resolves to a float value, see Smartswap Expression
|
exactPriceImpact (Optional) | Target price impact to be attained for each swap. toExactPrice and aveAmount will be ignored when exactPriceImpact is specified |
smartswapExpression that resolves to a float value between 0 and 1 , see Smartswap Expression
|
minSwapVolume (Optional) | Minimum volume in input token per swap transaction. It is important to set a sufficient amount, i.e. significantly (100 times and above) higher than swap (network) fees. | float |
apis (Optional) | A sequence of external APIs that can be used in smartswapExpression
|
Sequence of apiExpression separated by , , see API Expression
|
tolerance (Optional) | If the price changes by more than the tolerance within the confirmation window, the swap will revert to ensure no losses (to frontrunning using gaz price auction for example). Default is one third of threshold. |
float , percentage, e.g. 0.01 means 1% |
maxGasPrice (Optional) | Maximum gas price in GWEI. If the gas price exeeds this amount, the script will pause |
float or int |
stopConditionBase (Optional) | If the balance in input token is lower than the stopCondition , the script will pause |
float |
Smartswap Expression
smartswapExpression
is a special expression that is used for the smartswap
script class. It follows standard python
syntax and can use the following expression variables:
Expression Variables | Description | Type |
---|---|---|
mid | Mid price for the pair input token/output token | float |
apiValues | A list of values that are retrieved from third party APIs defined in the config parameter apis
|
list |
API Expression
apiExpression
is used to get values from third party APIs. Only REST APIs with a json
response body are supported.
To create an API expression, the first step is to construct a json
object that has the following attributes:
Keys | Description | Type |
---|---|---|
url | The full url of the API (including the query string) | str |
method | The API request method |
str , available values: get , post , delete , put
|
keyChain | A list of keys that resolves the raw response into a single value. See this example | array |
headers (Optional) | The headers of the API request constructed in json format, if any |
json |
data (Optional) | The request body of the API, if any | str |
Once the json
object is constructed, convert it to str
and encode it with base64
.
Finally, add REST-
at the beginning of the base64
encoded string. The API expression should look like this: REST-eyJ1cmwiOiAiaHR0cHM6Ly9hcGkuYmluYW5jZS5jb20vYXBpL3YzL3RpY2tlci8yNGhyP3N5bWJvbD1CTkJCVEMiLCAibWV0aG9kIjogImdldCIsICJrZXlDaGFpbiI6IFsibGFzdFByaWNlIl19
Keychain Example
Assuming the raw response of the API is as follows:
{
"key1": {
"key11": 6,
"key12": [
1,
3,
7
]
},
"key2": 10
}
The keyChain
should be an array
of keys that leads to the value to be resolved. If the value to be resolved is 3
, the keyChain
should be ["key1", "key12", 1]
. If the value to be resolved is 10
, the keyChain
should be ["key2"]
. Note that the index of an array
starts from 0
.
Script class symbol: schedule
Purpose: schedule
recursive orders over time, spaced out by a given time interval.
Details: Every time it places a buy order, it will use the account that has more quote currency; everytime it places a sell order, it will use the account that has less quote currency.
Use cases: Customize a trading strategy without any coding background.
Account(s): Main account, secondary account is optional.
Parameters | Description | Type |
---|---|---|
base | Market symbol of the base currency |
str , e.g. eth for the market ETH/USDT |
quote | Market symbol of the quote currency |
str , e.g. usdt for the market ETH/USDT |
interval | The number of seconds between each time the order(s) is/are placed | float |
randomness | Desired degree of randomness of the order amount for each order |
float , between 0 and 1: 0 is no randomess; 1 is maximum randomness |
buyAmount (Optional) | The order amount of the buy orders to be placed | float |
buyPrice (Optional) | The price of the buy orders to be placed |
float tp place the orders at a set price, expression (see syntax) to place the orders according to the market conditions |
sellAmount (Optional) | The order amount of the sell orders to be placed | float |
sellPrice (Optional) | The price of the sell orders to be placed |
float to place the orders at a set price, expression (see syntax) to place the order according to the market conditions |
async (Optional) | In order to place orders simultaneously | bool |
makerOnly (Optional) | In order to prevent the orders placed to fill existing external orders | bool |
baseName (Optional) | Full name of the base currency. Must specify if multiple currencies listed as the same symbol on CoinGecko. Case sensitive | str |
quoteName (Optional) | Full name of the quote currency. Must specify if multiple currencies listed as the same symbol on CoinGecko. Case sensitive | str |
stopConditionBase (Optional) | The stop condition for base currency: if the total base currency balance is lower than the threshold, the script will pause | float |
stopConditionQuote (Optional) | The stop condition for quote currency: if the total quote currency balance is lower than the threshold, the script will pause | float |
Note: at least one pair (buyAmount
, buyPrice
) and/or (sellAmount
, sellPrice
) has to be specified.
HTClient Components
Accounts
Accounts are the exchanges accounts. Accounts also more broadly designate wallets connected to liquidity pools (note that you first need to approve a wallet for swaping on given pair of a liquidity pool before being able to use it on HTClient).
An account is defined by: the exchange it is on and its API keys. Some exchanges may require a trading password; others may require to specify if the main account is to be used (input $main
in the relevant field in HTClient's account page) or if a subaccount is to be used; yet others (such as liquidity pools) require wallet information.
The exchanges currently supported are: binance, coinbase, kraken, huobi, kucoin, bithumb (Korea and global), bitfinex, uniswap (V2, V3, arbitrum), bybit, traderjoe, sushiswap, pancakeswap, gate.io, okx, crypto.com, bittrex, ftx, alcor, poloniex, liquid, ascendex, upbit, probit, mexc, hitbtc, okcoin, xt.com, zb, fmfw, digifinex, bitget, whitebit, gopax, bitrue, bitbns, coinsbit, cointiger, apeswap (bsc), latoken, coineal, hoo, lbank, bitforex, bw.com, btse, dragonex, bhex, bitmart, stex, biki, vitex, idex, coinall, bispex, smartvalor, nbx, mandala, mexo, pangolin, quickswap, coinlist pro, lcx, osmosis, nagax.
Scripts
Scripts are the algorithms that run on our servers.
A script is defined by: script class, parameters and account(s) it uses.
Note that you cannot run multiple script classes for the same market(pair) with the same account.
Classes
A script class is the strategy that a script uses. There are public script classes that are available for all users, and there are also customized script classes that are defined by each individual user.
The public script classes are: maker, stable, replication, migrate, arbitrage, swaparb, poolsarb, enter, exit, smartswap, and schedule.
HTClient User Interface
Accounts Page
The account page is used to add new accounts, manage the existing accounts, and balances.
Scripts Page
The scripts page is used to add new scripts, manage and monitor existing scripts, clear orders and storage, check the server logs of a script and download reports (reports can be downloaded individually following the config parameters of each script or in bulk using the top right button which takes into consideration search key words). For some script classes, the recommended funding can be checked based on the parameters it uses.
Classes Page
The classes page is used to create and manage customized script classes.
Monitor Page
The monitor page displays all the scripts that may require attention on one screen.
In each script monitor, Monitor Metrics
is displayed on the left and Server Logs
is displayed on the right.
The Monitor Metrics
field displays some metrics of the script, account balances in the format: available/total. If the script monitor of a script is displayed on the monitor page, it shows that some of the script metrics are different from the config parameters settings. If that happens, check the Server Logs
field to see if there is any error.
If there is no error in logs, the script will normally correct itself and maintain the right metrics.
If there are errors in logs, some action will have to be taken according to the error. For example, if the error says insufficient balance, you will have to refill the account accordingly.
In case the error returned by the exchange is not clear, i.e. the exchange returns an error followed by a number, please refer to the error section of the API documentation of that exchange for more information on the error encountered. A general error encountered happens when an exchange performs maintenance: in that case the error will have an HTML format (involving characters such as <>), at that time the script is not running and no new order is being placed.
HedgeTech Account Page
The HedgeTech account page shows user's information and allows to manage subscription and change password.
Settings Page
The settings page is used to customize the number of logs for the monitor, the monitor refresh rate and the report dates. It provides the app version number as well as useful links such as root directory (where reports can be found), documentation, terms of use and privacy policy.
Search Bars
Several terms separated by commas can be entered when searching. Spaces are ignored.
If all these terms are contained in an account name, script name, script class or status (online or offline), the appropriate results will be shown; otherwise nothing will be displayed.
When using the search bar within the monitor page, the results will be displayed among the items present on the last update of the monitor. Searching something will not update the monitor.
Customized Scripts
Coding background is required passed this point.
Customized scripts allow to define your own script class and run it on our backend, thus benefiting from our centralized script management, exchange integration and servers stability and scalability.
Components
To define a customized script class, the following components need to be defined: Meta, Code Block and Monitor Metrics.
Meta
Meta is a json
object that defines the required and optional config parameters and accounts. It has to following attributes:
Attributes | Description |
---|---|
paramRequired | An array of required config parameter names |
paramOptional | An array of optional config parameter names |
accRequired | An array of required account types |
accOptional | An array of optional account types |
In addition to what is defined in Meta, there will be two public config parameters that apply to all customized script classes:
Parameters | Type | Description |
---|---|---|
_sleep | float |
The number of seconds between each iteration of the script |
_clear | string |
The pair symbol of the orders that will be cleared if the "Clear Orders" button is used on the script page |
Note: if the account type main
is defined, the exchange logo of that account will be displayed within the script on the monitor page.
Code Block
Code block is the code that defines what the script will do within each iteration. It follows python3.6 runtime, and it supports the following libraries: requests, websocket_client, numpy, scipy, pandas and Crypto. In addition predefined functions and objects can be used, and it is possible to interact with the server storage, server logs and the exchanges APIs.
Any Exception
raised will be output to the server logs, you can use "View Logs" in the script page to debug your code.
In code block, all variables you defined will not be considered as global. In the functions or classes, if you want to refer to a name in a way that has been defined previously, you have to pass it in the argument. Otherwise it will raise a nameError
. Here is an example:
message = 'hello world'
def output():
log(message)
output()
The above code will raise a nameError
: name "message" is not defined. Instead, you should use the following code:
message = 'hellow world'
def output(message):
log(message)
output(message)
Monitor Metrics
Monitor metrics determine what will be displayed within the script monitor on the script page and monitor page. As many monitor metrics as needed can be defined. Each monitor metric has the following three attributes:
Attributes | Description |
---|---|
Name | The name of the monitor metric |
Value Expression | A python3.6 expression that returns the value of the monitor metric. predefined functions and objects can be used. |
Range Expression | A python3.6 expression that returns a bool type value, in which the name value returns the value of the metric that is defined by the value expression. If the value of the expression is True , it indicates that this monitor metric is within its normal range. predefined functions and objects can be used. In the monitor page, if the range expression returns False for one or more monitor metric(s), it indicates that the script may require attention, and it will appear on the monitor screen. |
Predefined Functions and Objects
The following objects and functions are predefined, they can be used in the code block and the expressions of the monitor metrics. Warning: these names shall not be overwritten when working on the code block.
Get the config parameter value
get(key)
Argument | description | type |
---|---|---|
key | the name of the config parameter | str |
It returns the value of the config parameter. If the config parameter is not defined, it returns None
.
Interact with the script storage
Each script has a designated storage that can store key/value pairs. The following functions are used to interact with them.
read(key)
Argument | description | type |
---|---|---|
key | the key in the storage | str |
It returns the value associated with the key in the storage. If the key is not defined, it returns None
.
write(key, value)
Arguments | description | type |
---|---|---|
key | the key of the key/value pair | str |
value | the value of the key/value pair |
str , float , int , bool , None
|
This function writes a key/value pair in the storage.
Output to logs
Use the following function to output a message to logs instead of the print statement:
log(message)
Argument | description | type |
---|---|---|
message | the message to be outputed to logs | str |
Check CoinGecko price
market_price(symbol, fullName=None)
Argument | description | type |
---|---|---|
symbol | symbol of the currency on CoinGecko (lowercase) | str |
fullName (Optional) | Full name of the currency, must specify if multiple currencies listed as the same symbol on CoinGecko, case sensitive | str |
It returns the reported price of the token/coin in USD.
Get Exchange API Client
HT(accType)
Argument | description | type |
---|---|---|
accType | The account type of the account that is usded by the script | str |
It returns a Client
object that can be used to interact with the exchange API.
The Exchange API Client
The Client
object represents an account that is used by the script. It is used to interact with the exchange API. Note that the proper way to get an instance of this class is to call the HT
function. The following are the methods defined:
Get the orderbook
Client.orderbook(self, base, quote)
Arguments | description | type |
---|---|---|
base | the symbol of the base currency of the trading pair (lowercase) | str |
quote | the symbol of the quote currency of the trading pair (lowercase) | str |
It returns a nested dict
, i.e.
{
'asks': [
{
'price': 9186,
'volume': 0.32
},
...
],
'bids': [
{
'price': 9185,
'volume': 1.05
},
...
]
}
Get the rolling 24 hours volume in USD
Client.volume24(self, baes, quote)
Arguments | description | type |
---|---|---|
base | the symbol of the base currency of the trading pair (lowercase) | str |
quote | the symbol of the quote currency of the trading pair (lowercase) | str |
It returns the rolling 24 hours volume in USD as a float
.
Get the last traded price
Client.last(self, base, quote)
Arguments | description | type |
---|---|---|
base | the symbol of the base currency of the trading pair (lowercase) | str |
quote | the symbol of the quote currency of the trading pair (lowercase) | str |
It returns the last traded price as a float
.
Get the pair meta
Client.meta(self, base, quote)
Arguments | description | type |
---|---|---|
base | the symbol of the base currency of the trading pair (lowercase) | str |
quote | the symbol of the quote currency of the trading pair (lowercase) | str |
It returns a dict
that is defined as follows:
keys | description | type |
---|---|---|
"priceDecimal" | The price precision | int |
"volumeDecimal" | The volume precision | int |
"minPrice" | The minimum price allowed to place order | float |
"maxPrice" | The maximum price allowed to place order | float |
"minVolume" | The minimum volume allowed to place order | float |
"maxVolume" | The maximum volume allowed to place order | float |
Check balance of the account
Client.balance(self, *args)
Argument(s) | description | type |
---|---|---|
*args | the symbol of the currencies (lowercase) | str |
It returns a nested dict
, i.e.:
{
'btc': {
'available': 3.5,
'total': 3.7
},
...
}
Place an order
Client.place_order(self, base, quote, side, volume, price)
Arguments | description | type |
---|---|---|
base | the symbol of the base currency of the trading pair (lowercase) | str |
quote | the symbol of the quote currency of the trading pair (lowercase) | str |
side | trading side |
'buy' /'sell'
|
volume | the volume of the order in base currency | float |
price | the price of the order | float |
It returns {'success': True}
if the order goes through; it raises an Exception
with the exchange error message if it does not go through.
Get all open orders
Client.get_orders(self, base, quote)
Arguments | description | type |
---|---|---|
base | the symbol of the base currency of the trading pair (lowercase) | str |
quote | the symbol of the quote currency of the trading pair (lowercase) | str |
It returns a nested dict
, i.e.:
{
'asks': [
{
'symbol': 'btc_usdt',
'_type': 'ask',
'price': 9186,
'volume': 0.58,
'order_id': 49830927
},
...
],
'bids': []
}
Cancel an order
Client.cancel(self, order)
The argument order
is a dict
that has the same format as the return of the get_orders
function, order
can be referred to the element of the 'asks'
or 'bids'
field from the return of the get_orders
function, i.e.:
{
'symbol': 'btc_usdt',
'_type': 'ask',
'price': 9186,
'volume': 0.58,
'order_id': 49830927
}
It returns {'success': True}
if the order is cancelled successfully; it raises an Exception
with the exchange error message if cancelling does not go through.
Cancel all orders for a certain pair
Client.cancel_all(self, base, quote)
Arguments | description | type |
---|---|---|
base | the symbol of the base currency of the trading pair (lowercase) | str |
quote | the symbol of the quote currency of the trading pair (lowercase) | str |
It returns {'success': True}
if all orders are cancelled successfully; it raises an Exception
with the exchange error message if one or more order(s) did not get cancelled.