### Installation and Initialization Source: https://github.com/shidenggui/easytrader/blob/master/docs/miniqmt.md Instructions for installing the MiniQMT component and initializing the client. ```APIDOC ## Installation miniqmt requires the `xtquant` library, which is large and needs to be installed separately. ```python pip install easytrader[miniqmt] ``` ## Import ```python import easytrader ``` ## Initialize Client ```python user = easytrader.use('miniqmt') ``` ## Connect to QMT Client Connect to the QMT client using the `connect` method. Ensure QMT is launched in 'Minimal Mode' or 'Independent Trading Mode'. ```python user.connect( miniqmt_path=r"D:\\国金证券QMT交易端\\userdata_mini", # Path to the miniqmt installation within the QMT client stock_account="Your Account ID", # Your account ID trader_callback=None, # Defaults to `easytrader.miniqmt.DefaultXtQuantTraderCallback` ) ``` ### Parameters - `miniqmt_path` (string): The path to the miniqmt installation directory within the QMT client. It's recommended not to install on the C: drive to avoid administrator permission issues. - `stock_account` (string): Your financial account number. - `trader_callback` (object, optional): A callback object for trading events. Defaults to `easytrader.miniqmt.DefaultXtQuantTraderCallback`. ``` -------------------------------- ### Install Easytrader Source: https://context7.com/shidenggui/easytrader/llms.txt Install or upgrade the easytrader library. Optional support for miniqmt can be installed using the `[miniqmt]` extra. ```python pip install easytrader ``` ```python pip install easytrader -U ``` ```python pip install easytrader[miniqmt] ``` -------------------------------- ### Installation and Initialization Source: https://context7.com/shidenggui/easytrader/llms.txt Instructions on how to install and upgrade the Easytrader library, including optional support for miniqmt. ```APIDOC ## Installation and Initialization Install easytrader library and initialize the trading client. ```python # Install pip install easytrader # Upgrade to the latest version pip install easytrader -U # Install miniqmt support (optional) pip install easytrader[miniqmt] ``` ``` -------------------------------- ### Install miniqmt Component Source: https://github.com/shidenggui/easytrader/blob/master/docs/miniqmt.md Install the miniqmt component and its dependencies using pip. This command installs the easytrader library with miniqmt support. ```python pip install easytrader[miniqmt] ``` -------------------------------- ### Initialize EasyTrader Trader (Xueqiu Example) Source: https://github.com/shidenggui/easytrader/blob/master/docs/follow.md Initializes an EasyTrader instance for a specific broker, using Xueqiu as an example. Requires a configuration file for authentication. ```python xq_user = easytrader.use('xq') xq_user.prepare('xq.json') ``` -------------------------------- ### Install EasyTrader using pip Source: https://github.com/shidenggui/easytrader/blob/master/docs/install.md Use this command to install the EasyTrader library. Ensure pip is available in your environment. ```shell pip install easytrader ``` -------------------------------- ### Connect to QMT Client Source: https://github.com/shidenggui/easytrader/blob/master/docs/miniqmt.md Connect to the QMT client using the `connect` method. Ensure QMT is launched in simplified or standalone trading mode. Provide the path to the miniqmt installation, your stock account, and optionally a trader callback. ```python user.connect( miniqmt_path=r"D:\\国金证券QMT交易端\\userdata_mini", # QMT 客户端下的 miniqmt 安装路径 stock_account="你的资金账号", # 资金账号 trader_callback=None, # 默认使用 `easytrader.miniqmt.DefaultXtQuantTraderCallback` ) ``` -------------------------------- ### Start Easytrader Remote Trading Server Source: https://context7.com/shidenggui/easytrader/llms.txt Launch the Easytrader trading service on a cloud server. This allows strategy clients to connect and execute trades remotely. ```python from easytrader import server # 启动交易服务(默认端口1430) server.run(port=1430) ``` -------------------------------- ### Get Account Balance Source: https://context7.com/shidenggui/easytrader/llms.txt Retrieve account balance, total assets, and available funds. The return format differs between standard clients and miniqmt. ```python import easytrader user = easytrader.use('ht_client') user.prepare(user='username', password='password', comm_password='communication_password') # Get balance information balance = user.balance print(balance) # Example return for standard clients: # [{'market_value': 21642.0, 'available_funds': 28494.21, 'currency': '0', 'total_assets': 50136.21, 'profit_loss': -90.21, 'cash_balance': 28494.21, 'account_id': 'xxx'}] # miniqmt return format: # [{'total_asset': 1000000.0, 'market_value': 400000.0, 'cash': 600000.0, 'frozen_cash': 0.0, 'account_type': 2, 'account_id': 'fund_account'}] ``` -------------------------------- ### Start Easytrader Trading Server Source: https://github.com/shidenggui/easytrader/blob/master/docs/remote.md Run the Easytrader trading server on a cloud instance. The default port is 1430. Ensure this server has a fixed IP address. ```python from easytrader import server server.run(port=1430) # Default port is 1430 ``` -------------------------------- ### Get Today's IPO Data Source: https://github.com/shidenggui/easytrader/blob/master/docs/usage.md Fetch data for Initial Public Offerings (IPOs) available for subscription today. Requires importing a utility function. ```python from easytrader.utils.stock import get_today_ipo_data get_today_ipo_data() ``` -------------------------------- ### Get Holdings Source: https://context7.com/shidenggui/easytrader/llms.txt Retrieve current stock holdings information. The return format differs between standard clients and miniqmt. ```python import easytrader user = easytrader.use('universal_client') user.connect(r'C:\\同花顺\\xiadan.exe') # Get holdings list positions = user.position print(positions) # Example return for standard clients: # [{'buy_frozen': 0, 'market': '沪A', 'sell_frozen': '0', 'current_price': 4.71, 'market_value': 10362.0, 'cost_price': 4.672, 'profit_loss': 82.79, 'current_volume': 2200, 'profit_loss_percent': '0.81%', 'shareholder_id': 'xxx', 'available_volume': 2200, 'stock_code': '601398', 'stock_name': '工商银行'}] # miniqmt return format: # [{'security': '162411', 'stock_code': '162411.SZ', 'volume': 100, 'can_use_volume': 100, 'open_price': 0.618, 'market_value': 63.8, 'frozen_volume': 0, 'avg_price': 0.618, 'account_id': '1111111111'}] ``` -------------------------------- ### user.position - Get Holdings Source: https://context7.com/shidenggui/easytrader/llms.txt Retrieve current stock holdings information for the account. ```APIDOC ## user.position - Get Holdings Get the current stock holdings information for the account. ```python import easytrader user = easytrader.use('universal_client') user.connect(r'C:\Tonghuashun\xiadan.exe') # Get holdings list positions = user.position print(positions) # Example return: # [{'buy_frozen': 0, # 'market': 'Shanghai A-share', # 'sell_frozen': '0', # 'reference_price': 4.71, # 'reference_market_value': 10362.0, # 'reference_cost_price': 4.672, # 'reference_profit_loss': 82.79, # 'current_holdings': 2200, # 'profit_loss_percentage': '0.81%', # 'shareholder_code': 'xxx', # 'stock_balance': 2200, # 'stock_available': 2200, # 'stock_code': '601398', # 'stock_name': 'ICBC'}] # miniqmt return format: # [{'security': '162411', # 'stock_code': '162411.SZ', # 'volume': 100, # 'can_use_volume': 100, # 'open_price': 0.618, # 'market_value': 63.8, # 'frozen_volume': 0, # 'avg_price': 0.618, # 'account_id': '1111111111'}] ``` ``` -------------------------------- ### Prepare for Auto-Login with Configuration File Source: https://github.com/shidenggui/easytrader/blob/master/docs/usage.md Automatically log in to the trading client using a JSON configuration file. Ensure the file is properly formatted and saved with an editor like Notepad++ or Sublime Text, not Notepad. ```python user.prepare('/path/to/your/yh_client.json') # 配置文件路径 ``` -------------------------------- ### Initialize miniqmt Client Source: https://github.com/shidenggui/easytrader/blob/master/docs/miniqmt.md Initialize the miniqmt client by specifying the trading client to use. ```python user = easytrader.use('miniqmt') ``` -------------------------------- ### user.balance - Get Fund Status Source: https://context7.com/shidenggui/easytrader/llms.txt Retrieve account fund status, including balance, total assets, and available funds. ```APIDOC ## user.balance - Get Fund Status Get the account's fund status, including balance, total assets, available funds, etc. ```python import easytrader user = easytrader.use('ht_client') user.prepare(user='username', password='password', comm_password='communication_password') # Get fund status balance = user.balance print(balance) # Example return: # [{'reference_market_value': 21642.0, # 'available_funds': 28494.21, # 'currency': '0', # 'total_assets': 50136.21, # 'stock_reference_profit_loss': -90.21, # 'fund_balance': 28494.21, # 'fund_account': 'xxx'}] # miniqmt return format: # [{'total_asset': 1000000.0, # 'market_value': 400000.0, # 'cash': 600000.0, # 'frozen_cash': 0.0, # 'account_type': 2, # 'account_id': 'fund_account'}] ``` ``` -------------------------------- ### user.prepare() - Auto-Login Client Source: https://context7.com/shidenggui/easytrader/llms.txt Automatically log in to the trading client using configuration files or parameters. ```APIDOC ## user.prepare() - Auto-Login Client Automatically log in to the trading client through configuration files or parameters. ```python import easytrader # Method 1: Log in using function parameters (recommended) user = easytrader.use('ht_client') user.prepare( user='username', password='plain_password', comm_password='Huatai communication password' # Not required for other brokers ) # Method 2: Log in using a configuration file user = easytrader.use('gj_client') user.prepare('/path/to/config.json') # Configuration file format (Galaxy/Guojin client): # { # "user": "username", # "password": "plain_password" # } # Configuration file format (Huatai client): # { # "user": "Huatai username", # "password": "Huatai plain password", # "comm_password": "Huatai communication password" # } # Configuration file format (Xueqiu): # { # "cookies": "Xueqiu cookies", # "portfolio_code": "ZH818559", # "portfolio_market": "cn" # } # Xueqiu portfolio login example xq_user = easytrader.use('xq') xq_user.prepare( cookies='Xueqiu login cookies', portfolio_code='ZH818559', portfolio_market='cn' # cn/us/hk ) ``` ``` -------------------------------- ### Client Initialization Source: https://github.com/shidenggui/easytrader/blob/master/docs/usage.md Initialize and select the trading client type. ```APIDOC ## Client Initialization ### Description Initialize and select the trading client type. ### Code Examples **Import library:** ```python import easytrader ``` **Select client type:** - **Universal Ths Client:** ```python user = easytrader.use('universal_client') ``` *Note: This is a fallback for when brokers don't provide their own Ths client.* - **Broker-Specific Ths Client:** ```python user = easytrader.use('ths') ``` *Note: These are modified Ths versions provided by specific brokers.* - **Xueqiu Combination:** ```python user = easytrader.use('xq') ``` - **GuoJin Client:** ```python user = easytrader.use('gj_client') ``` - **Haitong Client:** ```python user = easytrader.use('htzq_client') ``` - **Huatai Client:** ```python user = easytrader.use('ht_client') ``` ``` -------------------------------- ### Use Haitong Client Source: https://github.com/shidenggui/easytrader/blob/master/docs/usage.md Initialize the easytrader client for Haitong Securities client. ```python user = easytrader.use('htzq_client') ``` -------------------------------- ### Use Xueqiu Client Source: https://github.com/shidenggui/easytrader/blob/master/docs/usage.md Initialize the easytrader client for Xueqiu (Snowball) platform. ```python user = easytrader.use('xq') ``` -------------------------------- ### Get Stock Holdings Source: https://github.com/shidenggui/easytrader/blob/master/docs/miniqmt.md Fetch details of your current stock positions, including security identifiers, volume, average purchase price, and market value. This helps in tracking your portfolio. ```python user.position ``` -------------------------------- ### Initialize JoinQuant/RiceQuant Follower Source: https://github.com/shidenggui/easytrader/blob/master/docs/follow.md Initializes a follower to track strategies from JoinQuant or RiceQuant. Specify the target platform ('jq' or 'rq') and log in with your credentials. ```python target = 'jq' # joinquant target = 'rq' # ricequant follower = easytrader.follower(target) follower.login(user='rq/jq用户名', password='rq/jq密码') ``` -------------------------------- ### Adjust Portfolio Weight Source: https://github.com/shidenggui/easytrader/blob/master/docs/usage.md Adjust the weight of a specific stock within a portfolio to a target percentage. For example, setting '000001' to 10% adjusts Ping An Bank's holding proportion. ```python user.adjust_weight('股票代码', 目标比例) ``` -------------------------------- ### Strategy Tracker with Easytrader Source: https://context7.com/shidenggui/easytrader/llms.txt Create a strategy tracker to follow simulated trading signals from platforms like Juwan, Miqiu, or Xueqiu. This involves initializing a trading account and then setting up the follower for a specific platform. ```python import easytrader # 1. 初始化交易账户 xq_user = easytrader.use('xq') xq_user.prepare( cookies='雪球cookies', portfolio_code='ZH818559', portfolio_market='cn' ) # 2. 创建聚宽策略跟踪器 jq_follower = easytrader.follower('jq') # 或 'joinquant', '聚宽' jq_follower.login(user='聚宽用户名', password='聚宽密码') ``` -------------------------------- ### Use Ths Client for Specific Brokers Source: https://github.com/shidenggui/easytrader/blob/master/docs/usage.md Use a Ths client tailored for a specific broker. Examples include specialized versions provided by brokers like Galaxy or Guojin Securities. ```python user = easytrader.use('ths') ``` -------------------------------- ### Use Guojin Client Source: https://github.com/shidenggui/easytrader/blob/master/docs/usage.md Initialize the easytrader client for Guojin Securities client. ```python user = easytrader.use('gj_client') ``` -------------------------------- ### Configure Grid and Refresh Strategies Source: https://context7.com/shidenggui/easytrader/llms.txt Customize data acquisition and refresh strategies for different broker clients. This includes setting alternative grid strategies like Xls for clients that don't support clipboard, custom temporary folders, and using toolbar refresh buttons. ```python import easytrader from easytrader import grid_strategies, refresh_strategies user = easytrader.use('universal_client') user.connect(r'C:\同花顺\xiadan.exe') # 某些同花顺客户端不允许剪切板拷贝 Grid 数据 # 可以使用 Xls 策略(将数据存为文件再读取) user.grid_strategy = grid_strategies.Xls # 自定义临时文件目录(某些系统默认目录路径过长) user.grid_strategy_instance.tmp_folder = 'C:\\custom_folder' # 使用工具栏刷新按钮刷新数据(比菜单切换更快) user.refresh_strategy = refresh_strategies.Toolbar(refresh_btn_index=4) # 手动刷新数据 user.refresh() # 某些客户端无法通过默认方法输入文本 # 可以开启 type_keys 方式绕过 user.enable_type_keys_for_editor() # 退出客户端 user.exit() ``` -------------------------------- ### Get Account Balance Source: https://github.com/shidenggui/easytrader/blob/master/docs/miniqmt.md Retrieve the current financial status of your trading account, including total assets, market value, and available cash. This is useful for monitoring your account's performance. ```python user.balance ``` -------------------------------- ### Use Huatai Client Source: https://github.com/shidenggui/easytrader/blob/master/docs/usage.md Initialize the easytrader client for Huatai Securities client. ```python user = easytrader.use('ht_client') ``` -------------------------------- ### Import easytrader Source: https://github.com/shidenggui/easytrader/blob/master/docs/miniqmt.md Import the easytrader library to begin using its functionalities. ```python import easytrader ``` -------------------------------- ### Initialize Xueqiu Follower Source: https://github.com/shidenggui/easytrader/blob/master/docs/follow.md Initializes a follower specifically for tracking Xueqiu portfolios. Requires login using Xueqiu cookies. ```python xq_follower = easytrader.follower('xq') xq_follower.login(cookies='雪球 cookies,登陆后获取,获取方式见 https://smalltool.github.io/2016/08/02/cookie/') ``` -------------------------------- ### Prepare for Auto-Login with Parameters Source: https://github.com/shidenggui/easytrader/blob/master/docs/usage.md Automatically log in to the trading client using provided user credentials. This method is recommended for most clients, excluding some Ths variants that require manual login first. ```python user.prepare(user='用户名', password='雪球、银河客户端为明文密码', comm_password='华泰通讯密码,其他券商不用') ``` -------------------------------- ### easytrader.use() - Create Broker Trading Object Source: https://context7.com/shidenggui/easytrader/llms.txt Create trading object instances based on the broker type. Supports various broker clients and Xueqiu portfolio trading. ```APIDOC ## easytrader.use() - Create Broker Trading Object Based on the broker type, create the corresponding trading object instance. Supports various broker clients and Xueqiu portfolio trading. ```python import easytrader # Create a universal Tonghuashun client trading object user = easytrader.use('universal_client') # Create other broker-specific Tonghuashun clients user = easytrader.use('ths') # Create Huatai client trading object user = easytrader.use('ht_client') # Create Guojin client trading object user = easytrader.use('gj_client') # Create Haitong client trading object user = easytrader.use('htzq_client') # Create Xueqiu portfolio trading object (set initial assets to 1 million) user = easytrader.use('xq', initial_assets=1000000) # Create miniqmt quantitative trading object user = easytrader.use('miniqmt') # Enable debug mode to view detailed logs user = easytrader.use('universal_client', debug=True) ``` ``` -------------------------------- ### user.buy() - Buy Stocks Source: https://context7.com/shidenggui/easytrader/llms.txt Place an order to buy stocks at a specified price and quantity. ```APIDOC ## user.buy() - Buy Stocks Buy stocks at a specified price and quantity. ```python import easytrader user = easytrader.use('universal_client') user.connect(r'C:\Tonghuashun\xiadan.exe') # Limit order buy: Buy Huabao Oil Gas (162411) at 0.55 yuan, quantity 100 shares result = user.buy('162411', price=0.55, amount=100) print(result) # Returns: {'entrust_no': 'xxxxxxxx'} # Xueqiu portfolio buy (by amount) xq_user = easytrader.use('xq') xq_user.prepare(cookies='xxx', portfolio_code='ZH818559', portfolio_market='cn') result = xq_user.buy('600036', price=35.5, amount=100, volume=3550) # The 'volume' parameter indicates the total purchase amount ``` ``` -------------------------------- ### Create Brokerage Trading Object Source: https://context7.com/shidenggui/easytrader/llms.txt Use `easytrader.use()` to create a trading object for different brokerage clients or Xueqiu portfolios. Debug mode can be enabled by passing `debug=True`. ```python import easytrader # Create a universal HZ client trading object user = easytrader.use('universal_client') # Create a specific HZ client trading object user = easytrader.use('ths') # Create a Huatai client trading object user = easytrader.use('ht_client') # Create a Guojin client trading object user = easytrader.use('gj_client') # Create a Haitong client trading object user = easytrader.use('htzq_client') # Create a Xueqiu portfolio trading object (initial assets 1 million) user = easytrader.use('xq', initial_assets=1000000) # Create a miniqmt quantitative trading object user = easytrader.use('miniqmt') # Enable debug mode for detailed logs user = easytrader.use('universal_client', debug=True) ``` -------------------------------- ### Connect Follower to Trader for JoinQuant Source: https://github.com/shidenggui/easytrader/blob/master/docs/follow.md Connects the follower to the trader and specifies the JoinQuant simulation trading URL. The URL should point to a page where positions and trade records can be viewed. By default, only signals within 120 seconds are processed. ```python follower.follow(xq_user, 'jq的模拟交易url') ``` -------------------------------- ### Configuration File Issues Source: https://github.com/shidenggui/easytrader/blob/master/docs/usage.md Troubleshooting JSON decoding errors when using configuration files. ```APIDOC ## Configuration File Issues ### Description Troubleshooting JSON decoding errors when using configuration files. ### JSONDecodeError: Expecting value This error often occurs if you edit the JSON configuration file with Notepad. **Recommendation:** Use a more advanced text editor like [Notepad++](https://notepad-plus-plus.org/zh/) or [Sublime Text](http://www.sublimetext.com/) to edit JSON files. ``` -------------------------------- ### Track Multiple Users and Strategies Source: https://github.com/shidenggui/easytrader/blob/master/docs/follow.md Allows tracking multiple users and strategies simultaneously by providing lists for users, strategies, and their corresponding total assets. ```python follower.follow(users=[xq_user, yh_user], strategies=['组合1', '组合2'], total_assets=[10000, 10000]) ``` -------------------------------- ### Track Joinquant Strategy Source: https://context7.com/shidenggui/easytrader/llms.txt Follow a strategy from Joinquant by providing the user object, strategy URL, and optional parameters for command expiration and duplicate execution prevention. ```python jq_follower.follow( xq_user, 'https://www.joinquant.com/algorithm/live/index?backtestId=xxx', trade_cmd_expire_seconds=120, # 信号过期时间 cmd_cache=True # 防止重复执行 ) ``` -------------------------------- ### Connect to Remote Easytrader Server from Strategy Client Source: https://github.com/shidenggui/easytrader/blob/master/docs/remote.md Connect to the remote Easytrader trading server from your quantitative strategy platform. Specify the client type, server host IP, and port. This client can then be used to place buy and sell orders. ```python from easytrader import remoteclient user = remoteclient.use('Client type to use, optional: yh_client, ht_client, ths, xq, etc.', host='Server IP', port='Server port, default is 1430') user.buy(......) user.sell(......) ``` -------------------------------- ### Client Connection and Login Source: https://github.com/shidenggui/easytrader/blob/master/docs/usage.md Connect to and log in to the trading client. ```APIDOC ## Client Connection and Login ### Description Connect to and log in to the trading client. ### Methods **1. For Broker-Specific Ths Clients:** - These clients do not support automatic login. You must manually open and log in to the client first, then use the `connect` function. ```python user.connect(r'path/to/your/client/xiadan.exe') # e.g., r'C:\htzqzyb2\xiadan.exe' ``` **2. For Universal Ths Clients:** - Manual login is required once. Add your broker, enter your account number, password, and verification code, and check 'Save Password'. - After the first login, subsequent logins can be automated using `prepare` (requires account number and client path; password can be arbitrary). **3. For Other Clients (Non-Ths):** - Use the `prepare` function for automatic login. - Parameters for `prepare` can be provided via function arguments or a configuration file. **a. Function Arguments (Recommended):** ```python user.prepare(user='your_username', password='your_password', comm_password='huatai_communication_password') ``` *Note: `comm_password` is only needed for Huatai clients.* **b. Configuration File:** ```python user.prepare('/path/to/your/config.json') ``` *Note: Create this JSON file yourself using an editor like Notepad++ or Sublime Text. Do not use Notepad.* **Configuration File Formats:** - **Galaxy/GuoJin Client:** ```json { "user": "your_username", "password": "your_plain_text_password" } ``` - **Huatai Client:** ```json { "user": "huatai_username", "password": "huatai_plain_text_password", "comm_password": "huatai_communication_password" } ``` - **Xueqiu:** ```json { "cookies": "your_xueqiu_cookies", "portfolio_code": "your_portfolio_code", "portfolio_market": "market_type (e.g., us, cn, hk)" } ``` ``` -------------------------------- ### miniQMT Custom Callbacks Source: https://context7.com/shidenggui/easytrader/llms.txt Demonstrates how to create and use custom callback handlers for asynchronous event processing in the miniQMT interface. ```APIDOC ## miniQMT Custom Callbacks ### Description This section explains how to implement custom callback handlers for the miniQMT interface to process asynchronous events such as connection status changes, account updates, order status changes, trade executions, and errors. By inheriting from `XtQuantTraderCallback` and overriding its methods, you can define specific actions to be taken upon receiving these events. ### Method N/A (Callback mechanism) ### Endpoint N/A ### Parameters #### Callback Handler Class - **MyTraderCallback**: A custom class inheriting from `xtquant.xttrader.XtQuantTraderCallback`. - **on_disconnected()**: Called when the connection to the QMT client is lost. - **on_account_status(status)**: Called when account status information is received. - **on_stock_order(order)**: Called when an order's status is updated. - **on_stock_trade(trade)**: Called when a trade execution occurs. - **on_order_error(order_error)**: Called when an order placement fails. - **on_cancel_error(cancel_error)**: Called when an order cancellation fails. #### Connection Parameter - **trader_callback** (object) - When connecting, pass an instance of your custom callback class. ### Request Example ```python import easytrader from xtquant.xttrader import XtQuantTraderCallback # Define a custom callback handler class MyTraderCallback(XtQuantTraderCallback): def on_disconnected(self): print("Connection disconnected") def on_account_status(self, status): print(f"Account status: {status.account_id}, Status: {status.status}") def on_stock_order(self, order): print(f"Order callback: {order.stock_code}, Status: {order.order_status}") def on_stock_trade(self, trade): print(f"Trade callback: {trade.stock_code}, Price: {trade.traded_price}, Volume: {trade.traded_volume}") def on_order_error(self, order_error): print(f"Order placement failed: {order_error.order_id}, Error: {order_error.error_msg}") def on_cancel_error(self, cancel_error): print(f"Order cancellation failed: {cancel_error.order_id}, Error: {cancel_error.error_msg}") # Initialize and connect with the custom callback user = easytrader.use('miniqmt') user.connect( miniqmt_path=r"D:\\国金证券QMT交易端\\userdata_mini", stock_account="你的资金账号", trader_callback=MyTraderCallback() ) # Placing an order will now trigger the corresponding callbacks user.buy('600036', price=35.5, amount=100) ``` ### Response N/A (Callbacks are event-driven and do not return direct responses to the caller. Actions are performed within the callback methods.) ``` -------------------------------- ### Track with Market Orders Source: https://context7.com/shidenggui/easytrader/llms.txt Follow a strategy using market orders by specifying the user, portfolio code, and setting entrust_prop to 'market'. ```python follower.follow(xq_user, 'ZH123456', entrust_prop='market') ``` -------------------------------- ### Configuration File Format for Galaxy/Guojin Client Source: https://github.com/shidenggui/easytrader/blob/master/docs/usage.md JSON configuration file format for Galaxy or Guojin clients, requiring username and password. ```json { "user": "用户名", "password": "明文密码" } ``` -------------------------------- ### Track Ricequant Strategy Source: https://context7.com/shidenggui/easytrader/llms.txt Follow a strategy from Ricequant by logging in with your Ricequant credentials and providing the user object and strategy run ID. ```python rq_follower = easytrader.follower('rq') # 或 'ricequant', '米筐' rq_follower.login(user='米筐用户名', password='米筐密码') rq_follower.follow(xq_user, run_id='策略ID') ``` -------------------------------- ### Buy Stocks Source: https://context7.com/shidenggui/easytrader/llms.txt Place a buy order for stocks at a specified price and quantity. Xueqiu portfolios support buying by total amount using the `volume` parameter. ```python import easytrader user = easytrader.use('universal_client') user.connect(r'C:\\同花顺\\xiadan.exe') # Limit order buy: Buy 100 shares of Huabao Oil (162411) at 0.55 yuan result = user.buy('162411', price=0.55, amount=100) print(result) # Returns: {'entrust_no': 'xxxxxxxx'} # Xueqiu portfolio buy (by amount) xq_user = easytrader.use('xq') xq_user.prepare(cookies='xxx', portfolio_code='ZH818559', portfolio_market='cn') result = xq_user.buy('600036', price=35.5, amount=100, volume=3550) # The 'volume' parameter represents the total purchase amount ``` -------------------------------- ### Connect to HZ Client Source: https://context7.com/shidenggui/easytrader/llms.txt Connect to a manually logged-in HZ client. This is typically used for brokerage clients that require manual login before connecting. ```python import easytrader # Create a trading object user = easytrader.use('ths') # Connect to the client after manual login user.connect(r'C:\htzqzyb2\xiadan.exe') # After successful connection, trading operations can be performed print(user.balance) ``` -------------------------------- ### Place Buy Order Source: https://github.com/shidenggui/easytrader/blob/master/docs/usage.md Place a buy order for a specific stock. Requires stock code, price, and amount. The return value indicates the order status. ```python user.buy('162411', price=0.55, amount=100) ``` -------------------------------- ### user.sell() - Sell Stocks Source: https://context7.com/shidenggui/easytrader/llms.txt Place an order to sell stocks at a specified price and quantity. ```APIDOC ## user.sell() - Sell Stocks Sell stocks at a specified price and quantity. ```python import easytrader user = easytrader.use('ht_client') user.prepare(user='username', password='password', comm_password='communication_password') # Limit order sell: Sell Huabao Oil Gas (162411) at 0.60 yuan, quantity 100 shares result = user.sell('162411', price=0.60, amount=100) print(result) # Returns: {'entrust_no': 'xxxxxxxx'} # Check sell result if 'entrust_no' in result: print(f"Sell order successful, entrust number: {result['entrust_no']}") ``` ``` -------------------------------- ### easytrader.follower() - Strategy Follower Source: https://context7.com/shidenggui/easytrader/llms.txt Creates a strategy follower to track simulated trading signals from platforms like Xueqiu, JoinQuant, or MiKuang. ```APIDOC ## easytrader.follower() - Strategy Follower ### Description Initializes a strategy follower object that can track simulated trading signals from various platforms. This allows users to replicate trading strategies executed on these platforms within EasyTrader. ### Method Factory function ### Endpoint N/A ### Parameters #### `easytrader.follower(platform_name)` - **platform_name** (string) - Required - The name of the platform to follow (e.g., 'jq', 'joinquant', '聚宽', 'xq', 'xueqiu', '雪球', 'mk', 'mikuan', '米筐'). ### Available Methods on Follower Object - **login(** `user`, `password` **)**: Logs into the specified platform (required for platforms like JoinQuant). ### Request Example ```python import easytrader # 1. Initialize a trading account (e.g., Xueqiu) xq_user = easytrader.use('xq') xq_user.prepare( cookies='雪球cookies', portfolio_code='ZH818559', portfolio_market='cn' ) # 2. Create a JoinQuant strategy follower jq_follower = easytrader.follower('jq') # or 'joinquant', '聚宽' jq_follower.login(user='聚宽用户名', password='聚宽密码') # Further operations would involve using the follower object to interact with signals ``` ### Response N/A (This is a client-side initialization function.) ``` -------------------------------- ### Trade with MiniQMT Quant Interface Source: https://context7.com/shidenggui/easytrader/llms.txt Utilize the official MiniQMT quantitative trading interface provided by brokers. Supports connecting to the QMT client, querying balances and positions, and executing various order types. ```python import easytrader # 创建 miniqmt 交易对象 user = easytrader.use('miniqmt') # 连接 QMT 客户端(需先登录 QMT 并勾选极简模式) user.connect( miniqmt_path=r"D:\国金证券QMT交易端\userdata_mini", stock_account="你的资金账号" ) # 获取资金状况 print(user.balance) # [{'total_asset': 1000000.0, 'market_value': 400000.0, 'cash': 600000.0, ...}] # 获取持仓 print(user.position) # 限价买入 result = user.buy('600036', price=35.5, amount=100) print(result) # {'entrust_no': 123456} # 限价卖出 result = user.sell('600036', price=36.0, amount=100) # 市价买入 result = user.market_buy('600036', amount=100, ttype='对手方最优价格委托') # 市价卖出 result = user.market_sell('000001', amount=100, ttype='最优五档即时成交剩余撤销') # 撤单 result = user.cancel_entrust(123456) print(result) # {'success': True, 'message': 'success'} # 查询当日委托 print(user.today_entrusts) # 查询当日成交 print(user.today_trades) # 获取原始交易对象(高级用法) trader = user.trader # XtQuantTrader 对象 account = user.account # StockAccount 对象 ``` -------------------------------- ### Connect Xueqiu Follower to Trader Source: https://github.com/shidenggui/easytrader/blob/master/docs/follow.md Connects the Xueqiu follower to the trader, specifying the Xueqiu portfolio ID and total assets. Xueqiu uses percentage-based adjustments, so total assets must be set. ```python xq_follower.follow(xq_user, 'xq组合ID,类似ZH123456', total_assets=100000) ``` -------------------------------- ### Use Xls Grid Strategy Source: https://github.com/shidenggui/easytrader/blob/master/docs/usage.md Configure the grid data retrieval strategy to use XLS files. This is a workaround for clients that do not allow clipboard access for grid data. ```python from easytrader import grid_strategies user.grid_strategy = grid_strategies.Xls ``` -------------------------------- ### Automated IPO Subscription with Easytrader Source: https://context7.com/shidenggui/easytrader/llms.txt Automatically subscribe to new stocks available for IPO on the current day. Requires prior retrieval of IPO data. ```python import easytrader from easytrader.utils.stock import get_today_ipo_data user = easytrader.use('universal_client') user.connect(r'C:\同花顺\xiadan.exe') # 查询今日可申购新股 ipo_data = get_today_ipo_data() print(ipo_data) # 返回示例: # [{'stock_code': '股票代码', # 'stock_name': '股票名称', # 'price': 发行价, # 'apply_code': '申购代码'}] # 一键申购所有新股 result = user.auto_ipo() print(result) # 返回: {'message': 'success'} 或 {'message': '今日无新股'} ``` -------------------------------- ### Configuration File Format for Xueqiu Source: https://github.com/shidenggui/easytrader/blob/master/docs/usage.md JSON configuration file format for Xueqiu, requiring cookies, portfolio code, and market. ```json { "cookies": "雪球 cookies,登陆后获取,获取方式见 https://smalltool.github.io/2016/08/02/cookie/", "portfolio_code": "组合代码(例:ZH818559)", "portfolio_market": "交易市场(例:us 或者 cn 或者 hk)" } ``` -------------------------------- ### Connect to Ths Client Source: https://github.com/shidenggui/easytrader/blob/master/docs/usage.md Connect to a specific broker's Ths client after manually logging in. Provide the path to the trading executable. ```python user.connect(r'客户端xiadan.exe路径') # 类似 r'C:\htzqzyb2\xiadan.exe' ``` -------------------------------- ### Use Toolbar Refresh Strategy Source: https://github.com/shidenggui/easytrader/blob/master/docs/usage.md Configure the data refresh strategy to use the toolbar's refresh button. This can be faster than menu-based refreshing, but the button index may need adjustment. ```python from easytrader import refresh_strategies # refresh_btn_index 指的是刷新按钮在工具栏的排序,默认为第四个,根据客户端实际情况调整 user.refresh_strategy = refresh_strategies.Toolbar(refresh_btn_index=4) ``` -------------------------------- ### Auto-Login Client Source: https://context7.com/shidenggui/easytrader/llms.txt Automatically log in to the trading client using configuration files or function parameters. The configuration file format varies by brokerage. ```python import easytrader # Method 1: Login using function parameters (recommended) user = easytrader.use('ht_client') user.prepare( user='username', password='plain_password', comm_password='Huatai_communication_password' # Not required for other brokerages ) # Method 2: Login using a configuration file user = easytrader.use('gj_client') user.prepare('/path/to/config.json') # Configuration file format (Yinhe/Guojin client): # { # "user": "username", # "password": "plain_password" # } # Configuration file format (Huatai client): # { # "user": "Huatai_username", # "password": "Huatai_plain_password", # "comm_password": "Huatai_communication_password" # } # Configuration file format (Xueqiu): # { # "cookies": "Xueqiu_login_cookies", # "portfolio_code": "ZH818559", # "portfolio_market": "cn" # } # Xueqiu portfolio login example xq_user = easytrader.use('xq') xq_user.prepare( cookies='Xueqiu_login_cookies', portfolio_code='ZH818559', portfolio_market='cn' # cn/us/hk ) ``` -------------------------------- ### Advanced Configurations Source: https://github.com/shidenggui/easytrader/blob/master/docs/usage.md Advanced settings for grid data strategies and refresh methods. ```APIDOC ## Advanced Configurations ### Description Advanced settings for grid data strategies and refresh methods. ### Grid Data Strategy (XLS) If certain Ths clients prevent clipboard access for grid data, use the XLS strategy: ```python from easytrader import grid_strategies user.grid_strategy = grid_strategies.Xls ``` ### Refresh Strategy (Toolbar Button) To speed up data refresh, use the toolbar refresh button strategy: ```python from easytrader import refresh_strategies # refresh_btn_index is the position of the refresh button in the toolbar (default is 4) user.refresh_strategy = refresh_strategies.Toolbar(refresh_btn_index=4) ``` ### Custom Temporary Folder for XLS Strategy If the system's default temporary folder path is too long for XLS strategy: ```python user.grid_strategy_instance.tmp_folder = 'C:\\custom_folder' ``` ### Disable Debug Log Output ```python user = easytrader.use('yh', debug=False) ``` ``` -------------------------------- ### Place Sell Order Source: https://github.com/shidenggui/easytrader/blob/master/docs/usage.md Place a sell order for a specific stock. Requires stock code, price, and amount. The return value indicates the order status. ```python user.sell('162411', price=0.55, amount=100) ``` -------------------------------- ### Multi-User Multi-Strategy Tracking Source: https://context7.com/shidenggui/easytrader/llms.txt Track multiple strategies for multiple users simultaneously. Specify lists of users, strategies, and corresponding total assets, along with optional slippage and order interval. ```python follower.follow( users=[xq_user, yh_user], strategies=['组合1', '组合2'], total_assets=[10000, 10000], slippage=0.05, # 5%滑点 send_interval=30 # 下单间隔30秒 ) ``` -------------------------------- ### Configuration File Format for Huatai Client Source: https://github.com/shidenggui/easytrader/blob/master/docs/usage.md JSON configuration file format for Huatai clients, including username, password, and communication password. ```json { "user": "华泰用户名", "password": "华泰明文密码", "comm_password": "华泰通讯密码" } ``` -------------------------------- ### Custom Callback Handler for MiniQMT Source: https://context7.com/shidenggui/easytrader/llms.txt Implement custom callback handlers for MiniQMT to process order and trade events asynchronously. This allows for real-time event handling like connection status, account updates, order confirmations, and errors. ```python import easytrader from xtquant.xttrader import XtQuantTraderCallback class MyTraderCallback(XtQuantTraderCallback): def on_disconnected(self): print("连接断开") def on_account_status(self, status): print(f"账户状态: {status.account_id}, 状态: {status.status}") def on_stock_order(self, order): print(f"委托回调: {order.stock_code}, 状态: {order.order_status}") def on_stock_trade(self, trade): print(f"成交回调: {trade.stock_code}, 价格: {trade.traded_price}, 数量: {trade.traded_volume}") def on_order_error(self, order_error): print(f"下单失败: {order_error.order_id}, 错误: {order_error.error_msg}") def on_cancel_error(self, cancel_error): print(f"撤单失败: {cancel_error.order_id}, 错误: {cancel_error.error_msg}") # 使用自定义回调连接 user = easytrader.use('miniqmt') user.connect( miniqmt_path=r"D:\国金证券QMT交易端\userdata_mini", stock_account="你的资金账号", trader_callback=MyTraderCallback() ) # 下单后会触发相应的回调 user.buy('600036', price=35.5, amount=100) ``` -------------------------------- ### user.auto_ipo() - Auto IPO Subscription Source: https://context7.com/shidenggui/easytrader/llms.txt Automatically subscribes to new stocks available for IPO on the current day. ```APIDOC ## POST /api/user/auto_ipo ### Description Automatically subscribes to all new stocks available for IPO on the current trading day. It first retrieves the IPO data and then attempts to subscribe. ### Method POST ### Endpoint /api/user/auto_ipo ### Parameters None ### Request Example ```python import easytrader from easytrader.utils.stock import get_today_ipo_data user = easytrader.use('universal_client') user.connect(r'C:\同花顺\xiadan.exe') # Query today's IPO data ipo_data = get_today_ipo_data() print(ipo_data) # Automatically subscribe to all new stocks result = user.auto_ipo() print(result) ``` ### Response #### Success Response (200) - **message** (string) - Indicates the status of the IPO subscription, e.g., 'success' or '今日无新股' (No new stocks today). #### Response Example ```json { "message": "success" } ``` ``` -------------------------------- ### Upgrade EasyTrader using pip Source: https://github.com/shidenggui/easytrader/blob/master/docs/install.md Use this command to upgrade to the latest version of the EasyTrader library. The -U flag ensures an upgrade. ```shell pip install easytrader -U ``` -------------------------------- ### Use Universal Ths Client Source: https://github.com/shidenggui/easytrader/blob/master/docs/usage.md Select the universal Ths client for trading. This is a fallback option when a broker does not provide a dedicated Ths client. ```python user = easytrader.use('universal_client') ``` -------------------------------- ### Connect to Remote Easytrader Service Source: https://context7.com/shidenggui/easytrader/llms.txt Connect a strategy client to a running Easytrader remote trading service. Specify the client type, server host IP, and port. ```python from easytrader import remoteclient # 连接远程交易服务 user = remoteclient.use( 'ht_client', # 客户端类型: yh_client, ht_client, ths, xq 等 host='服务器IP', port=1430 ) # 执行交易操作(与本地模式相同) print(user.balance) print(user.position) result = user.buy('600036', price=35.5, amount=100) result = user.sell('600036', price=36.0, amount=100) ```