def setup(self): user_file = path("@/CSV/users.csv") print(user_file) if not os.path.isfile(user_file): raise ValueError("auth file missing.") with open(user_file) as f: reader = csv.DictReader(f) for user_data in reader: if (not (user_data["identity"] and user_data["password"])) or ( not (user_data["api_key"] and user_data["api_secret"])): logging.warning("invalid auth: %s".format(user_data)) continue self.user_auth_list.append(user_data) self.user_auth_queue.put_nowait(user_data) self.order_price_list.extend( map(lambda x: float(os.environ.get("BASE_PRICE", 10000)) + 0.5 * x, range(1, int(os.environ.get("LEVELS", 50)) + 1, 1)))
def cancel_all(client): for auth in AUTH_LIST: client.swagger_spec.http_client.authenticator = auth try: client.Order.Order_cancelAll().result() except (SwaggerError, HTTPBadRequest) as e: handle_exception(e) if __name__ == "__main__": running_flag = threading.Event() pause_flag = threading.Event() pause_flag.set() init_auth(path("@/CSV/users.csv"), AUTH_TOTAL) client_instance = nge(host=host_url(host=HOST)) if len(sys.argv) > 1 and sys.argv[1] == "cancel": cancel_all(client_instance) exit() mbl_local = {"Buy": dict(), "Sell": dict()} running_flag.set() main(flags=(running_flag, pause_flag), client=client_instance, symbol=SYMBOL,
from common.utils import path from clients.nge import nge, NGEAPIKeyAuthenticator # from clients.sso import User if __name__ == "__main__": host = "http://localhost" client = nge(host=host) auth_queue = Queue() base_price = float(os.environ.get("BASE_PRICE", 10000)) levels = int(os.environ.get("LEVELS", 50)) order_total = int(os.environ.get("ORDER_TOTAL", 10000)) user_file = path("@/CSV/users.csv") order_file = path("@/CSV/orders.csv") price_list = list( map(lambda x: base_price + 0.5 * x, range(1, levels + 1, 1))) volume_list = [1, 3, 5, 10, 15, 30, 50, 100] directions = ("Buy", "Sell") if not os.path.isfile(order_file): with open(order_file, mode='w+', encoding='utf-8', newline='') as f: order_writer = csv.DictWriter(f, fieldnames=("symbol", "side", "price", "orderQty")) order_writer.writeheader() order_writer.writerows([{ 'symbol': 'XBTUSD',
def nge(host="http://trade", config=None, api_key=None, api_secret=None): """ :rtype: SwaggerClient """ if not config: # See full config options at # http://bravado.readthedocs.io/en/latest/configuration.html config = { # Don't use models (Python classes) instead of dicts for # #/definitions/{models} 'use_models': False, 'validate_requests': True, # bravado has some issues with nullable fields 'validate_responses': False, 'include_missing_properties': False, # Returns response in 2-tuple of (body, response); # if False, will only return body 'also_return_response': True, 'formats': [ SwaggerFormat(format="guid", to_wire=lambda guid_obj: str(guid_obj), to_python=guid_deserializer, description="GUID to uuid", validate=guid_validate), SwaggerFormat(format="date-time", to_wire=datetime_serializer, to_python=datetime_deserializer, description="date-time", validate=datetime_validate) ] } spec_dir = path("@/swagger") spec_name = ("nge", "bitmex") spec_extension = ("yaml", "yml", "json") load_method = { "yaml": yaml.safe_load, "yml": yaml.safe_load, "json": json.dumps } with pushd(spec_dir): spec_file = "" for name, ext in product(spec_name, spec_extension): spec_file = ".".join([name, ext]) if os.path.isfile(spec_file): break if not spec_file: raise RuntimeError("no valid swagger api define file found.") with open(spec_file, encoding="utf-8") as f: spec_dict = load_method[ext](f.read()) if api_key and api_secret: request_client = RequestsClient() request_client.authenticator = NGEAPIKeyAuthenticator( host=host, api_key=api_key, api_secret=api_secret) return SwaggerClient.from_spec(spec_dict, origin_url=host, config=config, http_client=request_client) else: return SwaggerClient.from_spec(spec_dict, origin_url=host, config=config)
print(e) continue if not user or not user.logged: print("register failed: {}".format(user_data)) continue if not user.get_api_key(): print("get key failed: {}".format(user_data)) continue user.deposit() user_data.update({ 'api_key': user.api_key, 'api_secret': user.api_secret }) user_list.append(user_data) end = time.time() with open(path("@/CSV/users.csv"), mode="w", encoding="utf-8") as f: writer = DictWriter( f=f, fieldnames=["identity", "password", "api_key", "api_secret"]) writer.writeheader() writer.writerows(user_list) print("user registered total: {}".format(len(user_list))) print("rps: {}".format(round(user_total / (end - start))))
req_key=key_mapper[item], req_cache=self._request_cache, rtn_cache=rtn_cache_mapper[item], logger=self.logger, origin_res=origin_attribute, args=ResourceWrapper.args_tuple( sync_req_rtn=self.SYNC_REQ_WITH_RTN, wait_condition=self._wait_condition, rtn_wait_timeout=self.RTN_WAIT_TIMEOUT)) return origin_attribute if __name__ == "__main__": import logging logging.basicConfig(level=logging.INFO) config_base = path("./config") csv_base = path("./csv") with open(os.path.join(config_base, "order_config.yml"), mode='rb') as f: config = yaml.safe_load(f) ex = APITester(**config) order_file = os.path.join(csv_base, "order.csv") resource_name = str(os.path.basename(order_file).split( ".")[0].capitalize()) resource = getattr(ex, resource_name) DataMixin.register_resource(resource_name, resource) order_list = CSVData(order_file, rec_obj_mixin=(DataMixin, ))