[
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2021 John P Lennie\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# Simple Binance Trader\n\n# Disclaimer\nI am not responsible for the trades you make with the script, this script has not been exstensivly tested on live trades.\n\n## Please check the following:\n- Make sure your account uses BNB for the trade fees and that you have plenty of BNB for the trader to use for trades as if not there will be issues with the trader.\n- Please clear any cache files when updating the trader as there may be issues if not.\n- Please if any updates are also available for binance_api or the technical indicators update those also.\n\n\nNOTE: The current strtergy is also very weak and will mostlikley return only losses therefore I recomend you create your work or use some which would work. However the trader currently also does not support simulated trades and only support live trading, simulated trades should be added in the future so you may need to wait until then to use this to test stratergies.\n\nNOTE: Trader now supports MARGIN trades allowing the placement of short and long positions. If SPOT trading put your conditions within the \"long_entry/long_exit\" sections within the trader_configuration.py file.\n\n\n## Description\nThis is a simple binance trader that uses the REST api and sockets to allow automation or manipulation of account detail/data. The script which in the default configuration uses a basic MACD trading setup to trade. The script however is very customisable and you'll be able to configure it as you with via the help of the document in the usage section.\n\n### Repository Contains:\n- run.py : This is used to start/setup the bot.\n- trader_configuration.py : Here is where you write your conditions using python logic.\n- patterns.py : Can be used to trade based on specific patterns.\n- Core\n  - botCore.py : Is used to manage the socket and trader as well as pull data to be displayed.\n  - trader.py : The main trader inchage or updating and watching orders.\n  - static : Folder for static files for the website (js/css).\n  - templates : Folder for HTML page templates.\n  \n### Setting File:\n- PUBLIC_KEY -  Your public binanace api key\n- PRIVATE_KEY - Your private binanace api key\n- IS_TEST - Allow trader to be run in test mode (True/False)\n- MARKET_TYPE - Market type to be traded (SPOT/MARGIN)\n- UPDATE_BNB_BALANCE - Automatically update the BNB balance when low (for trading fees, only applicable to real trading)\n- TRADER_INTERVAL - Interval used for the trader (1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d).\n- TRADING_CURRENCY - The currency max the trader will use (in the quote key) also note this scales up with the number of markets i.e. 2 pairs each market will have 0.0015 as their trading currency pair.\n- TRADING_MARKETS - The markets that are being traded and seperate with ',' (BTC-ETH,BTC-NEO)\n- HOST_IP - The host IP for the web UI (if left blank default is 127.0.0.1)\n- HOST_PORT - The host port for the web UI (if left blank default is 5000)\n- MAX_CANDLES - Max candles the trader will use (if left brank default is 500)\n- MAX_DEPTH - Max market depth the trader will use (if left brank default is 50)\n\n## Usage\nI recommend setting this all up within a virtual python enviornment:\nFirst get the base modules:\n - To quickly install all the required modules use 'pip3 install -r requirements'.\n\nSecondly get the required techinal indicators module adn binance api.\n - https://github.com/EasyAI/binance_api, This is the binance API that the trader uses.\n - https://github.com/EasyAI/Python-Charting-Indicators, This contains the logic to calculate technical indicators. (only the file technical_indicators.py is needed)\n\nMove them into the site-packages folder. NOTE: If you get an error saying that either the technical_indicators or binance_api is not found you can move them in to the same directory as the run.py file for the trader.\n\nFinally navigate to the trader directory.\n\nTo set up the bot and for any further detail please refer to the google doc link below:\nhttps://docs.google.com/document/d/1VUx_1O5kQQxk0HfqqA8WyQpk6EbbnXcezAdqXkOMklo/edit?usp=sharing\n\n### Contact\nPlease if you find any bugs or issues contact me so I can improve.\nEMAIL: jlennie1996@gmail.com\n"
  },
  {
    "path": "core/botCore.py",
    "content": "#! /usr/bin/env python3\nimport os\nimport sys\nimport time\nimport json\nimport os.path\nimport hashlib\nimport logging\nimport threading\nfrom decimal import Decimal\nfrom flask_socketio import SocketIO\nfrom flask import Flask, render_template, url_for, request\n\nfrom binance_api import api_master_rest_caller\nfrom binance_api import api_master_socket_caller\n\nfrom . import trader\n\n\nMULTI_DEPTH_INDICATORS = ['ema', 'sma', 'rma', 'order']\n\n# Initilize globals.\n\n## Setup flask app/socket\nAPP         = Flask(__name__)\nSOCKET_IO   = SocketIO(APP)\n\n## Initilize base core object.\ncore_object = None\n\nstarted_updater = False\n\n## Initilize IP/port pair globals.\nhost_ip     = ''\nhost_port   = ''\n\n## Set traders cache file name.\nCAHCE_FILES = 'traders.json'\n\n\n@APP.context_processor\ndef override_url_for():\n    return(dict(url_for=dated_url_for))\n\n\ndef dated_url_for(endpoint, **values):\n    # Override to prevent cached assets being used.\n    if endpoint == 'static':\n        filename = values.get('filename', None)\n        if filename:\n            file_path = os.path.join(APP.root_path,\n                                    endpoint,\n                                    filename)\n            values['q'] = int(os.stat(file_path).st_mtime)\n    return url_for(endpoint, **values)\n\n\n@APP.route('/', methods=['GET'])\ndef control_panel():\n    # Base control panel configuration.\n    global started_updater \n\n    ## Web updater used for live updating.\n    if not(started_updater):\n        started_updater = True\n        web_updater_thread = threading.Thread(target=web_updater)\n        web_updater_thread.start()\n\n    ## Set socket ip/port.\n    start_up_data = {\n        'host':{'IP': host_ip, 'Port': host_port},\n        'market_symbols': core_object.trading_markets\n    }\n\n    return(render_template('main_page.html', data=start_up_data))\n\n\n@APP.route('/rest-api/v1/trader_update', methods=['POST'])\ndef update_trader():\n    # Base API for managing trader interaction.\n    data = request.get_json()\n\n    ## Check if specified bot exists.\n    current_trader = api_error_check(data)\n\n    if current_trader == None:\n        ## No trader therefore return false.\n        return(json.dumps({'call':False, 'message':'INVALID_TRADER'}))\n    elif data['action'] == 'start':\n        ## Updating trader status to running.\n        if current_trader.state_data['runtime_state'] == 'FORCE_PAUSE':\n            current_trader.state_data['runtime_state'] = 'RUN'\n    elif data['action'] == 'pause':\n        ## Updating trader status to paused.\n        if current_trader.state_data['runtime_state'] == 'RUN':\n            current_trader.state_data['runtime_state'] = 'FORCE_PAUSE'\n    else:\n        ## If action was not found return false\n        return(json.dumps({'call':False, 'message':'INVALID_ACTION'}))\n\n    return(json.dumps({'call':True}))\n\n\n@APP.route('/rest-api/v1/get_trader_charting', methods=['GET'])\ndef get_trader_charting():\n    # Endpoint to pass trader indicator data.\n    market = request.args.get('market')\n    limit = int(request.args.get('limit'))\n    data = {'market':market}\n\n    ## Check if specified bot exists.\n    current_trader = api_error_check(data)\n\n    if current_trader == None:\n        ## No trader therefore return false.\n        return(json.dumps({'call':False, 'message':'INVALID_TRADER'}))\n\n    candle_data = core_object.get_trader_candles(current_trader.print_pair)[:limit]\n    indicator_data = core_object.get_trader_indicators(current_trader.print_pair)\n    short_indicator_data = shorten_indicators(indicator_data, candle_data[-1][0])\n\n    return(json.dumps({'call':True, 'data':{'market':market, 'indicators':short_indicator_data, 'candles':candle_data}}))\n\n\n@APP.route('/rest-api/v1/get_trader_indicators', methods=['GET'])\ndef get_trader_indicators():\n    # Endpoint to pass trader indicator data.\n    market = request.args.get('market')\n    limit = int(request.args.get('limit'))\n    data = {'market':market}\n\n    ## Check if specified bot exists.\n    current_trader = api_error_check(data)\n\n    if current_trader == None:\n        ## No trader therefore return false.\n        return(json.dumps({'call':False, 'message':'INVALID_TRADER'}))\n\n    indicator_data = core_object.get_trader_indicators(current_trader.print_pair)\n\n    return(json.dumps({'call':True, 'data':{'market':market, 'indicators':indicator_data}}))\n\n\n@APP.route('/rest-api/v1/get_trader_candles', methods=['GET'])\ndef get_trader_candles():\n    # Endpoint to pass trader candles.\n    market = request.args.get('market')\n    limit = int(request.args.get('limit'))\n    data = {'market':market}\n\n    ## Check if specified bot exists.\n    current_trader = api_error_check(data)\n\n    if current_trader == None:\n        ## No trader therefore return false.\n        return(json.dumps({'call':False, 'message':'INVALID_TRADER'}))\n\n    candle_data = core_object.get_trader_candles(current_trader.print_pair)[:limit]\n\n    return(json.dumps({'call':True, 'data':{'market':market, 'candles':candle_data}}))\n\n\n@APP.route('/rest-api/v1/test', methods=['GET'])\ndef test_rest_call():\n    # API endpoint test\n    return(json.dumps({'call':True, 'message':'HELLO WORLD!'}))\n\n\ndef shorten_indicators(indicators, end_time):\n    base_indicators = {}\n\n    for ind in indicators:\n        if ind in MULTI_DEPTH_INDICATORS:\n            base_indicators.update({ind:{}})\n            for sub_ind in indicators[ind]:\n                base_indicators[ind].update({sub_ind:[ [val[0] if ind != 'order' else val[0]*1000,val[1]] for val in indicators[ind][sub_ind] if (val[0] if ind != 'order' else val[0]*1000) > end_time ]})\n        else:\n            base_indicators.update({ind:[ [val[0],val[1]] for val in indicators[ind] if val[0] > end_time]})\n\n    return(base_indicators)\n\n\ndef api_error_check(data):\n    ## Check if specified bot exists.\n    current_trader = None\n    for trader in core_object.trader_objects:\n        if trader.print_pair == data['market']:\n            current_trader = trader\n            break\n    return(current_trader)\n\n\ndef web_updater():\n    # Web updater use to update live via socket.\n    lastHash = None\n\n    while True:\n        if core_object.coreState == 'RUN':\n            ## Get trader data and hash it to find out if there have been any changes.\n            traderData = core_object.get_trader_data()\n            currHash = hashlib.md5(str(traderData).encode())\n\n            if lastHash != currHash:\n                ## Update any new changes via socket.\n                lastHash = currHash\n                total_bulk_data = []\n                for trader in traderData:\n                    bulk_data = {}\n                    bulk_data.update({'market':trader['market']})\n                    bulk_data.update({'trade_recorder':trader['trade_recorder']})\n                    bulk_data.update({'wallet_pair':trader['wallet_pair']})\n\n                    bulk_data.update(trader['custom_conditions'])\n                    bulk_data.update(trader['market_activity'])\n                    bulk_data.update(trader['market_prices'])\n                    bulk_data.update(trader['state_data'])\n                    total_bulk_data.append(bulk_data)\n\n                SOCKET_IO.emit('current_traders_data', {'data':total_bulk_data})\n                time.sleep(.8)\n\n\nclass BotCore():\n\n    def __init__(self, settings, logs_dir, cache_dir):\n        # Initilization for the bot core managment object.\n        logging.info('[BotCore] Initilizing the BotCore object.')\n\n        ## Setup binance REST and socket API.\n        self.rest_api           = api_master_rest_caller.Binance_REST(settings['public_key'], settings['private_key'])\n        self.socket_api         = api_master_socket_caller.Binance_SOCK()\n\n        ## Setup the logs/cache dir locations.\n        self.logs_dir           = logs_dir\n        self.cache_dir          = cache_dir\n\n        ## Setup run type, market type, and update bnb balance.\n        self.run_type           = settings['run_type']\n        self.market_type        = settings['market_type']\n        self.update_bnb_balance = settings['update_bnb_balance']\n\n        ## Setup max candle/depth setting.\n        self.max_candles        = settings['max_candles']\n        self.max_depth          = settings['max_depth']\n\n        ## Get base quote pair (This prevents multiple different pairs from conflicting.)\n        pair_one = settings['trading_markets'][0]\n\n        self.quote_asset        = pair_one[:pair_one.index('-')]\n        self.base_currency      = settings['trading_currency']\n        self.candle_Interval    = settings['trader_interval']\n\n        ## Initilize base trader settings.\n        self.trader_objects     = []\n        self.trading_markets    = settings['trading_markets']\n\n        ## Initilize core state\n        self.coreState          = 'READY'\n\n\n    def start(self):\n        # Start the core object.\n        logging.info('[BotCore] Starting the BotCore object.')\n        self.coreState = 'SETUP'\n\n        ## check markets\n        found_markets = []\n        not_supported = []\n\n        for market in self.rest_api.get_exchangeInfo()['symbols']:\n            fmtMarket = '{0}-{1}'.format(market['quoteAsset'], market['baseAsset'])\n\n            # If the current market is not in the trading markets list then skip.\n            if not fmtMarket in self.trading_markets:\n                continue\n\n            found_markets.append(fmtMarket)\n\n            if (self.market_type == 'MARGIN' and market['isMarginTradingAllowed'] == False) or (self.market_type == 'SPOT' and market['isSpotTradingAllowed'] == False):\n                not_supported.append(fmtMarket)\n                continue\n\n            # This is used to setup min quantity.\n            if float(market['filters'][2]['minQty']) < 1.0:\n                minQuantBase = (Decimal(market['filters'][2]['minQty'])).as_tuple()\n                lS = abs(int(len(minQuantBase.digits)+minQuantBase.exponent))+1\n            else: lS = 0\n\n            # This is used to set up the price precision for the market.\n            tickSizeBase = (Decimal(market['filters'][0]['tickSize'])).as_tuple()\n            tS = abs(int(len(tickSizeBase.digits)+tickSizeBase.exponent))+1\n\n            # This is used to get the markets minimal notation.\n            mN = float(market['filters'][3]['minNotional'])\n\n            # Put all rules into a json object to pass to the trader.\n            market_rules = {'LOT_SIZE':lS, 'TICK_SIZE':tS, 'MINIMUM_NOTATION':mN}\n\n            # Initilize trader objecta dn also set-up its inital required data.\n            traderObject = trader.BaseTrader(market['quoteAsset'], market['baseAsset'], self.rest_api, socket_api=self.socket_api)\n            traderObject.setup_initial_values(self.market_type, self.run_type, market_rules)\n            self.trader_objects.append(traderObject)\n\n        \n        ## Show markets that dont exist on the binance exchange.\n        if len(self.trading_markets) != len(found_markets):\n            no_market_text = ''\n            for market in [market for market in self.trading_markets if market not in found_markets]:\n                no_market_text+=str(market)+', '\n            logging.warning('Following pairs dont exist: {}'.format(no_market_text[:-2]))\n\n        ## Show markets that dont support the market type.\n        if len(not_supported) > 0:\n            not_support_text = ''\n            for market in not_supported:\n                not_support_text += ' '+str(market)\n            logging.warning('[BotCore] Following market pairs are not supported for {}: {}'.format(self.market_type, not_support_text))\n\n        valid_tading_markets = [market for market in found_markets if market not in not_supported]\n\n        ## setup the binance socket.\n        for market in valid_tading_markets:\n            self.socket_api.set_candle_stream(symbol=market, interval=self.candle_Interval)\n            self.socket_api.set_manual_depth_stream(symbol=market, update_speed='1000ms')\n\n        if self.run_type == 'REAL':\n            self.socket_api.set_userDataStream(self.rest_api, self.market_type)\n\n        self.socket_api.BASE_CANDLE_LIMIT = self.max_candles\n        self.socket_api.BASE_DEPTH_LIMIT = self.max_depth\n\n        self.socket_api.build_query()\n        self.socket_api.set_live_and_historic_combo(self.rest_api)\n\n        self.socket_api.start()\n\n        # Load the wallets.\n        if self.run_type == 'REAL':\n            user_info = self.rest_api.get_account(self.market_type)\n            if self.market_type == 'SPOT':\n                wallet_balances = user_info['balances']\n            elif self.market_type == 'MARGIN':\n                wallet_balances = user_info['userAssets']\n            current_tokens = {}\n            \n            for balance in wallet_balances:\n                total_balance = (float(balance['free']) + float(balance['locked']))\n                if total_balance > 0:\n                    current_tokens.update({balance['asset']:[\n                                        float(balance['free']),\n                                        float(balance['locked'])]})\n        else:\n            current_tokens = {self.quote_asset:[float(self.base_currency), 0.0]}\n\n        # Load cached data\n        cached_traders_data = None\n        if os.path.exists(self.cache_dir+CAHCE_FILES):\n            with open(self.cache_dir+CAHCE_FILES, 'r') as f:\n                cached_traders_data = json.load(f)['data']\n\n        ## Setup the trader objects and start them.\n        logging.info('[BotCore] Starting the trader objects.')\n        for trader_ in self.trader_objects:\n            currSymbol = \"{0}{1}\".format(trader_.base_asset, trader_.quote_asset)\n\n            # Update trader with cached data (to resume trades/keep records of trades.)\n            if cached_traders_data != '' and cached_traders_data:\n                for cached_trader in cached_traders_data:\n                    m_split = cached_trader['market'].split('-')\n                    if (m_split[1]+m_split[0]) == currSymbol:\n                        trader_.configuration           = cached_trader['configuration']\n                        trader_.custom_conditional_data = cached_trader['custom_conditions']\n                        trader_.market_activity         = cached_trader['market_activity']\n                        trader_.trade_recorder          = cached_trader['trade_recorder']\n                        trader_.state_data              = cached_trader['state_data']\n\n            wallet_pair = {}\n\n            if trader_.quote_asset in current_tokens:\n                wallet_pair.update({trader_.quote_asset:current_tokens[trader_.quote_asset]})\n\n            if trader_.base_asset in current_tokens:\n                wallet_pair.update({trader_.base_asset:current_tokens[trader_.base_asset]})\n\n            trader_.start(self.base_currency, wallet_pair)\n\n        logging.debug('[BotCore] Starting trader manager')\n        TM_thread = threading.Thread(target=self._trader_manager)\n        TM_thread.start()\n\n        if self.update_bnb_balance:\n            logging.debug('[BotCore] Starting BNB manager')\n            BNB_thread = threading.Thread(target=self._bnb_manager)\n            BNB_thread.start()\n\n        logging.debug('[BotCore] Starting connection manager thread.')\n        CM_thread = threading.Thread(target=self._connection_manager)\n        CM_thread.start()\n\n        logging.debug('[BotCore] Starting file manager thread.')\n        FM_thread = threading.Thread(target=self._file_manager)\n        FM_thread.start()\n\n        logging.info('[BotCore] BotCore successfully started.')\n        self.coreState = 'RUN'\n\n\n    def _trader_manager(self):\n        ''' '''\n        while self.coreState != 'STOP':\n            pass\n\n\n    def _bnb_manager(self):\n        ''' This will manage BNB balance and update if there is low BNB in account. '''\n        last_wallet_update_time = 0\n\n        while self.coreState != 'STOP':\n            socket_buffer_global = self.socket_api.socketBuffer\n\n            # If outbound postion is seen then wallet has updated.\n            if 'outboundAccountPosition' in socket_buffer_global:\n                if last_wallet_update_time != socket_buffer_global['outboundAccountPosition']['E']:\n                    last_wallet_update_time = socket_buffer_global['outboundAccountPosition']['E']\n\n                    for wallet in socket_buffer_global['outboundAccountPosition']['B']:\n                        if wallet['a'] == 'BNB':\n                            if float(wallet['f']) < 0.01:\n                                bnb_order = self.rest_api.place_order(self.market_type, symbol='BNBBTC', side='BUY', type='MARKET', quantity=0.1)\n            time.sleep(2)\n\n\n    def _file_manager(self):\n        ''' This section is responsible for activly updating the traders cache files. '''\n        while self.coreState != 'STOP':\n            time.sleep(15)\n\n            traders_data = self.get_trader_data()\n            if os.path.exists(self.cache_dir):\n                file_path = '{0}{1}'.format(self.cache_dir,CAHCE_FILES)\n                with open(file_path, 'w') as f:\n                    json.dump({'lastUpdateTime':time.time() ,'data':traders_data}, f)\n\n\n    def _connection_manager(self):\n        ''' This section is responsible for re-testing connectiongs in the event of a disconnect. '''\n        update_time = 0\n        retryCounter = 1\n        time.sleep(20)\n\n        while self.coreState != 'STOP':\n            time.sleep(1)\n            if self.coreState != 'RUN':\n                continue\n            if self.socket_api.last_data_recv_time != update_time:\n                update_time = self.socket_api.last_data_recv_time\n            else:\n                if (update_time + (15*retryCounter)) < time.time():\n                    retryCounter += 1\n                    \n                    try:\n                        print(self.rest_api.test_ping())\n                    except Exception as e:\n                        logging.warning('[BotCore] Connection issue: {0}.'.format(e))\n                        continue\n\n                    logging.info('[BotCore] Connection issue resolved.')\n                    if not(self.socket_api.socketRunning):\n                        logging.info('[BotCore] Attempting socket restart.')\n                        self.socket_api.start()\n\n\n    def get_trader_data(self):\n        ''' This can be called to return data for each of the active traders. '''\n        rData = [ _trader.get_trader_data() for _trader in self.trader_objects ]\n        return(rData)\n\n\n    def get_trader_indicators(self, market):\n        ''' This can be called to return the indicators that are used by the traders (Will be used to display web UI activity.) '''\n        for _trader in self.trader_objects:\n            if _trader.print_pair == market:\n                indicator_data = _trader.indicators\n                indicator_data.update({'order':{'buy':[], 'sell':[]}})\n                indicator_data['order']['buy'] = [ [order[0],order[1]] for order in _trader.trade_recorder if order[4] == 'BUY']\n                indicator_data['order']['sell'] = [ [order[0],order[1]] for order in _trader.trade_recorder if order[4] == 'SELL']\n                return(indicator_data)\n\n\n    def get_trader_candles(self, market):\n        ''' This can be called to return the candle data for the traders (Will be used to display web UI activity.) '''\n        for _trader in self.trader_objects:\n            if _trader.print_pair == market:\n                sock_symbol = str(_trader.base_asset)+str(_trader.quote_asset)\n                return(self.socket_api.get_live_candles(sock_symbol))\n\n\ndef start(settings, logs_dir, cache_dir):\n    global core_object, host_ip, host_port\n\n    if core_object == None:\n        core_object = BotCore(settings, logs_dir, cache_dir)\n        core_object.start()\n\n    logging.info('[BotCore] Starting traders in {0} mode, market type is {1}.'.format(settings['run_type'], settings['market_type']))\n    log = logging.getLogger('werkzeug')\n    log.setLevel(logging.ERROR)\n\n    host_ip = settings['host_ip']\n    host_port = settings['host_port']\n\n    SOCKET_IO.run(APP, \n        host=settings['host_ip'], \n        port=settings['host_port'], \n        debug=True, \n        use_reloader=False)\n"
  },
  {
    "path": "core/static/css/style.css",
    "content": "@import url('https://fonts.googleapis.com/css?family=Josefin+Sans&display=swap');\n\n*{\n  margin: 0;\n  padding: 0;\n  box-sizing: border-box;\n  list-style: none;\n  text-decoration: none;\n  font-family: arial;\n}\n\nbody{\n   \tbackground-color: #f3f5f9;\n\tdisplay: flex;\n  \tposition: relative;\n}\n\n.sidebar{\n  width: 200px;\n  height: 100%;\n  background: #4b4276;\n  padding: 30px 0px;\n  position: fixed;\n  color: #bdb8d7;\n}\n\n.sidebar ul li{\n  padding: 15px;\n}    \n\n.sidebar ul li a{\n  display: block;\n  color: #bdb8d7;\n}\n\n.sidebar ul li:hover{\n  background-color: #594f8d;\n}\n    \n.sidebar ul li:hover a{\n  color: #fff;\n}\n\nmain {\n\twidth: 100%;\n\tmargin-left: 200px;\n\tbackground-color: #F5F5F0;\n\tpadding-left: 20px;\n\tpadding-top: 10px;\n}\n\n.trader-panel {\n\tdisplay: none;\n}\n\n.small-button {\n\tpadding: 5px;\n\tfont-size: 12px;\n\tdisplay: block;\n\tdisplay: inline-block;\n\tborder: none;\n\tborder-radius: 4px;\n\tcursor: pointer;\n\tcolor: white;\n}\n\n.green-button {\n\tbackground-color: #00802b;\n}\n\n.green-button:hover {\n\tbackground-color: #33ff77;\n}\n\n.amber-button {\n\tbackground-color: #e68a00\n}\n\n.amber-button:hover {\n\tbackground-color: #ffa31a;\n}"
  },
  {
    "path": "core/static/js/charts.js",
    "content": "// Indicator meta details\nconst indicator_chart_types_mapping = {'patterns_data_lines':'line', 'patterns_data_points':'scatter', 'tops_bottoms':'scatter', 'data_lines':'line', 'cps':'line', 'ichi':'line', 'boll':'line', 'adx':'line', 'stock':'line', 'order':'scatter', 'ema':'line', 'sma':'line', 'rma':'line', 'rsi':'line', 'mfi':'line', 'cci':'line', 'zerolagmacd':'macd', 'macd':'macd'}\nconst indicator_home_type_mapping = {'patterns_data_lines':'MAIN', 'patterns_data_points':'MAIN', 'tops_bottoms':'MAIN', 'data_lines':'MAIN', 'ichi':'MAIN', 'cps':'MAIN', 'boll':'MAIN', 'adx':'OWN', 'stock':'OWN', 'order':'MAIN', 'ema':'MAIN', 'sma':'MAIN', 'rma':'MAIN', 'rsi':'OWN', 'mfi':'OWN', 'cci':'OWN', 'zerolagmacd':'OWN', 'macd':'OWN'}\nconst indicator_is_single_mapping = ['patterns_data_lines', 'patterns_data_points', 'tops_bottoms', 'data_lines', 'order', 'ema', 'sma', 'rma', 'rsi', 'mfi', 'cci', 'cps']\nconst double_depth_indicators = ['ema', 'sma', 'order', 'patterns_data_points', 'patterns_data_lines'];\n\n// Base Apex chart configuration.\nwindow.Apex = {\n    chart: {\n        animations: {\n            enabled: false\n        }\n    },\n    autoScaleYaxis: false\n};\n\n// Chart template for main chart.\nvar base_candle_chart_configuration = {\n    series: [],\n    chart: {\n        height: 800,\n        id: 'main_Chart',\n        type: 'line'\n    },\n    fill: {\n        type:'solid',\n    },\n    markers: {\n        size: []\n    },\n    //colors: [],\n    stroke: {\n        width: []\n    },\n    tooltip: {\n        shared: true,\n        custom: []\n    },\n    xaxis: {\n        type: 'datetime',\n    },\n    yaxis: {\n        labels: {\n            minWidth: 40,\n            formatter: function (value) { return Math.round(value); }\n        },\n    }\n};\n\nlet loaded_candles_chart = null;\n\n\nfunction initial_build(target_element, charting_data) {\n    // Add main chandle chart position.\n    var candle_data = charting_data['candles'];\n    var indicator_data = charting_data['indicators'];\n    var main_chart_series = [];\n\n    loaded_candles_chart = JSON.parse(JSON.stringify(base_candle_chart_configuration));\n\n    populate_chart(indicator_data);\n\n    var built_data = build_candle_data(candle_data);\n    var built_candle_data = built_data[0];\n\n    // Finally add the candle to the displayed chart.\n    loaded_candles_chart[\"series\"].push({\n        name: 'candle',\n        type: 'candlestick',\n        data: built_candle_data\n    });\n    loaded_candles_chart[\"stroke\"][\"width\"].push(1);\n    loaded_candles_chart[\"markers\"][\"size\"].push(0);\n    loaded_candles_chart[\"tooltip\"][\"custom\"].push(function({seriesIndex, dataPointIndex, w}) {\n        var o = w.globals.seriesCandleO[seriesIndex][dataPointIndex]\n        var h = w.globals.seriesCandleH[seriesIndex][dataPointIndex]\n        var l = w.globals.seriesCandleL[seriesIndex][dataPointIndex]\n        var c = w.globals.seriesCandleC[seriesIndex][dataPointIndex]\n        return (`Open:${o}<br>High:${h}<br>Low:${l}<br>Close:${c}`)\n    });\n\n    candle_chart = new ApexCharts(target_element, loaded_candles_chart);\n    candle_chart.render();\n}\n\n\nfunction build_candle_data(candle_data) {\n    var built_candle_data = [];\n    var built_volume_data = [];\n\n    for (var i=0; i < candle_data.length; i++) {\n        var candle = candle_data[i];\n        built_candle_data.push({\n            x: new Date(parseInt(candle[0])),\n            y: [\n                candle[1],\n                candle[2],\n                candle[3],\n                candle[4]\n            ]\n        });\n\n        built_volume_data.push({\n            x: new Date(parseInt(candle[0])),\n            y: Math.round(candle[5])\n        });\n    }\n    return([built_candle_data, built_volume_data]);\n}\n\n\nfunction build_timeseries(ind_obj) {\n    var indicator_lines = [];\n    var keys = []\n\n    // Use sorted timestamp to print out.\n    for (var ind in ind_obj) {\n        var current_set = ind_obj[ind]\n\n        if (typeof current_set[0] == 'number') {\n            indicator_lines.push({\n                x: new Date(parseInt(current_set[0])),\n                y: current_set[1].toFixed(8)\n            });\n        } else {\n            for (var sub_ind in current_set) {\n                if (!keys.includes(sub_ind)) {\n                    keys.push(sub_ind)\n                    indicator_lines[sub_ind] = []\n                }\n                indicator_lines[sub_ind].push({\n                    x: new Date(parseInt(current_set[sub_ind][0])),\n                    y: current_set[sub_ind][1].toFixed(8)\n                });\n            }\n        }\n    }\n    return(indicator_lines);\n}\n\n\nfunction build_basic_indicator(chart_obj, ind_obj, chart_type, line_name=null, ind_name=null) {\n    var indicator_lines = build_timeseries(ind_obj);\n\n    if (!(line_name == null)) {\n        chart_obj[\"series\"].push({\n            name: line_name,\n            type: chart_type,\n            data: indicator_lines\n        });\n        if (chart_type == \"scatter\") {\n            chart_obj[\"stroke\"][\"width\"].push(2);\n            chart_obj[\"markers\"][\"size\"].push(8);\n        } else {\n            chart_obj[\"stroke\"][\"width\"].push(2);\n            chart_obj[\"markers\"][\"size\"].push(0);\n        }\n    } else {\n        for (var sub_ind_name in indicator_lines) {\n            chart_obj[\"series\"].push({\n                name: sub_ind_name,\n                type: chart_type,\n                data: indicator_lines[sub_ind_name]});\n            if (chart_type == \"scatter\") {\n                chart_obj[\"stroke\"][\"width\"].push(2);\n                chart_obj[\"markers\"][\"size\"].push(8);\n            } else {\n                chart_obj[\"stroke\"][\"width\"].push(2);\n                chart_obj[\"markers\"][\"size\"].push(0);\n            }\n        }\n    }\n\n    if ('custom' in chart_obj[\"tooltip\"]) {\n        if (!(line_name == null)) {\n            chart_obj[\"tooltip\"][\"custom\"].push(\n                function({seriesIndex, dataPointIndex, w}) {\n                    return w.globals.series[seriesIndex][dataPointIndex]\n            });\n        } else {\n            for (var ind in indicator_lines) {\n                chart_obj[\"tooltip\"][\"custom\"].push(\n                    function({seriesIndex, dataPointIndex, w}) {\n                        return w.globals.series[seriesIndex][dataPointIndex]\n                });\n            }\n        }\n    }\n}\n\n\nfunction populate_chart(indicator_data) {\n\n    for (var raw_indicator in indicator_data) {\n\n        var patt = /[^\\d]+/i;\n        var indicator = raw_indicator.match(patt)[0];\n\n        var current_ind = indicator_data[raw_indicator];\n        var chart_type = indicator_chart_types_mapping[indicator];\n        var home_chart = indicator_home_type_mapping[indicator];\n        var line_name = null;\n        var ind_name = null;\n\n        if (home_chart == \"MAIN\") {\n            target_chart = loaded_candles_chart;\n\n            if (double_depth_indicators.includes(indicator)) {\n                for (var sub_ind in current_ind) {\n                    line_name = sub_ind;\n                    var built_chart = build_basic_indicator(target_chart, current_ind[sub_ind], chart_type, line_name, ind_name);\n                }\n            } else {\n                if (indicator_is_single_mapping.includes(indicator)) {\n                    line_name = raw_indicator;\n                }\n                var built_chart = build_basic_indicator(target_chart, current_ind, chart_type, line_name, ind_name);\n            }\n        }\n    }\n}"
  },
  {
    "path": "core/static/js/script.js",
    "content": "//\r\n// \r\nconst socket = io('http://'+ip+':'+port);\r\n\r\nconst class_data_mapping = {\r\n    'trader-state':'runtime_state', \r\n    'trader-lastupdate':'last_update_time', \r\n    'trader-lastprice':'lastPrice',\r\n    'trader-markettype':'order_market_type', \r\n    'trader-orderside':'order_side', \r\n    'trader-ordertype':'order_type', \r\n    'trader-orderstatus':'order_status', \r\n    'trader-buyprice':'price', \r\n    'trader-sellprice':'price', \r\n    'trader-orderpoint':'order_point'\r\n};\r\n\r\nvar current_chart = '';\r\nvar update_chart = false;\r\n\r\n\r\n$(document).ready(function() {\r\n    socket.on('current_traders_data', function(data) {\r\n        update_trader_results(data);\r\n    });\r\n});\r\n\r\n\r\nfunction update_trader_results(data) {\r\n    // \r\n    var currentTraders = data['data'];\r\n\r\n    var overall_total_trades = 0;\r\n    var overall_total_pl = 0;\r\n\r\n    for (x = 0; x < (currentTraders.length); x++){\r\n        var current = currentTraders[x];\r\n        var trade_recorder = current['trade_recorder'];\r\n        var update_targets = [`trader_${current['market']}`, `overview_${current['market']}`]\r\n\r\n        for (i = 0; i < (update_targets.length); i++){\r\n            var trader_panel = document.getElementById(update_targets[i]);\r\n            var target_el = null;\r\n\r\n            for (var key in class_data_mapping) {\r\n                target_el = trader_panel.getElementsByClassName(key);\r\n                if (target_el.length != 0) {\r\n                    if (current['order_side'] == 'SELL' && key == 'trader-buyprice') {\r\n                        show_val = trade_recorder[trade_recorder.length-1][1];\r\n                    } else {\r\n                        show_val = current[class_data_mapping[key]];\r\n                    }\r\n\r\n                    if (show_val === null) {\r\n                        show_val = 'Null';\r\n                    }\r\n                    target_el[0].innerText = show_val;\r\n                }\r\n            }\r\n\r\n            target_el = trader_panel.getElementsByClassName('show-sellaction');\r\n            if (target_el.length != 0) {\r\n                if (current['order_side'] == 'SELL') {\r\n                    target_el[0].style.display = 'block';\r\n                } else {\r\n                    target_el[0].style.display = 'none';\r\n                }\r\n            }\r\n\r\n            var outcome = 0;\r\n            var total_trades = 0;\r\n            if (trade_recorder.length >= 2) {\r\n                range = trade_recorder.length/2\r\n                for (y = 0; y < (range); y++) {\r\n                    buy_order = trade_recorder[(range*2)-2]\r\n                    sell_order = trade_recorder[range*2-1]\r\n\r\n                    buy_value = buy_order[1]*buy_order[2]\r\n                    sell_value = sell_order[1]*buy_order[2]\r\n\r\n                    if (buy_order[3].includes(\"SHORT\")) {\r\n                        outcome += buy_value-sell_value;\r\n                    } else {\r\n                        outcome += sell_value-buy_value;\r\n                    }\r\n                    total_trades += 1\r\n                }\r\n            }\r\n\r\n            var r_outcome = Math.round(outcome*100000000)/100000000;\r\n\r\n            target_el = trader_panel.getElementsByClassName('trader-trades')[0];\r\n            target_el.innerText = total_trades;\r\n            target_el = trader_panel.getElementsByClassName('trader-overall')[0];\r\n            target_el.innerText = r_outcome;\r\n\r\n            if (update_targets[i] != `overview_${current['market']}`) {\r\n                overall_total_trades += total_trades;\r\n                overall_total_pl += r_outcome;\r\n            }\r\n\r\n            if ((current_chart == update_targets[i]) && (update_chart == true) && current_chart != 'trader_Overview') {\r\n                console.log(currentTraders);\r\n                update_chart = false;\r\n                target_el = trader_panel.getElementsByClassName('trader_charts')[0];\r\n                build_chart(current['market'], target_el);\r\n            }\r\n        }\r\n    }\r\n    var overview_section = document.getElementById('trader_Overview');\r\n\r\n    target_el = overview_section.getElementsByClassName('overview-totalpl')[0];\r\n    target_el.innerText = overall_total_pl;\r\n    target_el = overview_section.getElementsByClassName('overview-totaltrades')[0];\r\n    target_el.innerText = overall_total_trades;\r\n}\r\n\r\n\r\nfunction hide_section(e, section_id){\r\n\r\n    var section_el = document.getElementsByTagName('section');\r\n    for (i = 0; i < (section_el.length); i++){\r\n        if (section_el[i].id == `trader_${section_id}`) {\r\n            current_chart = `trader_${section_id}`;\r\n            update_chart = true;\r\n            section_el[i].style.display = \"block\";\r\n        } else {\r\n            section_el[i].style.display = \"none\";\r\n        }\r\n    }\r\n}\r\n\r\n\r\nfunction start_trader(e, market_pair){\r\n    e.preventDefault();\r\n    rest_api('POST', 'trader_update', {'action':'start', 'market':market_pair});\r\n}\r\n\r\n\r\nfunction pause_trader(e, market_pair){\r\n    e.preventDefault();\r\n    rest_api('POST', 'trader_update', {'action':'pause', 'market':market_pair});\r\n}\r\n\r\n\r\nfunction build_chart(market_pair, element){\r\n    rest_api('GET', `get_trader_charting?market=${market_pair}&limit=200`, null, initial_build, element);\r\n}\r\n\r\n\r\nfunction rest_api(method, endpoint, data=null, target_function=null, target_element=null){\r\n    // if either the user has requested a force update on bot data or the user has added a new market to trade then send an update to the backend.\r\n    console.log(`'M: ${method}, ULR: /rest-api/v1/${endpoint}, D:${data}`);\r\n    let request = new XMLHttpRequest();\r\n    request.open(method, '/rest-api/v1/'+endpoint, true);\r\n\r\n    request.onload = function() {\r\n        if (this.status == 200){\r\n            var resp_data = JSON.parse(request.responseText);\r\n            console.log(resp_data);\r\n            if (target_function != null && target_element == null) {\r\n                target_function(resp_data);\r\n            } else if (target_function != null && target_element != null) {\r\n                target_function(target_element, resp_data['data']);\r\n            }\r\n        } else {\r\n            console.log(`error ${request.status} ${request.statusText}`);\r\n        }\r\n    }\r\n\r\n    if (data == null){\r\n        request.send();\r\n    } else {\r\n        request.setRequestHeader('content-type', 'application/json');\r\n        request.send(JSON.stringify(data));\r\n    }\r\n}"
  },
  {
    "path": "core/templates/jinja_templates.html",
    "content": "{% macro overview_data_panel(market_symbols) %}\n    <section id=\"trader_Overview\" class=\"Overview-panel\">\n        <h3>Trader Overview</h3>\n        <p>\n            Total PL: <span class=\"overview-totalpl\"></span> | Total Trades: <span class=\"overview-totaltrades\"></span>\n        </p>\n        {% for market_symbol in market_symbols %}\n        <div id=\"overview_{{ market_symbol }}\">\n            Symbol: {{ market_symbol }} | State: <span class=\"trader-state\"></span> | Side: <span class=\"trader-orderside\"></span> | Trades: <span class=\"trader-trades\"></span> | Overall: <span class=\"trader-overall\"></span></span> | Last Price: <span class=\"trader-lastprice\"></span> | OP: <span class=\"trader-orderpoint\"></span><br />\n        </div>\n        {% endfor %}\n    </section>\n{% endmacro %}\n\n\n{% macro market_data_panel(market_symbol) %}\n    <section id=\"trader_{{ market_symbol }}\" class=\"trader-panel\">\n        <h3>{{ market_symbol }}</h3>\n        <a href=# class=\"small-button green-button\" onclick=\"start_trader(event, '{{ market_symbol }}');\">Start</a>\n        <a href=# class=\"small-button amber-button\" onclick=\"pause_trader(event, '{{ market_symbol }}');\">Pause</a>\n        <p>\n            State: <span class=\"trader-state\"></span> | Trades: <span class=\"trader-trades\"></span> | Overall: <span class=\"trader-overall\"></span> | Last Update: <span class=\"trader-lastupdate\"></span> | Last Price: <span class=\"trader-lastprice\"></span><br />\n            <span class=\"trader-markettype\"></span> <span class=\"trader-orderside\"></span> | Type: <span class=\"trader-ordertype\"></span> | Status: <span class=\"trader-orderstatus\"></span> | Buy Price: <span class=\"trader-buyprice\"></span><span class=\"show-sellaction\">| Sell Price: <span class=\"trader-sellprice\"></span></span> | OP: <span class=\"trader-orderpoint\"></span>\n        </p>\n        <div class=\"trader_charts\">\n        </div>\n    </section>\n{% endmacro %}"
  },
  {
    "path": "core/templates/main_page.html",
    "content": "<html>\n    <head>\n        <title>Trader Control Panel</title>\n        <meta charst=\"en\">\n        <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n        <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">\n\n        <script src=\"https://cdn.jsdelivr.net/npm/apexcharts\"></script>\n        <script src=\"{{ url_for('static', filename='js/charts.js') }}\"></script>\n        <script type=\"text/javascript\" src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js\"></script>\n        <script type=\"text/javascript\" src=\"//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js\"></script>\n\n        <!-- This is used to load the modules that I made and will be using. -->\n        <link rel=\"stylesheet\" href=\"{{ url_for('static', filename='css/style.css') }}\">\n        <script type=\"text/javascript\">\n            var ip = '{{ data.host.IP }}';\n            var port = '{{ data.host.Port }}';\n        </script>\n        \n    </head>\n    <body>\n        {% from 'jinja_templates.html' import overview_data_panel %}\n        {% from 'jinja_templates.html' import market_data_panel %}\n\n        <div class=\"sidebar\">\n            <h2>Binance Trader</h2>\n            <ul>\n                <li><a href=# onclick=\"hide_section(event, 'Overview');\">Overview</a></li>\n            {% for market_symbol in data.market_symbols %}\n                <li><a href=# onclick=\"hide_section(event, '{{ market_symbol }}');\">{{ market_symbol }}</a></li>\n            {% endfor %}\n            </ul>\n        </div>\n        <main>\n            {{ overview_data_panel(data.market_symbols) }}\n            {% for market_symbol in data.market_symbols %}\n                {{ market_data_panel(market_symbol) }}\n            {% endfor %}\n        </main>\n        <script src=\"{{ url_for('static', filename='js/script.js') }}\"></script>\n    </body>\n</html>"
  },
  {
    "path": "core/templates/page_template.html",
    "content": "<html>\n    <head>\n        <title>Trader Control Panel</title>\n        <meta charst=\"en\">\n        <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n        <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">\n\n        <script type=\"text/javascript\" src=\"https://cdn.jsdelivr.net/npm/chart.js@2.8.0\"></script>\n        <script type=\"text/javascript\" src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js\"></script>\n        <script type=\"text/javascript\" src=\"//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js\"></script>\n\n        <!-- This is used to load the modules that I made and will be using. -->\n        <link rel=\"stylesheet\" href=\"{{ url_for('static', filename='css/style.css') }}\">\n        <script type=\"text/javascript\">\n            var ip = '{{ data.hostIP }}';\n            var port = '{{ data.hostPort }}';\n        </script>\n        <script src=\"{{ url_for('static', filename='js/script.js') }}\"></script>\n        \n    </head>\n    <header>\n        <h1>Binance Trader Control Panel</h1>\n    </header>\n    <body>\n        {% block content %}{% endblock content %}\n    </body>\n    <footer>\n    </footer>\n</html>"
  },
  {
    "path": "core/trader.py",
    "content": "#! /usr/bin/env python3\nimport os\nimport sys\nimport copy\nimport time\nimport logging\nimport datetime\nimport threading\nimport trader_configuration as TC\n\nMULTI_DEPTH_INDICATORS = ['ema', 'sma', 'rma']\nTRADER_SLEEP = 1\n\n# Base commission fee with binance.\nCOMMISION_FEE = 0.00075\n\n# Base layout for market pricing.\nBASE_TRADE_PRICE_LAYOUT = {\n    'lastPrice':0,           # Last price seen for the market.\n    'askPrice':0,            # Last ask price seen for the market.\n    'bidPrice':0             # Last bid price seen for the market.\n}\n\n# Base layout for trader state.\nBASE_STATE_LAYOUT = {\n    'base_currency':0.0,     # The base mac value used as referance.\n    'force_sell':False,      # If the trader should dump all tokens.\n    'runtime_state':None,    # The state that actual trader object is at.\n    'last_update_time':0     # The last time a full look of the trader was completed.\n}\n\n# Base layout used by the trader.\nBASE_MARKET_LAYOUT = {\n    'can_order':True,        # If the bot is able to trade in the current market.\n    'price':0.0,             # The price related to BUY.\n    'buy_price':0.0,         # Buy price of the asset.\n    'stopPrice':0.0,         # The stopPrice relate\n    'stopLimitPrice':0.0,    # The stopPrice relate\n    'tokens_holding':0.0,    # Amount of tokens being held.\n    'order_point':None,      # Used to visulise complex stratergy progression points.\n    'order_id':None,         # The ID that is tied to the placed order.\n    'order_status':0,        # The type of the order that is placed\n    'order_side':'BUY',      # The status of the current order.\n    'order_type':'WAIT',     # Used to show the type of order\n    'order_description':0,   # The description of the order.\n    'order_market_type':None,# The market type of the order placed.\n    'market_status':None     # Last state the market trader is.    \n}\n\n# Market extra required data.\nTYPE_MARKET_EXTRA = {\n    'loan_cost':0,           # Loan cost.\n    'loan_id':None,          # Loan id.\n}\n\nclass BaseTrader(object):\n    def __init__(self, quote_asset, base_asset, rest_api, socket_api=None, data_if=None):\n        # Initilize the main trader object.\n        symbol = '{0}{1}'.format(base_asset, quote_asset)\n\n        ## Easy printable format for market symbol.\n        self.print_pair = '{0}-{1}'.format(quote_asset, base_asset)\n        self.quote_asset = quote_asset\n        self.base_asset = base_asset\n\n        logging.info('[BaseTrader][{0}] Initilizing trader object and empty attributes.'.format(self.print_pair))\n\n        ## Sets the rest api that will be used by the trader.\n        self.rest_api = rest_api\n\n        if socket_api == None and data_if == None:\n            logging.critical('[BaseTrader][{0}] Initilization failed, bot must have either socket_api OR data_if set.'.format(self.print_pair))\n            return\n\n        ## Setup socket/data interface.\n        self.data_if = None\n        self.socket_api = None\n\n        if socket_api:\n            ### Setup socket for live market data trading.\n            self.candle_enpoint = socket_api.get_live_candles\n            self.depth_endpoint = socket_api.get_live_depths\n            self.socket_api = socket_api\n        else:\n            ### Setup data interface for past historic trading.\n            self.data_if = data_if\n            self.candle_enpoint = data_if.get_candle_data\n            self.depth_endpoint = data_if.get_depth_data\n\n        ## Setup the default path for the trader by market beeing traded.\n        self.orders_log_path = 'logs/order_{0}_log.txt'.format(symbol)\n        self.configuration = {}\n        self.market_prices = {}\n        self.wallet_pair = None\n        self.custom_conditional_data = {}\n        self.indicators = {}\n        self.market_activity = {}\n        self.trade_recorder = []\n        self.state_data = {}\n        self.rules = {}\n\n        logging.debug('[BaseTrader][{0}] Initilized trader object.'.format(self.print_pair))\n\n\n    def setup_initial_values(self, trading_type, run_type, filters):\n        # Initilize trader values.\n        logging.info('[BaseTrader][{0}] Initilizing trader object attributes with data.'.format(self.print_pair))\n\n        ## Populate required settings.\n        self.configuration.update({\n            'trading_type':trading_type,\n            'run_type':run_type,\n            'base_asset':self.base_asset,\n            'quote_asset':self.quote_asset,\n            'symbol':'{0}{1}'.format(self.base_asset, self.quote_asset)\n        })\n        self.rules.update(filters)\n\n        ## Initilize default values.\n        self.market_activity.update(copy.deepcopy(BASE_MARKET_LAYOUT))\n        self.market_prices.update(copy.deepcopy(BASE_TRADE_PRICE_LAYOUT))\n        self.state_data.update(copy.deepcopy(BASE_STATE_LAYOUT))\n\n        if trading_type == 'MARGIN':\n            self.market_activity.update(copy.deepcopy(TYPE_MARKET_EXTRA))\n\n        logging.debug('[BaseTrader][{0}] Initilized trader attributes with data.'.format(self.print_pair))\n\n\n    def start(self, MAC, wallet_pair, open_orders=None):\n        '''\n        Start the trader.\n        Requires: MAC (Max Allowed Currency, the max amount the trader is allowed to trade with in BTC).\n        -> Check for previous trade.\n            If a recent, not closed traded is seen, or leftover currency on the account over the min to place order then set trader to sell automatically.\n        \n        ->  Start the trader thread. \n            Once all is good the trader will then start the thread to allow for the market to be monitored.\n        '''\n        logging.info('[BaseTrader][{0}] Starting the trader object.'.format(self.print_pair))\n        sock_symbol = self.base_asset+self.quote_asset\n\n        if self.socket_api != None:\n            while True:\n                if self.socket_api.get_live_candles()[sock_symbol] and ('a' in self.socket_api.get_live_depths()[sock_symbol]):\n                    break\n\n        self.state_data['runtime_state'] = 'SETUP'\n        self.wallet_pair = wallet_pair\n        self.state_data['base_currency'] = float(MAC)\n\n        ## Start the main of the trader in a thread.\n        threading.Thread(target=self._main).start()\n        return(True)\n\n\n    def stop(self):\n        ''' \n        Stop the trader.\n        -> Trader cleanup.\n            To gracefully stop the trader and cleanly eliminate the thread as well as market orders.\n        '''\n        logging.debug('[BaseTrader][{0}] Stopping trader.'.format(self.print_pair))\n\n        self.state_data['runtime_state'] = 'STOP'\n        return(True)\n\n\n    def _main(self):\n        '''\n        Main body for the trader loop.\n        -> Wait for candle data to be fed to trader.\n            Infinite loop to check if candle has been populated with data,\n        -> Call the updater.\n            Updater is used to re-calculate the indicators as well as carry out timed checks.\n        -> Call Order Manager.\n            Order Manager is used to check on currently PLACED orders.\n        -> Call Trader Manager.\n            Trader Manager is used to check the current conditions of the indicators then set orders if any can be PLACED.\n        '''\n        sock_symbol = self.base_asset+self.quote_asset\n        last_wallet_update_time = 0\n\n        if self.configuration['trading_type'] == 'SPOT':\n            position_types = ['LONG']\n        elif self.configuration['trading_type'] == 'MARGIN':\n            position_types = ['LONG', 'SHORT']\n\n        ## Main trader loop\n        while self.state_data['runtime_state'] != 'STOP':\n            # Pull required data for the trader.\n            candles = self.candle_enpoint(sock_symbol)\n            books_data = self.depth_endpoint(sock_symbol)\n            self.indicators = TC.technical_indicators(candles)\n            indicators = self.strip_timestamps(self.indicators)\n\n            logging.debug('[BaseTrader] Collected trader data. [{0}]'.format(self.print_pair))\n\n            socket_buffer_symbol = None\n            if self.configuration['run_type'] == 'REAL':\n\n                if sock_symbol in self.socket_api.socketBuffer:\n                    socket_buffer_symbol = self.socket_api.socketBuffer[sock_symbol]\n\n                # get the global socket buffer and update the wallets for the used markets.\n                socket_buffer_global = self.socket_api.socketBuffer\n                if 'outboundAccountPosition' in socket_buffer_global:\n                    if last_wallet_update_time != socket_buffer_global['outboundAccountPosition']['E']:\n                        self.wallet_pair, last_wallet_update_time = self.update_wallets(socket_buffer_global)\n            \n            # Update martket prices with current data\n            if books_data != None:\n                self.market_prices = {\n                    'lastPrice':candles[0][4],\n                    'askPrice':books_data['a'][0][0],\n                    'bidPrice':books_data['b'][0][0]}\n\n            # Check to make sure there is enough crypto to place orders.\n            if self.state_data['runtime_state'] == 'PAUSE_INSUFBALANCE':\n                if self.wallet_pair[self.quote_asset][0] > self.state_data['base_currency']:\n                    self.state_data['runtime_state'] = 'RUN' \n\n            if not self.state_data['runtime_state'] in ['STANDBY', 'FORCE_STANDBY', 'FORCE_PAUSE']:\n                ## Call for custom conditions that can be used for more advanced managemenet of the trader.\n\n                for market_type in position_types:\n                    cp = self.market_activity\n\n                    if cp['order_market_type'] != market_type and cp['order_market_type'] != None:\n                        continue\n\n                    ## For managing active orders.\n                    if socket_buffer_symbol != None or self.configuration['run_type'] == 'TEST':\n                        cp = self._order_status_manager(market_type, cp, socket_buffer_symbol)\n\n                    ## For checking custom conditional actions\n                    self.custom_conditional_data, cp = TC.other_conditions(\n                        self.custom_conditional_data, \n                        cp,\n                        self.trade_recorder,\n                        market_type,\n                        candles,\n                        indicators, \n                        self.configuration['symbol'])\n\n                    ## For managing the placement of orders/condition checking.\n                    if cp['can_order'] and self.state_data['runtime_state'] == 'RUN' and cp['market_status'] == 'TRADING':\n                        if cp['order_type'] == 'COMPLETE':\n                            cp['order_type'] = 'WAIT'\n\n                        tm_data = self._trade_manager(market_type, cp, indicators, candles)\n                        cp = tm_data if tm_data else cp\n\n                    if not cp['market_status']: \n                        cp['market_status'] = 'TRADING'\n\n                    self.market_activity = cp\n\n                    time.sleep(TRADER_SLEEP)\n\n            current_localtime = time.localtime()\n            self.state_data['last_update_time'] = '{0}:{1}:{2}'.format(current_localtime[3], current_localtime[4], current_localtime[5])\n\n            if self.state_data['runtime_state'] == 'SETUP':\n                self.state_data['runtime_state'] = 'RUN'\n        \n\n    def _order_status_manager(self, market_type, cp, socket_buffer_symbol):\n        '''\n        This is the manager for all and any active orders.\n        -> Check orders (Test/Real).\n            This checks both the buy and sell side for test orders and updates the trader accordingly.\n        -> Monitor trade outcomes.\n            Monitor and note down the outcome of trades for keeping track of progress.\n        '''\n        active_trade = False\n        \n        if self.configuration['run_type'] == 'REAL':\n            # Manage order reports sent via the socket.\n            if 'executionReport' in socket_buffer_symbol:\n                order_seen = socket_buffer_symbol['executionReport']\n\n                # Manage trader placed orders via order ID's to prevent order conflict.\n                if order_seen['i'] == cp['order_id']:\n                    active_trade = True\n\n                elif cp['order_status'] == 'PLACED':\n                    active_trade = True\n\n        else:\n            # Basic update for test orders.\n            if cp['order_status'] == 'PLACED':\n                active_trade = True\n                order_seen = None\n\n        trade_done = False\n        if active_trade:\n            # Determine the current state of an order.\n            if self.state_data['runtime_state'] == 'CHECK_ORDERS':\n                self.state_data['runtime_state'] = 'RUN'\n                cp['order_status'] = None\n            cp, trade_done, token_quantity = self._check_active_trade(cp['order_side'], market_type, cp, order_seen)\n\n        ## Monitor trade outcomes.\n        if trade_done:\n            if self.configuration['run_type'] == 'REAL':\n                print('order seen: ')\n                print(order_seen)\n\n            # Update order recorder.\n            self.trade_recorder.append([time.time(), cp['price'], token_quantity, cp['order_description'], cp['order_side']])\n            logging.info('[BaseTrader] Completed {0} order. [{1}]'.format(cp['order_side'], self.print_pair))\n\n            if cp['order_side'] == 'BUY':\n                cp['order_side'] = 'SELL'\n                cp['order_point'] = None\n                cp['buy_price'] = self.trade_recorder[-1][1]\n\n            elif cp['order_side'] == 'SELL':\n                cp['order_side'] = 'BUY'\n                cp['buy_price'] = 0.0\n                cp['order_point'] = None\n                cp['order_market_type'] = None\n\n                # If the trader is trading margin and the runtype is real then repay any loans.\n                if self.configuration['trading_type']  == 'MARGIN':\n                    if self.configuration['run_type'] == 'REAL' and cp['loan_cost'] != 0:\n                        loan_repay_result = self.rest_api.margin_accountRepay(asset=self.base_asset, amount=cp['loan_cost'])\n\n                # Format data to print it to a file.\n                trB = self.trade_recorder[-2]\n                trS = self.trade_recorder[-1]\n\n                buyTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(trB[0]))\n                sellTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(trS[0]))\n\n                outcome = ((trS[1]-trB[1])*trS[2])\n\n                trade_details = 'BuyTime:{0}, BuyPrice:{1:.8f}, BuyQuantity:{2:.8f}, BuyType:{3}, SellTime:{4}, SellPrice:{5:.8f}, SellQuantity:{6:.8f}, SellType:{7}, Outcome:{8:.8f}\\n'.format(\n                    buyTime, trB[1], trB[2], trB[3], sellTime, trS[1], trS[2], trS[3], outcome) # (Sellprice - Buyprice) * tokensSold\n                with open(self.orders_log_path, 'a') as file:\n                    file.write(trade_details)\n\n                # Reset trader variables.\n                cp['market_status']     = 'COMPLETE_TRADE'\n            cp['order_type']        = 'COMPLETE'\n            cp['price']             = 0.0\n            cp['stopPrice']         = 0.0\n            cp['stopLimitPrice']    = 0.0\n            cp['order_id']          = None\n            cp['order_status']      = None\n            cp['order_description'] = None\n\n        return(cp)\n\n\n    def _check_active_trade(self, side, market_type, cp, order_seen):\n        trade_done = False\n        token_quantity = None\n\n        if side == 'BUY':\n            if self.configuration['run_type'] == 'REAL':\n                if order_seen['S'] == 'BUY' or (market_type == 'SHORT' and order_seen['S'] == 'SELL'):\n                    cp['price'] = float(order_seen['L'])\n\n                    if market_type == 'LONG':\n                        target_wallet = self.base_asset\n                        target_quantity = float(order_seen['q'])\n                    elif market_type == 'SHORT':\n                        target_wallet = self.quote_asset\n                        target_quantity = float(order_seen['q'])*float(order_seen['L'])\n\n                    if order_seen['X'] == 'FILLED' and target_wallet in self.wallet_pair:\n                        wallet_pair = self.wallet_pair\n                        if wallet_pair[target_wallet][0] >= target_quantity:\n                            trade_done = True\n                            token_quantity = float(order_seen['q'])\n                    elif order_seen['X'] == 'PARTIALLY_FILLED' and cp['order_status'] != 'LOCKED':\n                        cp['order_status'] = 'LOCKED'\n            else:\n                if market_type == 'LONG':\n                    trade_done = True if ((self.market_prices['lastPrice'] <= cp['price']) or (cp['order_type'] == 'MARKET')) else False\n                elif market_type == 'SHORT':\n                    trade_done = True if ((self.market_prices['lastPrice'] >= cp['price']) or (cp['order_type'] == 'MARKET')) else False\n                token_quantity = cp['tokens_holding']\n\n        elif side == 'SELL':\n            if self.configuration['run_type'] == 'REAL':\n                if order_seen['S'] == 'SELL' or (market_type == 'SHORT' and order_seen['S'] == 'BUY'):\n                    if order_seen['X'] == 'FILLED':\n                        cp['price'] = float(order_seen['L'])\n                        token_quantity = float(order_seen['q'])\n                        trade_done = True\n                    elif order_seen['X'] == 'PARTIALLY_FILLED' and cp['order_status'] != 'LOCKED':\n                        cp['order_status'] = 'LOCKED'\n            else:\n                if market_type == 'LONG':\n                    if cp['order_type'] != 'STOP_LOSS_LIMIT':\n                        trade_done = True if ((self.market_prices['lastPrice'] >= cp['price']) or (self.market_prices['lastPrice'] >= cp['stopLimitPrice']) or (cp['order_type'] == 'MARKET')) else False\n                    else:\n                        trade_done = True if (self.market_prices['lastPrice'] <= cp['price']) else False\n\n                elif market_type == 'SHORT':\n                    if cp['order_type'] != 'STOP_LOSS_LIMIT':\n                        trade_done = True if ((self.market_prices['lastPrice'] <= cp['price']) or (cp['order_type'] == 'MARKET')) else False\n                    else:\n                        trade_done = True if (self.market_prices['lastPrice'] >= cp['price']) else False\n                token_quantity = cp['tokens_holding']\n        return(cp, trade_done, token_quantity)\n\n\n    def _trade_manager(self, market_type, cp, indicators, candles):\n        ''' \n        Here both the sell and buy conditions are managed by the trader.\n        -\n        '''\n\n\n        # Check for entry/exit conditions.\n\n        ## If order status is locked then return.\n        if cp['order_status'] == 'LOCKED':\n            return\n\n        ## Select the correct conditions function dynamically.\n        if cp['order_side'] == 'SELL':\n            current_conditions = TC.long_exit_conditions if market_type == 'LONG' else TC.short_exit_conditions\n\n        elif cp['order_side'] == 'BUY':\n            ### If the bot is forced set to froce prevent buy return.\n            if self.state_data['runtime_state'] == 'FORCE_PREVENT_BUY':\n                return\n\n            current_conditions = TC.long_entry_conditions if market_type == 'LONG' else TC.short_entry_conditions\n\n\n        # Check condition check results.\n        logging.debug('[BaseTrader] Checking for {0} {1} condition. [{2}]'.format(cp['order_side'], market_type, self.print_pair))\n        new_order = current_conditions(self.custom_conditional_data, cp, indicators,  self.market_prices, candles, self.print_pair)\n                \n        ## If no new order is returned then just return.\n        if not(new_order):\n            return\n\n        ## Update order point.\n        if 'order_point' in new_order:\n            cp['order_point'] = new_order['order_point']\n\n        order = None\n\n        ## Check for a new possible order type update.\n        if 'order_type' in new_order:\n\n            ### If order type update is not WAIT then update the current order OR cancel the order.\n            if new_order['order_type'] != 'WAIT':\n                print(new_order)\n                cp['order_description'] = new_order['description']\n\n                #### Format the prices to be used.\n                if 'price' in new_order:\n                    if 'price' in new_order:\n                        new_order['price'] = '{0:.{1}f}'.format(float(new_order['price']), self.rules['TICK_SIZE'])\n                    if 'stopPrice' in new_order:\n                        new_order['stopPrice'] = '{0:.{1}f}'.format(float(new_order['stopPrice']), self.rules['TICK_SIZE'])\n\n                    if float(new_order['price']) != cp['price']:\n                        order = new_order\n                else:\n                    #### If the order type has changed OR the placement price has been changed update the order with the new price/type.\n                    if cp['order_type'] != new_order['order_type']:\n                        order = new_order\n\n            else:\n                #### Cancel the order.\n                cp['order_status'] = None\n                cp['order_type'] = 'WAIT'\n\n                #### Only reset market type IF its buy or as margin allows for 2 market types.\n                if cp['order_side'] == 'BUY':\n                    cp['order_market_type'] = None\n\n                #### Cancel active order if one is placed.\n                if cp['order_id'] != None and new_order['order_type'] == 'WAIT':\n                    cancel_order_results = self._cancel_order(cp['order_id'], cp['order_type'])\n                    cp['order_id'] = None\n\n                return(cp)\n\n        # Place a new market order.\n        if order:\n            order_results = self._place_order(market_type, cp, order)\n            logging.info('order: {0}\\norder result:\\n{1}'.format(order, order_results))\n\n            # Error handle for binance related errors from order placement:\n            if 'code' in order_results['data']:\n                if order_results['data']['code'] == -2010:\n                    self.state_data['runtime_state'] = 'PAUSE_INSUFBALANCE'\n                elif order_results['data']['code'] == -2011:\n                    self.state_data['runtime_state'] = 'CHECK_ORDERS'\n                return\n\n            logging.info('[BaseTrader] {0} Order placed for {1}.'.format(self.print_pair, new_order['order_type']))\n            logging.info('[BaseTrader] {0} Order placement results:\\n{1}'.format(self.print_pair, str(order_results['data'])))\n\n            if 'type' in order_results['data']:\n                if order_results['data']['type'] == 'MARKET':\n                    price1 = order_results['data']['fills'][0]['price']\n                else:\n                    price1 = order_results['data']['price']\n            else: price1 = None\n\n            # Set the price the order was placed at.\n            price2 = None\n            if 'price' in order:\n                price2 = float(order['price'])\n                if price1 == 0.0 or price1 == None: \n                    order_price = price2\n                else: order_price = price1\n            else: order_price = price1\n\n            if 'stopPrice' in order:\n                cp['stopPrice'] == ['stopPrice']\n\n            # Setup the test order quantity and setup margin trade loan.\n            if order['side'] == 'BUY':\n                cp['order_market_type'] = market_type\n\n                if self.configuration['run_type'] == 'REAL':\n                    if self.configuration['trading_type'] == 'MARGIN' and 'loan_id' in order_results['data']:\n                        cp['loan_id'] = order_results['data']['loan_id'] \n                        cp['loan_cost'] = order_results['data']['loan_cost']\n                else:\n                    cp['tokens_holding'] = order_results['data']['tester_quantity']\n\n            # Update the live order id for real trades.\n            if self.configuration['run_type'] == 'REAL':\n                cp['order_id'] = order_results['data']['orderId']\n\n            cp['price']         = float(order_price)\n            cp['order_type']    = new_order['order_type']\n            cp['order_status']  = 'PLACED'\n\n            logging.info('type: {0}, status: {1}'.format(new_order['order_type'], cp['order_status']))\n            return(cp)\n\n\n    def _place_order(self, market_type, cp, order):\n        ''' place order '''\n\n        ## Calculate the quantity amount for the BUY/SELL side for long/short real/test trades.\n        quantity = None\n        if order['side'] == 'BUY':\n            quantity = float(self.state_data['base_currency'])/float(self.market_prices['bidPrice'])\n\n        elif order['side'] == 'SELL':\n            if 'order_prec' in order:\n                quantity = ((float(order['order_prec']/100))*float(self.trade_recorder[-1][2]))\n            else:\n                quantity = float(self.trade_recorder[-1][2])\n\n        if self.configuration['run_type'] == 'REAL' and cp['order_id']:\n            cancel_order_results = self._cancel_order(cp['order_id'], cp['order_type'])\n            if 'code' in cancel_order_results:\n                return({'action':'ORDER_ISSUE', 'data':cancel_order_results})\n\n        ## Setup the quantity to be the correct precision.\n        if quantity:\n            split_quantity = str(quantity).split('.')\n            f_quantity = float(split_quantity[0]+'.'+split_quantity[1][:self.rules['LOT_SIZE']])\n\n        logging.info('Order: {0}'.format(order))\n\n        ## Place orders for both SELL/BUY sides for both TEST/REAL run types.\n        if self.configuration['run_type'] == 'REAL':\n            rData = {}\n            ## Convert BUY to SELL if the order is a short (for short orders are inverted)\n            if market_type == 'LONG':\n                side = order['side']\n            elif market_type == 'SHORT':\n                if order['side'] == 'BUY':\n                    ## Calculate the quantity required for a short loan.\n                    loan_get_result = self.rest_api.margin_accountBorrow(asset=self.base_asset, amount=f_quantity)\n                    rData.update({'loan_id':loan_get_result['tranId'], 'loan_cost':f_quantity})\n                    side = 'SELL'\n                else:\n                    side = 'BUY'\n\n            if order['order_type'] == 'OCO_LIMIT':\n                logging.info('[BaseTrader] symbol:{0}, side:{1}, type:{2}, quantity:{3} price:{4}, stopPrice:{5}, stopLimitPrice:{6}'.format(self.print_pair, order['side'], order['order_type'], f_quantity,order['price'], order['stopPrice'], order['stopLimitPrice']))\n                rData.update(self.rest_api.place_order(self.configuration['trading_type'], symbol=self.configuration['symbol'], side=side, type=order['order_type'], timeInForce='GTC', quantity=f_quantity, price=order['price'], stopPrice=order['stopPrice'], stopLimitPrice=order['stopLimitPrice']))\n                return({'action':'PLACED_MARKET_ORDER', 'data':rData})\n\n            elif order['order_type'] == 'MARKET':\n                logging.info('[BaseTrader] symbol:{0}, side:{1}, type:{2}, quantity:{3}'.format(self.print_pair, order['side'], order['order_type'], f_quantity))\n                rData.update(self.rest_api.place_order(self.configuration['trading_type'], symbol=self.configuration['symbol'], side=side, type=order['order_type'], quantity=f_quantity))\n                return({'action':'PLACED_MARKET_ORDER', 'data':rData})\n\n            elif order['order_type'] == 'LIMIT':\n                logging.info('[BaseTrader] symbol:{0}, side:{1}, type:{2}, quantity:{3} price:{4}'.format(self.print_pair, order['side'], order['order_type'], f_quantity, order['price']))\n                rData.update(self.rest_api.place_order(self.configuration['trading_type'], symbol=self.configuration['symbol'], side=side, type=order['order_type'], timeInForce='GTC', quantity=f_quantity, price=order['price']))\n                return({'action':'PLACED_LIMIT_ORDER', 'data':rData})\n\n            elif order['order_type'] == 'STOP_LOSS_LIMIT':\n                logging.info('[BaseTrader] symbol:{0}, side:{1}, type:{2}, quantity:{3} price:{4}, stopPrice:{5}'.format(self.print_pair, order['side'], order['order_type'], f_quantity, order['price'], order['stopPrice']))\n                rData.update(self.rest_api.place_order(self.configuration['trading_type'], symbol=self.configuration['symbol'], side=side, type=order['order_type'], timeInForce='GTC', quantity=f_quantity, price=order['price'], stopPrice=order['stopPrice']))\n                return({'action':'PLACED_STOPLOSS_ORDER', 'data':rData})\n\n        else:\n            placed_order = {'type':'test', 'price':0, 'tester_quantity':float(f_quantity)}\n            \n            if order['order_type'] == 'OCO_LIMIT':\n                placed_order.update({'stopPrice':order['stopPrice'], 'stopLimitPrice':order['stopLimitPrice']})\n\n            if order['order_type'] == 'MARKET':\n                placed_order.update({'price':self.market_prices['lastPrice']})\n            else:\n                placed_order.update({'price':order['price']})\n\n            return({'action':'PLACED_TEST_ORDER', 'data':placed_order})\n\n\n    def _cancel_order(self, order_id, order_type):\n        ''' cancel orders '''\n        if self.configuration['run_type'] == 'REAL':\n            if order_type == 'OCO_LIMIT':\n                cancel_order_result = self.rest_api.cancel_oco_order(symbol=self.configuration['symbol'])\n            else:\n                cancel_order_result = self.rest_api.cancel_order(self.configuration['trading_type'], symbol=self.configuration['symbol'], orderId=order_id)\n            logging.debug('[BaseTrader] {0} cancel order results:\\n{1}'.format(self.print_pair, cancel_order_result))\n            return(cancel_order_result)\n        logging.debug('[BaseTrader] {0} cancel order.'.format(self.print_pair))\n        return(True)\n\n\n    def get_trader_data(self):\n        ''' Access that is availble for the traders details. '''\n        trader_data = {\n            'market':self.print_pair,\n            'configuration':self.configuration,\n            'market_prices':self.market_prices,\n            'wallet_pair':self.wallet_pair,\n            'custom_conditions':self.custom_conditional_data,\n            'market_activity':self.market_activity,\n            'trade_recorder':self.trade_recorder,\n            'state_data':self.state_data,\n            'rules':self.rules\n        }\n\n        return(trader_data)\n\n\n    def strip_timestamps(self, indicators):\n\n        base_indicators = {}\n\n        for ind in indicators:\n            if ind in MULTI_DEPTH_INDICATORS:\n                base_indicators.update({ind:{}})\n                for sub_ind in indicators[ind]:\n                    base_indicators[ind].update({sub_ind:[ val[1] for val in indicators[ind][sub_ind] ]})\n            else:\n                base_indicators.update({ind:[ val[1] for val in indicators[ind] ]})\n\n        return(base_indicators)\n\n\n    def update_wallets(self, socket_buffer_global):\n        ''' Update the wallet data with that collected via the socket '''\n        last_wallet_update_time = socket_buffer_global['outboundAccountPosition']['E']\n        foundBase = False\n        foundQuote = False\n        wallet_pair = {}\n\n        for wallet in socket_buffer_global['outboundAccountPosition']['B']:\n            if wallet['a'] == self.base_asset:\n                wallet_pair.update({self.base_asset:[float(wallet['f']), float(wallet['l'])]})\n                foundBase = True\n            elif wallet['a'] == self.quote_asset:\n                wallet_pair.update({self.quote_asset:[float(wallet['f']), float(wallet['l'])]})\n                foundQuote = True\n\n            if foundQuote and foundBase:\n                break\n\n        if not(foundBase):\n            wallet_pair.update({self.base_asset:[0.0, 0.0]})\n        if not(foundQuote):\n            wallet_pair.update({self.quote_asset:[0.0, 0.0]})\n\n        logging.info('[BaseTrader] New account data pulled, wallets updated. [{0}]'.format(self.print_pair))\n        return(wallet_pair, last_wallet_update_time)"
  },
  {
    "path": "patterns.py",
    "content": "import numpy as np\r\n'''\r\nx : Price list\r\ny : Last comparible value.\r\nz : Historic comparible value.\r\n\r\n# find_high_high\r\n( x : price list, y : last high, z : historic high value )\r\nReturn highest value seen vs both recent and historically or None.\r\n\r\n# find_high\r\n( x : price list, y : last high )\r\nReturn the highest value seen or None.\r\n\r\n# find_low_high\r\n( x : price list, y : last high, z : historic high value )\r\nReturn highest value seen recently but lower historically or None.\r\n\r\n# find_low_low\r\n( x : price list, y : last low, z : historic low value )\r\nReturn the lowest value seen vs both recent and historically or None.\r\n\r\n# find_low\r\n( x : price list, y : last low )\r\nReturn the lowest value seen or None.\r\n\r\n# find_high_low\r\n( x : price list, y : last low, z : historic low value )\r\nReturn lowest value seen recently but higher historically or None.\r\n'''\r\n## High setups\r\nfind_high_high  = lambda x, y, z: x.max() if z < x.max() > y else None\r\nfind_high       = lambda x, y: x.max() if x.max() > y else None\r\nfind_low_high   = lambda x, y, z: x.max() if z > x.max() > y else None\r\n## Low setup\r\nfind_low_low    = lambda x, y, z: x.min() if z > x.min() < y else None\r\nfind_low        = lambda x, y: x.min() if x.min() < y else None\r\nfind_high_low   = lambda x, y, z: x.min() if z < x.min() < y else None\r\n\r\n\"\"\"\r\nTrading patterns.\r\n\r\n\"\"\"\r\nclass pattern_W:\r\n    def __init__(self):\r\n        self.required_points = 4\r\n        self.result_points = 1 # Only required for testing to view outcome.\r\n        self.segment_span = 4\r\n        self.price_point = 0\r\n\r\n    def check_condition(self, point_set):\r\n        if point_set[3] > point_set[1] > point_set[2] > point_set[0]:\r\n            print('part 1')\r\n            if point_set[1] > point_set[2]+((point_set[3]-point_set[2])/2) and (100 - ((point_set[0]/point_set[2])*100)) < 1.2:\r\n                print('part 2')\r\n                return(True)\r\n\r\n        return(False)"
  },
  {
    "path": "requirements.txt",
    "content": "numpy\r\nrequests\r\nflask\r\nflask-socketio==4.3.2\r\nwebsocket-client\r\n"
  },
  {
    "path": "run.py",
    "content": "#! /usr/bin/env python3\nimport os\nimport logging\nfrom core import botCore\n\n## Setup    \ncwd = os.getcwd()\nCACHE_DIR = 'cache/'.format(cwd)\nLOGS_DIR = 'logs/'.format(cwd)\n\n## Settup logging.\nlog_format = '%(asctime)s:%(name)s:%(message)s'\nlogging.basicConfig(\n    format=log_format,\n    level=logging.INFO)\nlogger = logging.getLogger()\n\nSETTINGS_FILE_NAME = 'settings.conf'\nDEFAULT_SETTINGS_DATA = '''# Public and Private key pais used for the for the trader.\nPUBLIC_KEY=\nPRIVATE_KEY=\n\n# Allow trader to be run in test mode (True/False).\nIS_TEST=True\n\n# Allow trader to be run in either spot or margin type.\nMARKET_TYPE=SPOT\n\n# Automatically update the BNB balance when low (for trading fees, only applicable to real trading)\nUPDATE_BNB_BALANCE=True\n\n# Interval used for the trader (1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d).\nTRADER_INTERVAL=15m\n\n# The currency max the trader will use (in BTC) also note this scales up with the number of markets i.e. 2 pairs each market will have 0.0015 as their trading currency pair.\nTRADING_CURRENCY=0.002\n\n# The markets that will be traded (currently only BTC markets) seperate markets with a , for multi market trading.\nTRADING_MARKETS=BTC-ETH,BTC-LTC\n\n# Configuration for the webapp (default if left blank is IP=127.0.0.1, Port=5000)\nHOST_IP=\nHOST_PORT=\n\n# Configuration for the candle range and depth range (default if left bank is candles=500, Depth=50)\nMAX_CANDLES=\nMAX_DEPTH=\n'''\n\n\ndef settings_reader():\n    # Setting reader function to parse over the settings file and collect kv pairs.\n\n    ## Setup settings file object with initial default variables.\n    settings_file_data = {'public_key':'', 'private_key':'', 'host_ip':'127.0.0.1', 'host_port':5000, 'max_candles':500,'max_depth':50}\n\n    ## Read the settings file and extract the fields.\n    with open(SETTINGS_FILE_NAME, 'r') as f:\n        for line in f.readlines():\n\n            ### Check for kv line.\n            if not('=' in line) or line[0] == '#':\n                continue\n\n            key, data = line.split('=')\n\n            ### Check if data holds a value.\n            if data == None or data == '\\n':\n                continue\n\n            data = data.replace('\\n', '')\n\n            if key == 'IS_TEST':\n                data = 'TEST' if data.upper() == 'TRUE' else 'REAL'\n                key = 'run_type'\n\n            elif key == 'MARKET_TYPE':\n                data = data.upper()\n\n            elif key == 'TRADING_MARKETS':\n                data = data.replace(' ', '')\n                data = data.split(',') if ',' in data else [data]\n\n            elif key == 'HOST_IP':\n                default_ip = '127.0.0.1'\n\n            elif key == 'HOST_PORT':\n                data = int(data)\n\n            elif key == 'MAX_CANDLES':\n                data = int(data)\n\n            elif key == 'MAX_DEPTH':\n                data = int(data)\n\n            settings_file_data.update({key.lower():data})\n\n    return(settings_file_data)\n\n\nif __name__ == '__main__':\n\n    ## Check and make cache/logs dir.\n    if not(os.path.exists(LOGS_DIR)):\n        os.makedirs(LOGS_DIR, exist_ok=True)\n    if not(os.path.exists(CACHE_DIR)):\n        os.makedirs(CACHE_DIR, exist_ok=True)\n\n    ## Load settings/create settings file.\n    if os.path.exists(SETTINGS_FILE_NAME):\n        settings = settings_reader()\n        botCore.start(settings, LOGS_DIR, CACHE_DIR)\n    else:\n        with open(SETTINGS_FILE_NAME, 'w') as f:\n            f.write(DEFAULT_SETTINGS_DATA)\n        print('Created settings.conf file.')\n\n"
  },
  {
    "path": "trader_configuration.py",
    "content": "import logging\nimport numpy as np\nimport technical_indicators as TI\n\n## Minimum price rounding.\npRounding = 8\n\ndef technical_indicators(candles):\n    indicators = {}\n\n    time_values     = [candle[0] for candle in candles]\n    open_prices     = [candle[1] for candle in candles]\n    high_prices     = [candle[2] for candle in candles]\n    low_prices      = [candle[3] for candle in candles]\n    close_prices    = [candle[4] for candle in candles]\n\n    indicators.update({'macd':TI.get_MACD(close_prices, time_values=time_values, map_time=True)})\n\n    indicators.update({'ema':{}})\n    indicators['ema'].update({'ema200':TI.get_EMA(close_prices, 200, time_values=time_values, map_time=True)})\n\n    return(indicators)\n\n'''\n--- Current Supported Order ---\n    Below are the currently supported order types that can be placed which the trader\n-- MARKET --\n    To place a MARKET order you must pass:\n        'side'              : 'SELL', \n        'description'       : 'Long exit signal', \n        'order_type'        : 'MARKET'\n    \n-- LIMIT STOP LOSS --\n    To place a LIMIT STOP LOSS order you must pass:\n        'side'              : 'SELL', \n        'price'             : price,\n        'stopPrice'         : stopPrice,\n        'description'       : 'Long exit stop-loss', \n        'order_type'        : 'STOP_LOSS_LIMIT'\n-- LIMIT --\n    To place a LIMIT order you must pass:\n        'side'              : 'SELL', \n        'price'             : price,\n        'description'       : 'Long exit stop-loss', \n        'order_type'        : 'LIMIT'\n-- OCO LIMIT --\n    To place a OCO LIMIT order you must pass:\n        'side'              : 'SELL', \n        'price'             : price,\n        'stopPrice'         : stopPrice,\n        'stopLimitPrice'    : stopLimitPrice,\n        'description'       : 'Long exit stop-loss', \n        'order_type'        : 'OCO_LIMIT'\n--- Key Descriptions--- \n    Section will give brief descript of what each order placement key is and how its used.\n        side            = The side the order is to be placed either buy or sell.\n        price           = Price for the order to be placed.\n        stopPrice       = Stop price to trigger limits.\n        stopLimitPrice  = Used for OCO to to determine price placement for part 2 of the order.\n        description     = A description for the order that can be used to identify multiple conditions.\n        order_type      = The type of the order that is to be placed.\n--- Candle Structure ---\n    Candles are structured in a multidimensional list as follows:\n        [[time, open, high, low, close, volume], ...]\n'''\n\n\ndef other_conditions(custom_conditional_data, trade_information, previous_trades, position_type, candles, indicators, symbol):\n    # Define defaults.\n    can_order = True\n\n    # Setup additional extra conditions for trading.\n    if trade_information['market_status'] == 'COMPLETE_TRADE':\n        trade_information['market_status'] = 'TRADING'\n\n    trade_information.update({'can_order':can_order})\n    return(custom_conditional_data, trade_information)\n\n\ndef long_exit_conditions(custom_conditional_data, trade_information, indicators, prices, candles, symbol):\n    # Place Long exit (sell) conditions under this section.\n    order_point = 0\n    signal_id = 0\n    macd = indicators['macd']\n\n    if macd[0]['macd'] < macd[1]['macd']:\n        order_point += 1\n        if macd[1]['hist'] < macd[0]['hist']:\n            return({'side':'SELL',\n                'description':'LONG exit signal 1', \n                'order_type':'MARKET'})\n\n    stop_loss_price = float('{0:.{1}f}'.format((trade_information['buy_price']-(trade_information['buy_price']*0.004)), pRounding))\n    stop_loss_status = basic_stoploss_setup(trade_information, stop_loss_price, stop_loss_price, 'LONG')\n\n    # Base return for waiting and updating order positions.\n    if stop_loss_status:\n        return(stop_loss_status)\n    else:\n        return({'order_point':'L_ext_{0}_{1}'.format(signal_id, order_point)})\n\n\ndef long_entry_conditions(custom_conditional_data, trade_information, indicators, prices, candles, symbol):\n    # Place Long entry (buy) conditions under this section.\n    order_point = 0\n    signal_id = 0\n    macd = indicators['macd']\n    ema200 = indicators['ema']['ema200']\n\n    if (candles[0][4] > ema200[0]):\n        if macd[0]['macd'] > macd[1]['macd']:\n            order_point += 1\n            if macd[1]['hist'] > macd[0]['hist']:\n                return({'side':'BUY',\n                    'description':'LONG entry signal 1', \n                    'order_type':'MARKET'})\n\n    # Base return for waiting and updating order positions.\n    if order_point == 0:\n        return({'order_type':'WAIT'})\n    else:\n        return({'order_type':'WAIT', 'order_point':'L_ent_{0}_{1}'.format(signal_id, order_point)})\n\n\ndef short_exit_conditions(custom_conditional_data, trade_information, indicators, prices, candles, symbol):\n    ## Place Short exit (sell) conditions under this section.\n    order_point = 0\n    signal_id = 0\n    macd = indicators['macd']\n\n    if macd[0]['macd'] > macd[1]['macd']:\n        order_point += 1\n        if macd[1]['hist'] > macd[0]['hist']:\n            return({'side':'SELL',\n                'description':'SHORT exit signal 1', \n                'order_type':'MARKET'})\n\n    stop_loss_price = float('{0:.{1}f}'.format((trade_information['buy_price']+(trade_information['buy_price']*0.004)), pRounding))\n    stop_loss_status = basic_stoploss_setup(trade_information, stop_loss_price, stop_loss_price, 'SHORT')\n\n    # Base return for waiting and updating order positions.\n    if stop_loss_status:\n        return(stop_loss_status)\n    else:\n        return({'order_point':'S_ext_{0}_{1}'.format(signal_id, order_point)})\n\n\ndef short_entry_conditions(custom_conditional_data, trade_information, indicators, prices, candles, symbol):\n    ## Place Short entry (buy) conditions under this section.\n    order_point = 0\n    signal_id = 0\n    macd = indicators['macd']\n    ema200 = indicators['ema']['ema200']\n\n    if (candles[0][4] < ema200[0]):\n        if macd[0]['macd'] < macd[1]['macd'] and macd[0]['hist'] > macd[0]['macd']:\n            order_point += 1\n            if macd[1]['hist'] < macd[0]['hist']:\n                return({'side':'BUY',\n                    'description':'SHORT entry signal 1', \n                    'order_type':'MARKET'})\n\n    # Base return for waiting and updating order positions.\n    if order_point == 0:\n        return({'order_type':'WAIT'})\n    else:\n        return({'order_type':'WAIT', 'order_point':'S_ent_{0}_{1}'.format(signal_id, order_point)})\n\n\ndef basic_stoploss_setup(trade_information, price, stop_price, position_type):\n    # Basic stop-loss setup.\n    if trade_information['order_type'] == 'STOP_LOSS_LIMIT':\n        return\n\n    return({'side':'SELL', \n        'price':price,\n        'stopPrice':stop_price,\n        'description':'{0} exit stop-loss'.format(position_type), \n        'order_type':'STOP_LOSS_LIMIT'})"
  }
]