Global
_G()
持久化保存数据,该函数实现了一个可保存的全局字典功能。数据结构为键值对表,永久保存在托管者本地数据库文件中。
语法
python
# 设置值
_G(key, value)
# 获取值
value = _G(key)
# 删除键
_G(key, None)
# 清空所有
_G(None)
# 获取 robot_id
robot_id = _G()参数
| 参数名 | 类型 | 必选 | 默认值 | 说明 |
|---|---|---|---|---|
| key | any | 否 | - | 字符串类型,键名。传入 None 表示清空所有全局变量 |
| value | any | 否 | - | 任意可序列化类型的值。传入 None 表示删除该键,不传表示获取值 |
返回值
- 设置操作
_G(key, value): 返回True(成功) 或False(失败) - 获取操作
_G(key): 返回对应的值,键不存在时返回None - 删除操作
_G(key, None): 返回True(成功) 或False(失败) - 清空操作
_G(None): 返回True(成功) 或False(失败) - 获取 robot_id
_G(): 返回当前实盘的real_trade_id
数据持久化
- 数据存储在本地 SQLite 数据库中 (
data/logs/{real_trade_id}.db) - 策略重启后数据依然保留
- 支持存储数字、字符串、列表、字典等可 JSON 序列化的类型
示例
基本用法
python
def main():
# 设置值
_G("num", 1)
Log(_G("num")) # 输出: 1
# 更新值
_G("num", "ok")
Log(_G("num")) # 输出: "ok"
# 删除键
_G("num", None)
Log(_G("num")) # 输出: None
# 获取 robot_id
robotId = _G()
Log("实盘ID:", robotId)计数器
python
def main():
# 初始化计数器
count = _G("trade_count")
if count is None:
count = 0
while True:
ticker = exchange.GetTicker()
# 交易逻辑
if ticker['Last'] > 50000:
exchange.Buy(ticker['Last'], 0.1)
count += 1
_G("trade_count", count) # 保存计数器
Log(f"已交易 {count} 次")
Sleep(5000)保存最后价格
python
def main():
last_price = _G("last_price")
if last_price:
Log(f"上次价格: {last_price}")
while True:
ticker = exchange.GetTicker()
current_price = ticker['Last']
# 保存当前价格
_G("last_price", current_price)
# 价格变化检测
if last_price and abs(current_price - last_price) / last_price > 0.05:
Log(f"价格变化超过 5%! {last_price} -> {current_price}")
last_price = current_price
Sleep(10000)存储复杂数据结构
python
def main():
# 存储字典
config = {
"stop_loss": 0.02,
"take_profit": 0.05,
"max_position": 10
}
_G("config", config)
# 读取配置
saved_config = _G("config")
Log("止损:", saved_config['stop_loss'])
Log("止盈:", saved_config['take_profit'])
# 存储列表
prices = [50000, 51000, 52000]
_G("price_history", prices)
# 读取列表
history = _G("price_history")
Log("历史价格:", history)策略状态持久化
python
def main():
# 恢复策略状态
state = _G("strategy_state")
if state is None:
state = {
"position": 0,
"avg_price": 0,
"profit": 0,
"last_trade_time": 0
}
Log("恢复状态:", state)
while True:
ticker = exchange.GetTicker()
# 买入逻辑
if state['position'] == 0 and ticker['Last'] < 50000:
exchange.Buy(ticker['Last'], 1)
state['position'] = 1
state['avg_price'] = ticker['Last']
state['last_trade_time'] = Unix()
_G("strategy_state", state) # 保存状态
Log("建仓完成")
# 卖出逻辑
if state['position'] > 0 and ticker['Last'] > state['avg_price'] * 1.05:
exchange.Sell(ticker['Last'], state['position'])
profit = (ticker['Last'] - state['avg_price']) * state['position']
state['position'] = 0
state['profit'] += profit
_G("strategy_state", state) # 保存状态
Log(f"平仓完成,本次盈利: {profit}")
Sleep(5000)清空所有数据
python
def main():
# 保存多个键值对
_G("key1", "value1")
_G("key2", "value2")
_G("key3", "value3")
Log("key1:", _G("key1")) # 输出: value1
# 清空所有全局变量
_G(None)
Log("key1:", _G("key1")) # 输出: None
Log("key2:", _G("key2")) # 输出: None实盘重启后数据保留
python
def main():
# 第一次运行
startup_count = _G("startup_count")
if startup_count is None:
startup_count = 0
startup_count += 1
_G("startup_count", startup_count)
Log(f"策略已启动 {startup_count} 次")
# 即使策略重启,startup_count 也会保留并累加注意事项
- 数据类型: 只能存储可 JSON 序列化的数据类型(数字、字符串、列表、字典、布尔值、None)
- 数据大小: 建议单个值不要太大(< 1MB),避免影响性能
- 键名规范: 建议使用有意义的键名,避免使用特殊字符
- 并发安全: 同一个实盘的多个策略实例共享同一个数据库,注意并发问题
- 清空操作:
_G(None)会删除所有全局变量,谨慎使用
相关函数
- LogStatus() - 显示策略状态信息
- Log() - 输出日志