Skip to content

Commit

Permalink
2.0.0rc1
Browse files Browse the repository at this point in the history
  • Loading branch information
DogsTailFarmer committed Nov 1, 2023
1 parent d209109 commit 1238d86
Show file tree
Hide file tree
Showing 13 changed files with 323 additions and 201 deletions.
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
## 2.0.0rc1 - 2023-11-01
### Added for new features
* Bybit exchange V5 API support implemented. Supported account type is
[Unified Trading Account](https://testnet.bybit.com/en/help-center/article/Introduction-to-Bybit-Unified-Trading-Account),
for main and sub-accounts. Spot Trading only.

### Update
* Lost compatibility with margin.de terminal. Scripts developed for use with the terminal can be run as
executable modules, but not the other way around.
* The logic and implementation of monitoring exceptional situations when placing and deleting orders has been updated.
* Improved gRPC outage exception handling
* Up requirements

## 1.3.7.post3 - 2023-10-09
### Fix
Expand Down
16 changes: 7 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,9 @@ All risks and possible losses associated with use of this strategy lie with you.
Strongly recommended that you test the strategy in the demo mode before using real bidding.

## Important notices
* For `exchanges-wrapper` `v1.3.6b4`-`v1.3.6b7` must be updated `exch_srv_cfg.toml` (see [CHANGELOG](https://github.com/DogsTailFarmer/exchanges-wrapper/blob/master/CHANGELOG.md) for details)
* Starting with version `martin-binance 1.3.4`, compatibility with `margin` will be lost, since some new parts
of the code are no longer supported by implemented `Python 3.7`. I'm focused on `Python 3.10`.
I won't rid the code of numerous compatibility elements yet, so if the margin team will update its version,
everything should work.
* For [exchanges-wrapper](https://github.com/DogsTailFarmer/exchanges-wrapper) `v>= v1.4.0` must be updated `exch_srv_cfg.toml`
* Lost compatibility with `margin.de` terminal. Scripts developed for use with the terminal can be run as
executable modules, but not the other way around.

* You cannot run multiple pairs with overlapping currencies on the same account!

Expand All @@ -48,16 +46,16 @@ Strongly recommended that you test the strategy in the demo mode before using re
## Referral link
<p id="referral-link"></p>

Create account on [Binance](https://accounts.binance.com/en/register?ref=QCS4OGWR) and get 10% discount on all trading
fee
Create account on [Binance](https://accounts.binance.com/en/register?ref=QCS4OGWR) and get 10% discount on all trading fee

Create account on [HUOBI](https://www.huobi.com/en-us/topic/double-reward/?invite_code=9uaw3223) and will get 50 % off
trading fees
Create account on [HUOBI](https://www.huobi.com/en-us/topic/double-reward/?invite_code=9uaw3223) and will get 50 % off trading fees

Create account on [Bitfinex](https://www.bitfinex.com/sign-up?refcode=v_4az2nCP) and get 6% rebate fee

Create account on [OKEX](https://www.okex.com/join/2607649) and get Mystery Boxes worth up to $10,000

Create account on [Bybit](https://www.bybit.com/invite?ref=9KEW1K) and get exclusive referral rewards

Also, you can start strategy on [Hetzner](https://hetzner.cloud/?ref=uFdrF8nsdGMc) cloud VPS only for 4.75 € per month

### Donate
Expand Down
27 changes: 8 additions & 19 deletions martin_binance/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,20 @@
__author__ = "Jerry Fedorenko"
__copyright__ = "Copyright © 2021 Jerry Fedorenko aka VM"
__license__ = "MIT"
__version__ = "1.4.0.b2"
__version__ = "2.0.0rc1"
__maintainer__ = "Jerry Fedorenko"
__contact__ = "https://github.com/DogsTailFarmer"

from pathlib import Path
from shutil import copy

STANDALONE = True
if 'margin' in str(Path().resolve()):
print('margin detected')
STANDALONE = False
WORK_PATH = Path(Path.home(), ".MartinBinance")
CONFIG_PATH = Path(WORK_PATH, "config")
CONFIG_FILE = Path(CONFIG_PATH, "ms_cfg.toml")
DB_FILE = Path(WORK_PATH, "funds_rate.db")
if STANDALONE:
LOG_PATH = Path(WORK_PATH, "log")
LAST_STATE_PATH = Path(WORK_PATH, "last_state")
BACKTEST_PATH = Path(WORK_PATH, "back_test")
else:
LOG_PATH = None
LAST_STATE_PATH = None
BACKTEST_PATH = None
LOG_PATH = Path(WORK_PATH, "log")
LAST_STATE_PATH = Path(WORK_PATH, "last_state")
BACKTEST_PATH = Path(WORK_PATH, "back_test")


def init():
Expand All @@ -37,19 +28,17 @@ def init():
else:
print("Can't find client config file! Creating it...")
CONFIG_PATH.mkdir(parents=True, exist_ok=True)
if STANDALONE:
LOG_PATH.mkdir(parents=True, exist_ok=True)
LAST_STATE_PATH.mkdir(parents=True, exist_ok=True)
LOG_PATH.mkdir(parents=True, exist_ok=True)
LAST_STATE_PATH.mkdir(parents=True, exist_ok=True)
copy(Path(Path(__file__).parent.absolute(), "ms_cfg.toml.template"), CONFIG_FILE)
copy(Path(Path(__file__).parent.absolute(), "funds_rate.db.template"), DB_FILE)
copy(Path(Path(__file__).parent.absolute(), "cli_0_BTCUSDT.py.template"), Path(WORK_PATH, "cli_0_BTCUSDT.py"))
copy(Path(Path(__file__).parent.absolute(), "cli_1_BTCUSDT.py.template"), Path(WORK_PATH, "cli_1_BTCUSDT.py"))
copy(Path(Path(__file__).parent.absolute(), "cli_2_TESTBTCTESTUSDT.py.template"),
Path(WORK_PATH, "cli_2_TESTBTCTESTUSDT.py"))
copy(Path(Path(__file__).parent.absolute(), "cli_3_BTCUSDT.py.template"), Path(WORK_PATH, "cli_3_BTCUSDT.py"))
print(f"Before the first run, set the parameters in {CONFIG_FILE}")
if STANDALONE:
raise SystemExit(1)
raise UserWarning()
raise SystemExit(1)


if __name__ == '__main__':
Expand Down
11 changes: 4 additions & 7 deletions martin_binance/cli_0_BTCUSDT.py.template
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
__author__ = "Jerry Fedorenko"
__copyright__ = "Copyright © 2021 Jerry Fedorenko aka VM"
__license__ = "MIT"
__version__ = "1.3.4"
__version__ = "2.0.0"
__maintainer__ = "Jerry Fedorenko"
__contact__ = "https://github.com/DogsTailFarmer"
"""
Expand All @@ -17,10 +17,7 @@ Disclaimer
All risks and possible losses associated with use of this strategy lie with you.
Strongly recommended that you test the strategy in the demo mode before using real bidding.
##################################################################
For standalone use set SYMBOL parameter at the TOP of this file
Check and set parameter at the TOP part of script
Verify init message in Strategy output window for no error
"""
################################################################
Expand All @@ -32,7 +29,7 @@ from martin_binance.executor import * # lgtm [py/polluting-import]
################################################################
# Exchange setup and parameter settings
################################################################
# Set trading pair for STANDALONE mode, for margin mode takes from terminal
# Set trading pair for Strategy
ex.SYMBOL = 'BTCUSDT'
# Exchange setup, see list of exchange in ms_cfg.toml
ex.ID_EXCHANGE = 0 # See ms_cfg.toml Use for collection of statistics *and get client connection*
Expand Down Expand Up @@ -61,7 +58,7 @@ ex.SHIFT_GRID_DELAY = 15 # sec delay for shift grid action
ex.STATUS_DELAY = 5 # Minute between sending Tlg message about current status, 0 - disable
ex.GRID_ONLY = False # Only place grid orders for buy/sell asset
ex.LOG_LEVEL_NO_PRINT = [] # LogLevel.DEBUG Print for level over this list member
ex.COLLECT_ASSETS = False # Transfer free asset to main account, valid for STANDALONE mode on subaccount only
ex.COLLECT_ASSETS = False # Transfer free asset to main account, valid for subaccount only
# Parameter for calculate grid over price and grid orders quantity in set_trade_condition()
# If ADAPTIVE_TRADE_CONDITION = True, ORDER_Q / OVER_PRICE determines the density of grid orders
ex.ADAPTIVE_TRADE_CONDITION = True
Expand Down Expand Up @@ -139,5 +136,5 @@ def trade():
loop.close()


if __name__ == "__main__" and STANDALONE:
if __name__ == "__main__":
trade()
11 changes: 4 additions & 7 deletions martin_binance/cli_1_BTCUSDT.py.template
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
__author__ = "Jerry Fedorenko"
__copyright__ = "Copyright © 2021 Jerry Fedorenko aka VM"
__license__ = "MIT"
__version__ = "1.3.4"
__version__ = "2.0.0"
__maintainer__ = "Jerry Fedorenko"
__contact__ = "https://github.com/DogsTailFarmer"
"""
Expand All @@ -17,10 +17,7 @@ Disclaimer
All risks and possible losses associated with use of this strategy lie with you.
Strongly recommended that you test the strategy in the demo mode before using real bidding.
##################################################################
For standalone use set SYMBOL parameter at the TOP of this file
Check and set parameter at the TOP part of script
Verify init message in Strategy output window for no error
"""
################################################################
Expand All @@ -32,7 +29,7 @@ from martin_binance.executor import * # lgtm [py/polluting-import]
################################################################
# Exchange setup and parameter settings
################################################################
# Set trading pair for STANDALONE mode, for margin mode takes from terminal
# Set trading pair for Strategy
ex.SYMBOL = 'BTCUSDT'
# Exchange setup, see list of exchange in ms_cfg.toml
ex.ID_EXCHANGE = 1 # See ms_cfg.toml Use for collection of statistics *and get client connection*
Expand Down Expand Up @@ -61,7 +58,7 @@ ex.SHIFT_GRID_DELAY = 15 # sec delay for shift grid action
ex.STATUS_DELAY = 5 # Minute between sending Tlg message about current status, 0 - disable
ex.GRID_ONLY = False # Only place grid orders for buy/sell asset
ex.LOG_LEVEL_NO_PRINT = [] # LogLevel.DEBUG Print for level over this list member
ex.COLLECT_ASSETS = False # Transfer free asset to main account, valid for STANDALONE mode on subaccount only
ex.COLLECT_ASSETS = False # Transfer free asset to main account, valid for subaccount only
# Parameter for calculate grid over price and grid orders quantity in set_trade_condition()
# If ADAPTIVE_TRADE_CONDITION = True, ORDER_Q / OVER_PRICE determines the density of grid orders
ex.ADAPTIVE_TRADE_CONDITION = True
Expand Down Expand Up @@ -139,5 +136,5 @@ def trade():
loop.close()


if __name__ == "__main__" and STANDALONE:
if __name__ == "__main__":
trade()
11 changes: 4 additions & 7 deletions martin_binance/cli_2_TESTBTCTESTUSDT.py.template
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
__author__ = "Jerry Fedorenko"
__copyright__ = "Copyright © 2021 Jerry Fedorenko aka VM"
__license__ = "MIT"
__version__ = "1.3.4"
__version__ = "2.0.0"
__maintainer__ = "Jerry Fedorenko"
__contact__ = "https://github.com/DogsTailFarmer"
"""
Expand All @@ -17,10 +17,7 @@ Disclaimer
All risks and possible losses associated with use of this strategy lie with you.
Strongly recommended that you test the strategy in the demo mode before using real bidding.
##################################################################
For standalone use set SYMBOL parameter at the TOP of this file
Check and set parameter at the TOP part of script
Verify init message in Strategy output window for no error
"""
################################################################
Expand All @@ -32,7 +29,7 @@ from martin_binance.executor import * # lgtm [py/polluting-import]
################################################################
# Exchange setup and parameter settings
################################################################
# Set trading pair for STANDALONE mode, for margin mode takes from terminal
# Set trading pair for Strategy
ex.SYMBOL = 'TESTBTCTESTUSDT'
# Exchange setup, see list of exchange in ms_cfg.toml
ex.ID_EXCHANGE = 2 # See ms_cfg.toml Use for collection of statistics *and get client connection*
Expand Down Expand Up @@ -61,7 +58,7 @@ ex.SHIFT_GRID_DELAY = 15 # sec delay for shift grid action
ex.STATUS_DELAY = 5 # Minute between sending Tlg message about current status, 0 - disable
ex.GRID_ONLY = False # Only place grid orders for buy/sell asset
ex.LOG_LEVEL_NO_PRINT = [] # LogLevel.DEBUG Print for level over this list member
ex.COLLECT_ASSETS = False # Transfer free asset to main account, valid for STANDALONE mode on subaccount only
ex.COLLECT_ASSETS = False # Transfer free asset to main account, valid for subaccount only
# Parameter for calculate grid over price and grid orders quantity in set_trade_condition()
# If ADAPTIVE_TRADE_CONDITION = True, ORDER_Q / OVER_PRICE determines the density of grid orders
ex.ADAPTIVE_TRADE_CONDITION = True
Expand Down Expand Up @@ -139,5 +136,5 @@ def trade():
loop.close()


if __name__ == "__main__" and STANDALONE:
if __name__ == "__main__":
trade()
140 changes: 140 additions & 0 deletions martin_binance/cli_3_BTCUSDT.py.template
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
####################################################################
# Cyclic grid strategy based on martingale
# See README.md for detail
####################################################################
__author__ = "Jerry Fedorenko"
__copyright__ = "Copyright © 2021 Jerry Fedorenko aka VM"
__license__ = "MIT"
__version__ = "2.0.0"
__maintainer__ = "Jerry Fedorenko"
__contact__ = "https://github.com/DogsTailFarmer"
"""
##################################################################
Disclaimer
All risks and possible losses associated with use of this strategy lie with you.
Strongly recommended that you test the strategy in the demo mode before using real bidding.
##################################################################
Check and set parameter at the TOP part of script
Verify init message in Strategy output window for no error
"""
################################################################
import toml
# noinspection PyUnresolvedReferences
import sys
import martin_binance.executor as ex
from martin_binance.executor import * # lgtm [py/polluting-import]
################################################################
# Exchange setup and parameter settings
################################################################
# Set trading pair for Strategy
ex.SYMBOL = 'BTCUSDT'
# Exchange setup, see list of exchange in ms_cfg.toml
ex.ID_EXCHANGE = 3 # See ms_cfg.toml Use for collection of statistics *and get client connection*
ex.FEE_IN_PAIR = True # Fee pays in pair
ex.FEE_MAKER = Decimal('0.1') # standard exchange Fee for maker
ex.FEE_TAKER = Decimal('0.15') # standard exchange Fee for taker
ex.FEE_SECOND = False # On KRAKEN fee always in second coin
ex.FEE_BNB_IN_PAIR = False # Binance fee in BNB and BNB is base asset
ex.GRID_MAX_COUNT = 5 # Maximum counts for placed grid orders
# Trade parameter
ex.START_ON_BUY = True # First cycle direction
ex.AMOUNT_FIRST = Decimal('0') # Deposit for Sale cycle in first currency
ex.USE_ALL_FUND = False # Use all available fund for initial cycle or alltime for GRID_ONLY
ex.AMOUNT_SECOND = Decimal('1000.0') # Deposit for Buy cycle in second currency
ex.PRICE_SHIFT = 0.01 # 'No market' shift price in % from current bid/ask price
# Round pattern, set pattern 1.0123456789 or if not set used exchange settings
ex.ROUND_BASE = str()
ex.ROUND_QUOTE = str()
ex.PROFIT = Decimal('0.1') # 0.1 - 0.85
ex.PROFIT_MAX = Decimal('0.5') # If set it is maximum adapted cycle profit
ex.OVER_PRICE = Decimal('0.6') # Overlap price in one direction
ex.ORDER_Q = 11 # Target grid orders quantity in moment
ex.MARTIN = Decimal('10') # 5-20, % increments volume of orders in the grid
ex.SHIFT_GRID_DELAY = 1 # sec delay for shift grid action
# Other
ex.STATUS_DELAY = 60 # Minute between sending Tlg message about current status, 0 - disable
ex.GRID_ONLY = False # Only place grid orders for buy/sell asset
ex.LOG_LEVEL_NO_PRINT = [] # LogLevel.DEBUG Print for level over this list member
ex.COLLECT_ASSETS = False # Transfer free asset to main account, valid for subaccount only
# Parameter for calculate grid over price and grid orders quantity in set_trade_condition()
# If ADAPTIVE_TRADE_CONDITION = True, ORDER_Q / OVER_PRICE determines the density of grid orders
ex.ADAPTIVE_TRADE_CONDITION = True
ex.BB_CANDLE_SIZE_IN_MINUTES = 60
ex.BB_NUMBER_OF_CANDLES = 20
ex.KBB = 1.0 # k for Bollinger Band
# Parameter for calculate price of grid orders by logarithmic scale
# If -1 function is disabled, can take a value from 0 to infinity (in practice no more 1000)
# When 0 - logarithmic scale, increase parameter the result is approaching linear
ex.LINEAR_GRID_K = 0 # See 'Model of logarithmic grid.ods' for detail
# Average Directional Index with +DI and -DI for Reverse conditions analise
ex.ADX_CANDLE_SIZE_IN_MINUTES = 1
ex.ADX_NUMBER_OF_CANDLES = 60
ex.ADX_PERIOD = 14
ex.ADX_THRESHOLD = 40 # ADX value that indicates a strong trend
ex.ADX_PRICE_THRESHOLD = 0.05 # % Max price drift before release Hold reverse cycle
# Start first as Reverse cycle, also set appropriate AMOUNT
ex.REVERSE = False
ex.REVERSE_TARGET_AMOUNT = Decimal('0')
ex.REVERSE_INIT_AMOUNT = Decimal('0')
ex.REVERSE_STOP = False # Stop after ending reverse cycle
# Backtest mode parameters
ex.MODE = 'T' # 'T' - Trade, 'TC' - Trade and Collect, 'S' - Simulate
ex.SAVE_DS = True # Save session result data (ticker, orders) for compare
ex.SAVE_PERIOD = 24 * 60 * 60 # sec, timetable for save data portion, but memory limitation consider also matter
ex.SAVED_STATE = False # Use saved state for backtesting
################################################################
# DO NOT EDIT UNDER THIS LINE ###
################################################################
ex.PARAMS = Path(__file__).absolute()
config = toml.load(str(ex.CONFIG_FILE)) if ex.CONFIG_FILE.exists() else None
ex.HEAD_VERSION = __version__
ex.EXCHANGE = config.get('exchange')
ex.VPS_NAME = config.get('Exporter').get('vps_name')
# Telegram parameters
telegram = config.get('Telegram')
ex.TELEGRAM_URL = config.get('telegram_url')
for tlg in telegram:
if ex.ID_EXCHANGE in tlg.get('id_exchange'):
ex.TOKEN = tlg.get('token')
ex.CHANNEL_ID = tlg.get('channel_id')
ex.INLINE_BOT = tlg.get('inline')
break


def trade():
import logging.handlers
# For autoload last state
ex.LOAD_LAST_STATE = 1 if len(sys.argv) > 1 else 0
#
log_file = Path(ex.LOG_PATH, f"{ex.ID_EXCHANGE}_{ex.SYMBOL}.log")
ex.LAST_STATE_FILE = Path(ex.LAST_STATE_PATH, f"{ex.ID_EXCHANGE}_{ex.SYMBOL}.json")
#
_logger = logging.getLogger('logger')
_logger.setLevel(logging.DEBUG)
handler = logging.handlers.RotatingFileHandler(log_file, maxBytes=1000000, backupCount=10)
handler.setFormatter(logging.Formatter(fmt="[%(asctime)s: %(levelname)s] %(message)s"))
_logger.addHandler(handler)
_logger.propagate = False
#
try:
loop.create_task(main(ex.SYMBOL))
loop.run_forever()
except KeyboardInterrupt:
pass
finally:
try:
loop.run_until_complete(ask_exit())
except asyncio.CancelledError:
pass
except Exception as _err:
print(f"Error: {_err}")
loop.run_until_complete(loop.shutdown_asyncgens())
if ex.MODE in ('T', 'TC'):
loop.close()


if __name__ == "__main__":
trade()
2 changes: 1 addition & 1 deletion martin_binance/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
__author__ = "Jerry Fedorenko"
__copyright__ = "Copyright © 2021 Jerry Fedorenko aka VM"
__license__ = "MIT"
__version__ = "1.4.0.b2"
__version__ = "2.0.0rc1"
__maintainer__ = "Jerry Fedorenko"
__contact__ = "https://github.com/DogsTailFarmer"

Expand Down
Loading

0 comments on commit 1238d86

Please sign in to comment.