binance margin stop loss


SUBMITTED BY: Guest

DATE: April 19, 2020, 5:53 p.m.

FORMAT: Python 3

SIZE: 6.6 kB

HITS: 801

  1. #!/usr/bin/env python3
  2. '''
  3. @author: chmick
  4. @todo : FINISH DEBUGING
  5. ### basic trailing stop loss for binance margin trading
  6. ## you can use freely
  7. ## delivered with no support , use at your own risk
  8. ## it's a while true loop that check a market price and sell
  9. ## if it reaches a parameter limit. The limit can change if the trailing stop option
  10. ## is activated and price moves in the right direction
  11. ## thanks to Sam Chardy for the binance api (you need it , for this program to work )
  12. ## https://github.com/sammchardy/python-binance
  13. '''
  14. import sys
  15. import os
  16. from argparse import ArgumentParser
  17. from time import sleep
  18. import logging
  19. import configparser
  20. from logging.handlers import RotatingFileHandler
  21. from binance.enums import ORDER_TYPE_MARKET
  22. from binance.enums import SIDE_SELL, TIME_IN_FORCE_GTC, SIDE_BUY
  23. from binance.client import Client
  24. from urllib.request import urlopen
  25. def internet_on():
  26. try:
  27. response = urlopen('https://www.binance.com/en/', timeout=10)
  28. logger.debug("net response %r" % response)
  29. return True
  30. except:
  31. return False
  32. ##########################################
  33. ### put your api key and secret
  34. ###########################################
  35. binance_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
  36. binance_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
  37. ## if testMode = False
  38. ## the program just play a sound, print a message and exit when triggered
  39. testMode = False
  40. ## WARNING if testMode = False
  41. ## the program will execute
  42. #testMode = True
  43. #######################################
  44. ### Program
  45. ########################################"
  46. parser = ArgumentParser(description='binance margin stop loss')
  47. parser.add_argument("-l", "--loglevel", dest="loglevel", default='INFO', help="log level default is INFO",choices=['INFO','DEBUG', 'WARNING', 'ERROR'])
  48. parser.add_argument("-p", "--pair", dest="pair", default='BTCUSDT', help="pair to watch")
  49. group = parser.add_mutually_exclusive_group(required=True)
  50. group.add_argument("-L", "--Long", dest="trademode", action='store_const', const='LONG', help="stop loss for long position")
  51. group.add_argument("-S", "--Short", dest="trademode", action='store_const', const='SHORT', help="stop loss for short position ")
  52. parser.add_argument("-t", "--trigger", dest="trigger", required=True, help="trigger limit", type=float)
  53. parser.add_argument("-T", "--trailing", dest="trailing", action='store_true', help="enable trailing stop")
  54. list_args = parser.parse_args()
  55. config = configparser.ConfigParser()
  56. program_name = os.path.basename(sys.argv[0])
  57. pair = list_args.pair
  58. formatter = logging.Formatter(fmt='%(asctime)s.%(msecs)03d %(levelname)s #%(threadName)-9s# %(message)s', datefmt='%m-%d %H:%M:%S')
  59. logger = logging.getLogger('BinanceStopLoss' + pair + str(os.getpid()))
  60. logger.setLevel(list_args.loglevel)
  61. logger.critical('loglevel set to : %s' % logger.level)
  62. filelogdebug = RotatingFileHandler(filename=os.path.dirname(os.path.abspath(__file__))+'/log/'+__file__ + pair + '.debug.log', mode='a', maxBytes=40960000, backupCount=10)
  63. filelogwarn = RotatingFileHandler(filename=os.path.dirname(os.path.abspath(__file__))+'/log/'+__file__ + pair + '.warn.log', mode='a', maxBytes=40960000, backupCount=10)
  64. filelogdebug.setLevel(logging.DEBUG)
  65. filelogdebug.setFormatter(formatter)
  66. filelogwarn.setLevel(logging.WARNING)
  67. filelogwarn.setFormatter(formatter)
  68. logger.addHandler(filelogdebug)
  69. logger.addHandler(filelogwarn)
  70. bclient = Client(api_key=binance_key, api_secret=binance_secret )
  71. ## VARIABLES
  72. symbolData = bclient.get_symbol_info(symbol=list_args.pair)
  73. # baseAsset est le coin que l on trade exemple BNB dans BNBUSDT
  74. baseAsset = symbolData['baseAsset']
  75. #quoteAsset est contre quoi on trade exemple USDT dans BNBUSDT
  76. quoteAsset = symbolData['quoteAsset']
  77. tempDict = next(item for item in symbolData['filters'] if item["filterType"] == 'PRICE_FILTER')
  78. filterPricePrecision = int(symbolData['baseAssetPrecision'])
  79. filterTicksize = float(tempDict['tickSize'])
  80. tempDict = next(item for item in symbolData['filters'] if item["filterType"] == 'LOT_SIZE')
  81. filterMinSize = float(tempDict['minQty'])
  82. filterLotStepSize = float(tempDict['stepSize'])
  83. filterVolumePrecision = int(symbolData['quotePrecision'])
  84. price = 0
  85. previousPrice = 0
  86. trigger = list_args.trigger
  87. ### MAIN LOOP
  88. while True :
  89. sleep(10)
  90. previousPrice = price
  91. info = bclient.get_margin_account()
  92. ## we keep a dictionnary containing a list of what we borrowed
  93. borrowedDict = dict()
  94. for c in info['userAssets']:
  95. if 0 != float(c['borrowed']): borrowedDict[c['asset']] = c
  96. ticker = bclient.get_orderbook_ticker(symbol=list_args.pair)
  97. print('mode %s , limit %f , last ticker %r'%(list_args.trademode,trigger,ticker))
  98. ## in short mode , we compare trigger and sell price
  99. ## if triggered , the program th net borrowed
  100. if list_args.trademode == 'SHORT' :
  101. price = float(ticker['askPrice'])
  102. ## trailing management
  103. if price < previousPrice and list_args.trailing == True and previousPrice != 0:
  104. trigger = trigger - (previousPrice-price)
  105. if price >= trigger :
  106. v == 0
  107. temp = borrowedDict.get(baseAsset, None)
  108. if temp :
  109. v = float(temp['netAsset'] )
  110. print('!!!! trigger value reached in short mode, rebuying %f'%v)
  111. print("\a")
  112. if not testMode :
  113. myLimitOrder = bclient.create_margin_order(symbol=list_args.pair,quantity=v, side=SIDE_BUY, type=ORDER_TYPE_MARKET, timeInForce=TIME_IN_FORCE_GTC)
  114. exit(0)
  115. ## in LONG mode , we compare trigger and buy price
  116. if list_args.trademode == 'LONG':
  117. price = float(ticker['bidPrice'])
  118. ## trailing management
  119. if price > previousPrice and list_args.trailing == True and previousPrice != 0:
  120. trigger = trigger + (price - previousPrice)
  121. if price <= trigger :
  122. ## in long mode we sell everything
  123. temp = bclient.get_margin_account()['userAssets']
  124. for a in temp :
  125. if a['asset'] == baseAsset :
  126. v = float(a['free'])
  127. print('trigger value reached in long mode, selling %f'%v)
  128. print("\a")
  129. if not testMode:
  130. myLimitOrder = bclient.create_margin_order(symbol=list_args.pair, quantity=v, side=SIDE_SELL, type=ORDER_TYPE_MARKET, timeInForce=TIME_IN_FORCE_GTC)
  131. exit(0)

comments powered by Disqus