-
-
Notifications
You must be signed in to change notification settings - Fork 54
How it's work
Setup all mentioned trade parameter at the top of cli_X_AAABBB.py
Where X is exchange number, see it in ms_cfg.toml and AAABBB is trade pair, for example BTCUSDT on Binance is cli_9_BTCUSDT.py
The main parameters for the strategy are grid parameters. Specify the trade direction for the first cycle. If START_ON_BUY = True, a grid of buy orders will be placed and take profit will be for sale.
Specify the deposit size for the first cycle in the desired currency, and the number of grid orders. These are related parameters, there is a limit on the minimum size of the order, so a many orders if the deposit is insufficient will not pass the verification during initialization.
The size of the order in the grid calculated according to the law of geometric progression, while the MARTIN parameter is a coefficient of progression.
The first order, the price of which is closest to the current one is the smallest in volume. On calculation of the volume of the first order.
To avoid the execution of the first order "by market" its price set with a slight offset, which is determined by the parameter PRICE_SHIFT.
It happens that when place a grid, the price goes in the opposite direction. There is no point in waiting in this case, we need to move the grid after the price. For this there are SHIFT_GRID_DELAY. Configure them or leave the default values.
The range of prices that overlaps the grid of orders affects profitability directly and must correspond to market conditions. If it is too wide combined with small number of orders, the cycle time will be too long, and most of the deposit will not be involved in turnover. With a small overlap, the entire order grid will be executed in a short time, and the algorithm will be reversed, while the profit on the cycle not fixed.
The overlap range can be fixed. Then it is defined by OVER_PRICE = xx and ADAPTIVE_TRADE_CONDITION = False.
For automatic market adjustment, ADAPTIVE_TRADE_CONDITION = True. In this case, the instant value of the Bollinger Band on 20 * 1 hour candles used to calculate the overlap range. The minimum values are limited by the exchange limit for minimal price change per one step combined with number of orders.
For fine-tuning there is KBB parameter. By default, value 2.0 is used to calculate Bollinger curves.
The over price value update before the start of the new cycle and periodically refreshed. If the market condition change exceeds the set limits, the grid is updated (does not apply in reverse cycle).
Two parameters determine the number of orders, ORDER_Q and OVER_PRICE. For start cycle and parameter ADAPTIVE_TRADE_CONDITION = False, these are absolute and fixed values.
For Reverse cycle or parameter ADAPTIVE_TRADE_CONDITION = True they specify the density of grid orders. At the same time, the larger the range of overlap, the more orders there will be. When calculating, the exchange's restrictions on the minimum order size and price step taken into account and thus limit the maximum number of orders.
For Reverse cycle, this is especially important, since with large price fluctuations we will have to sweep a very large range, 30-50% or more. In which case an adaptive number of orders will allow to do this as efficiently as possible.
For successful trading, the speed of the bot response to price fluctuations is important. When testing on Bitfinex, I noticed that when placed a group of orders, the first 5 are placed quickly, and the remaining ones with a significant delay. Also, the more orders, the longer it takes to shift the grid.
Therefore, I added the parameter GRID_MAX_COUNT, which specifies the number of initial orders to be placed. Then, two options performed. First, the grid shift function triggered. Second, one of the placed grid orders executed, and after successful creation of the take profit order, the next part GRID_MAX_COUNT of hold grid orders added. If total count of active grid orders more than ORDER_Q and hold grid not exhaust each next placed one after filling one grid order, until the hold list exhausted.
Thus, we always have a given number of active orders to respond to price fluctuations and have a large range of price overlap. Then, we do not risk running into the ban from exchange for exceeding the limit.
You can increase the share of the deposit in turnover when calculating the price for grid orders using not a linear, but a logarithmic distribution. The density of orders near the current price will be higher, which increases the likelihood of their execution.
Use LINEAR_GRID_K parameter and see '/doc/Model of logarithmic grid.ods' for detail.
It happens that all grid orders completed. Then we believe that we successfully bought the asset, and place a take profit order. Instead of one order, we place a grid, which ensures the break-even strategy. The grid parameters change dynamically, depending on the market conditions, accumulated deposit during execution of the Reverse cycle, and the specified profitability parameters.
With each successful completion of the reverse cycle, the accumulated profit volume increases, which reduces the necessary price overlap for the profitable completion of the original cycle.
In order for the algorithm not to work for itself in reverse mode, only half part of the earned profit is reinvested. Every odd Reverse cycle increase depo, every even - increase Free assets, which can be withdrawal
To boost trade in case of low market volatility: TP order is updated once every 15 minutes, and in Reverse cycle grid update once an hour.
You can buy/sell asset with grid options at the best price at the moment. Grid parameters are calculated as usual, except the grid shift price threshold, which is calculated on the basis of the Bollinger Band indicator with a period of 15 minutes. In the Bye cycle, the threshold is set at the lower limit, for "Sell" it is set at the upper limit. When executing some orders, the grid shift mode remains ACTIVE, which allows us to complete the cycle regardless of the price move.
To do this, set the parameter GRID_ONLY = True
In this case, the take-profit order will not be placed and Reverse cycle not started. After filling all grid orders strategy goes to STOP state.
Another option is to set the parameter USE_ALL_FUND = True
, which switch-on the mode of continuous Buy/Sell of an
asset. In this case, the entire available volume will be converted at the best price and the program will go into
standby mode. The transfer or deposit of the asset activates the conversion mode.
This mode (on the master account) is convenient in combination with the
COLLECT_ASSETS
parameter (on the sub-account). Available funds earned in a sub-account are automatically transferred to a master account, where they are automatically converted into the selected stablecoin currency.
As the grid orders executed, the volume of the take profit order sums up their volume, price averaged and increased to override the fees and earn the specified profit.
Do not set PROFIT too large. This reduces the probability of executing a take profit order with small price fluctuations. I settled on a value of about 0.1 - 0.25 The fee amount will be added to this value.
For adaptive calculate profit before place order you can set PROFIT_MAX (0.5 - 0.85). Then its value will be set in the range from PROFIT to PROFIT_MAX. Calculation based on Bollinger Band indicator.
When take profit order executed the cycle results recorded, the deposit increased by the cycle profit, and bot restarted.
To correctly count fees for MAKER and TAKER, you must set the FEE_MAKER and FEE_TAKER parameters.
For fee processing in first or second currency only, like as HTX on HTX or BNB on Binance, use FEE_FIRST = True
or FEE_SECOND = True
Attention: the commission, which is charged in the third coin (HTX or BNB, for example), is taken into account in the calculation of income and accumulated on account at current pair assets and must be converted in third asset for payment of commission.
In this case, if the commission is charged in a third currency, you need to monitor its availability on the main (HTX) or sub-account. To maintain a given balance of the desired asset, launch a separate pair on the main account, where free funds are accumulated with the following parameters:
ex.SYMBOL = 'HTXUSDT' # Using HTX as an example, the commission is charged from HTX to the main account
ex.AMOUNT_FIRST = Decimal('1500000') # Target level of first (HTX) asset
ex.AMOUNT_SECOND = Decimal('20') # Depo in second coin (USDT) for Buy cycle
ex.START_ON_BUY = True # First cycle direction
ex.GRID_ONLY = True
ex.COLLECT_ASSETS = False
Thus, as HTX is spent to pay the commission, as soon as the level falls below the target and there is a sufficient amount of USDT, the buying cycle starts.
Implemented for Binance sub-accounts only
To receive a commission discount you must:
- enable the option in the account settings on the exchange use BNB to pay commission
- have enough BNB in the sub-account in addition to the pair assets
The process of supplying working sub-accounts with BNB is now automated. To understand, a view from above:
- The working strategy on the sub-accounts generates profit
- Using Asset management the profit is accumulated on the master sub-account
- Using the Keeping level of first asset settings, the specified volume of BNB is maintained on the master sub-account
- These settings force the working pair to monitor the BNB level and generate a request to the strategy on master sub-account for replenishment (the strategy on the master sub-account and working strategies must be launched on the same instance,
funds_rate.db
is used to the BNB transfer request):
ex.FEE_MAKER = Decimal('0.075') # standard exchange Fee for maker
ex.FEE_TAKER = Decimal('0.075') # standard exchange Fee for taker
ex.FEE_FIRST = False # For example fee in BNB and BNB in pair, and it is base asset
ex.FEE_SECOND = False # For example fee in BNB and BNB in pair, and it is quote asset
# Setting for auto deposit BNB on subaccount for fee payment. For Binance subaccount only.
# See also https://github.com/DogsTailFarmer/martin-binance/wiki/How-it's-work#keeping-level-of-first-asset
ex.FEE_BNB = {
'id_exchange': 0, # Where collected assets and keeping BNB volume
'symbol': 'BNB/USDT', # Specified on the source strategy (id_exchange above)
'email': 'sub-account@email.com', # Email registered on this subaccount
'target_amount': '0', # BNB in USD equivalent, no less than min_notional
'tranche_volume': '0' # BNB in USD equivalent, no less than min_notional
}
Depositing Asset:
- There is no limitation on depositing assets. Depositing any asset from pair within an active strategy will involve them in active trading, leading to adjustments of internal variables and, if necessary, re-balancing of orders.
Withdrawing Asset:
- Employ Asset management to extract accrued profits without halting the strategy's operation.
- For preferred withdrawal while minimizing working capital, await the completion of the active cycle. Utilize Telegram-based management to stop the strategy, withdraw the asset, adjust initial parameters, and relaunch the strategy.
- You can also withdraw all available funds (not locked in orders) at any time. Depending on the strategy's state, this may have unintended consequences.
Basic information about the state of the bot, for example, about the start and results of the cycle, can be sent to Telegram bot.
- status - get current status
- stop - stop after end of cycle (if current cycle is reverse - only after back to direct cycle)
- end - stop after end of cycle, direct and reverse, no difference
- restart - save current state, reload config and restart
All commands are sent as a reply to message from desired strategy. Use simple text message or menu items. For use menu after first run strategy in Telegram bot use /start command once. If all is normal, you will receive a confirmation that the system has received the command within 10 seconds.
Analytic subsystem is not mandatory and has no impact on trading strategy. From 3.0.16 you can use SAVE_ASSET = False
parameter for disable this feature. This can be useful if:
- you want to save resources if you don't need this feature overall
- if bots for one (sub)account are running on different VPS instances, then this feature should be disabled on one of them to avoid data duplication in the consolidated analytics.
All data collected into funds_rate.db
Cycle time, yield, funds, initial cycle parameters, all this for all pairs and exchanges where this bot launched.
It Sqlite3 db with very simple structure, in table t_funds each row is the result of one cycle with parameters and result.
Now I'm use prometheus -> Grafana for calculate and visualization analytic data. It's useful. You can use funds_rate_exporter.py for start. Find it into repository.
Also, you can try the martin_binance/service/grafana.json
as example of consolidated report.
If you have several trading pairs on different exchanges, then regular valuation of the asset is a very time-consuming task.
At the end of each trading cycle, deposit data recorded for each currency. Once a day, the current currency rate to USD
is queried. In funds_rate_exporter.py
of times per minute calculated data for unloading in
prometheus. An example of a summary report implemented on Grafana
located above.
To receive quotes, you need to get the free API key on CoinMarketCap.
Specify the key at the top of the ms_cfg.toml and start funds_rate_exporter.py
as service. For Ubuntu,
you can use /service/funds_export.service
The result of working in the reverse cycle is a gradual accumulation of assets that are not included in the turnover and can be withdrawn. With a significant number of trading pairs on several sub-accounts, this is a rather laborious task. First, you need to transfer the available funds to one account and convert these assets into one coin.
Starting from version 1.2.10, the function of automatic transfer of free funds from operating sub-accounts to the main account is implemented.
In this case, the main account is not used for trading, it serves for asset management: accumulation, conversion, distribution, withdrawal.
Some settings change:
Update cli_XX_AAABBB.py
from martin_binance/cli_0_BTCUSDT.py.template
and
set up params ex.COLLECT_ASSETS = True
Also need change into exchanges-wrapper server config file, see details here
- Auto for Network failure, exchange timeout etc.
- Auto recovery after restart with full implemented Tmux install (Linux only)
- For manual restart with save order and load last state run
./cli_X_AAABBB.py 1
You can ask any questions about strategy in discussions section. Create issue if you have trouble or suggestions for development.
1. Home
- Trade idea
- Features
- Quick start
- Terminal Tmux (useful tips)
-
How it's work
- Place grid
- Reverse
- Grid only
- Place take profit order
- Restart
- Fee options
- Keeping level of first asset
- Maintaining a supply of BNB in a sub-account to pay fees
- Deposit and withdraw assets on active strategy
- Telegram notification
- Telegram control
- Save data for external analytics
- Consolidated asset valuation
- Asset management
- Recovery after any reason crash, restart etc.
- Back testing and parameters optimization
- For developers