Pharos
Global

exit - 主动停止实盘

策略主动停止实盘运行并退出进程。

语法

python
# 主动退出
exit()

# 带原因退出
exit(reason)

参数

参数名类型必选默认值说明
reasonstring"策略主动退出"停止原因,用于记录日志

返回值

此函数不返回,调用后会停止实盘并退出进程。

示例

示例1: 基本用法

python
# 检测到严重错误,主动退出
if critical_error:
    exit("检测到严重错误,主动停止")

示例2: 达到目标收益后退出

python
def check_profit_target():
    """检查是否达到目标收益"""
    account = exchange.GetAccount()
    initial_balance = _G("initial_balance")
    
    if initial_balance is None:
        # 首次运行,记录初始余额
        _G("initial_balance", account['Balance'])
        return
    
    # 计算收益
    profit = account['Balance'] - initial_balance
    profit_rate = (profit / initial_balance) * 100
    
    Log(f"当前收益: {profit:.2f} ({profit_rate:.2f}%)")
    
    # 达到目标收益 20%,主动退出
    if profit_rate >= 20:
        Log(f"🎉 已达到目标收益 20%!")
        LogProfit(profit, f"目标收益达成")
        exit(f"已达到目标收益 {profit_rate:.2f}%,主动停止")

# 在主循环中检查
while True:
    check_profit_target()
    Sleep(60000)  # 每分钟检查一次

示例3: 错误次数过多时退出

python
error_count = 0
MAX_ERRORS = 10

while True:
    try:
        # 策略逻辑
        ticker = exchange.GetTicker()
        if ticker is None:
            error_count += 1
            Log(f"获取行情失败,错误计数: {error_count}/{MAX_ERRORS}")
            
            if error_count >= MAX_ERRORS:
                exit(f"错误次数达到 {MAX_ERRORS},主动停止")
        else:
            # 成功则重置错误计数
            error_count = 0
        
        Sleep(5000)
    except Exception as e:
        error_count += 1
        LogError(f"策略异常: {e}", exception=e)
        
        if error_count >= MAX_ERRORS:
            exit(f"异常次数达到 {MAX_ERRORS},主动停止")
        
        Sleep(5000)

示例4: 市场条件不满足时退出

python
def check_market_conditions():
    """检查市场条件"""
    ticker = exchange.GetTicker()
    
    # 检查流动性
    if ticker['Volume'] < 1000000:
        Log("⚠️ 市场流动性不足")
        exit("市场流动性不足(成交量 < 100万),停止交易")
    
    # 检查波动率
    records = exchange.GetRecords()
    if len(records) > 20:
        high = max([r['High'] for r in records[-20:]])
        low = min([r['Low'] for r in records[-20:]])
        volatility = ((high - low) / low) * 100
        
        if volatility < 1:
            Log("⚠️ 市场波动率过低")
            exit(f"市场波动率过低({volatility:.2f}%),停止交易")

# 初始化时检查
check_market_conditions()

示例5: 时间控制

python
import time
from datetime import datetime

def check_trading_time():
    """检查是否在交易时间内"""
    now = datetime.now()
    hour = now.hour
    
    # 只在工作时间运行 (9:00 - 23:00)
    if hour < 9 or hour >= 23:
        Log(f"当前时间 {hour}:00 不在交易时间内")
        exit(f"非交易时间({_D()}),停止实盘")

# 定期检查
while True:
    check_trading_time()
    
    # 策略逻辑...
    
    Sleep(3600000)  # 每小时检查一次

示例6: 账户余额低于阈值

python
def check_account_balance():
    """检查账户余额"""
    account = exchange.GetAccount()
    min_balance = 100  # 最低余额要求
    
    if account['Balance'] < min_balance:
        Log(f"❌ 账户余额不足: {account['Balance']} < {min_balance}")
        exit(f"账户余额不足({account['Balance']} USDT),停止交易")
    
    Log(f"✅ 账户余额: {account['Balance']} USDT")

# 启动时检查
check_account_balance()

示例7: 触发风控规则

python
class RiskControl:
    """风控管理"""
    def __init__(self, max_loss_rate=0.1, max_drawdown=0.15):
        self.initial_balance = None
        self.max_balance = None
        self.max_loss_rate = max_loss_rate  # 最大亏损率 10%
        self.max_drawdown = max_drawdown     # 最大回撤 15%
    
    def check(self):
        """检查风控条件"""
        account = exchange.GetAccount()
        balance = account['Balance']
        
        # 初始化
        if self.initial_balance is None:
            self.initial_balance = balance
            self.max_balance = balance
            _G("initial_balance", balance)
            Log(f"初始余额: {balance}")
            return True
        
        # 更新最高余额
        if balance > self.max_balance:
            self.max_balance = balance
        
        # 检查总亏损率
        total_loss_rate = (self.initial_balance - balance) / self.initial_balance
        if total_loss_rate > self.max_loss_rate:
            Log(f"❌ 触发止损: 总亏损率 {total_loss_rate*100:.2f}%")
            exit(f"触发止损规则(亏损率 {total_loss_rate*100:.2f}%)")
        
        # 检查回撤
        drawdown = (self.max_balance - balance) / self.max_balance
        if drawdown > self.max_drawdown:
            Log(f"❌ 触发回撤保护: 回撤 {drawdown*100:.2f}%")
            exit(f"触发回撤保护(回撤 {drawdown*100:.2f}%)")
        
        return True

# 使用风控
risk_control = RiskControl(max_loss_rate=0.1, max_drawdown=0.15)

while True:
    risk_control.check()
    # 策略逻辑...
    Sleep(60000)

示例8: 手动控制退出

python
# 通过全局变量控制退出
if _G("manual_stop"):
    Log("🛑 检测到手动停止信号")
    exit("用户手动停止")

# 在其他地方设置停止信号:
# _G("manual_stop", True)

注意事项

  1. 不可恢复: 调用 exit() 后,实盘会立即停止,进程退出,无法恢复

  2. 日志记录: 退出前会自动记录日志,原因会被保存到数据库

  3. 资源清理: 系统会自动清理资源(关闭连接等)

  4. 立即生效: 调用后会立即停止,后续代码不会执行

  5. 区别于异常:

    • exit() 是主动停止,正常退出
    • 未捕获的异常会导致策略崩溃
  6. 建议用法:

    • 达到预设目标(收益/止损)
    • 市场条件不符合要求
    • 检测到严重错误
    • 余额不足以继续交易
  7. 避免误用: 不要在临时性错误时调用,应该使用重试机制

  8. 配合 IsVirtual: 回测环境中可能需要不同的退出策略

相关 API

  • LogError - 记录错误日志
  • IsVirtual - 判断是否为回测环境
  • _G - 持久化全局变量