Market
exchange.GetRecords()
获取K线数据(OHLCV)。
语法
python
# 方式1:使用周期常量(推荐)
# 常量已自动注入,无需 import,直接使用
records = exchange.GetRecords(period=PERIOD_M5, limit=100)
# 方式2:使用标准格式字符串
records = exchange.GetRecords(period='5m', limit=100)
# 方式3:使用秒数字符串
records = exchange.GetRecords(period='300', limit=100)参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| period | str | 否 | K线周期,默认 '1m',支持多种格式(见下文) |
| limit | int | 否 | 返回数量,默认 100 |
周期格式说明
支持三种周期格式:
1. 周期常量(推荐)✨
使用预定义常量,代码可读性更好:
python
# 这些常量已自动注入到策略全局作用域,无需 import
# 就像 exchange、Log、Sleep 一样直接使用
def main():
# 可用的周期常量:
# PERIOD_M1, PERIOD_M3, PERIOD_M5, PERIOD_M15, PERIOD_M30
# PERIOD_H1, PERIOD_H2, PERIOD_H4, PERIOD_H6, PERIOD_H12
# PERIOD_D1, PERIOD_D3, PERIOD_W1
# 直接使用示例
records = exchange.GetRecords(period=PERIOD_M5, limit=100)2. 标准格式字符串
| 格式 | 说明 | 示例 |
|---|---|---|
1m | 1分钟 | exchange.GetRecords('1m', 100) |
3m | 3分钟 | exchange.GetRecords('3m', 100) |
5m | 5分钟 | exchange.GetRecords('5m', 100) |
15m | 15分钟 | exchange.GetRecords('15m', 100) |
30m | 30分钟 | exchange.GetRecords('30m', 100) |
1h | 1小时 | exchange.GetRecords('1h', 100) |
2h | 2小时 | exchange.GetRecords('2h', 100) |
4h | 4小时 | exchange.GetRecords('4h', 100) |
6h | 6小时 | exchange.GetRecords('6h', 100) |
12h | 12小时 | exchange.GetRecords('12h', 100) |
1d | 1天 | exchange.GetRecords('1d', 100) |
3d | 3天 | exchange.GetRecords('3d', 100) |
1w | 1周 | exchange.GetRecords('1w', 100) |
3. 秒数字符串(支持但不推荐)
任意秒数的字符串,系统会自动转换:
| 秒数 | 自动转换为 | 说明 |
|---|---|---|
"60" | 1m | 60秒 = 1分钟 |
"300" | 5m | 300秒 = 5分钟 |
"3600" | 1h | 3600秒 = 1小时 |
"7200" | 2h | 7200秒 = 2小时 |
"86400" | 1d | 86400秒 = 1天 |
转换规则:
- 能被86400整除 → 转为天数(如
"172800"→2d) - 能被3600整除 → 转为小时(如
"7200"→2h) - 能被60整除 → 转为分钟(如
"300"→5m) - 其他数字 → 秒数(如
"30"→30s)
返回值
返回一个列表,每个元素是一个字典,包含以下字段:
| 字段 | 类型 | 说明 |
|---|---|---|
| Time | int | 时间戳(毫秒) |
| Open | float | 开盘价 |
| High | float | 最高价 |
| Low | float | 最低价 |
| Close | float | 收盘价 |
| Volume | float | 成交量 |
周期常量详解
可用常量列表
以下常量已自动注入到策略全局作用域,无需 import,直接使用即可:
| 常量名 | 值(秒) | 周期 | 转换后 |
|---|---|---|---|
PERIOD_M1 | "60" | 1分钟 | 1m |
PERIOD_M3 | "180" | 3分钟 | 3m |
PERIOD_M5 | "300" | 5分钟 | 5m |
PERIOD_M15 | "900" | 15分钟 | 15m |
PERIOD_M30 | "1800" | 30分钟 | 30m |
PERIOD_H1 | "3600" | 1小时 | 1h |
PERIOD_H2 | "7200" | 2小时 | 2h |
PERIOD_H4 | "14400" | 4小时 | 4h |
PERIOD_H6 | "21600" | 6小时 | 6h |
PERIOD_H12 | "43200" | 12小时 | 12h |
PERIOD_D1 | "86400" | 1天 | 1d |
PERIOD_D3 | "259200" | 3天 | 3d |
PERIOD_W1 | "604800" | 1周 | 1w |
使用说明
- 自动注入:这些常量像
exchange、Log、Sleep一样是全局变量,策略启动时自动可用 - 无需导入:不需要使用
from sdk import或import - 提高可读性:
PERIOD_M5比"300"或"5m"更直观易读 - IDE支持:在支持的IDE中可以获得自动补全
优势对比
✅ 推荐:使用常量
python
# 清晰易读
records = exchange.GetRecords(period=PERIOD_M5, limit=100)
records_1h = exchange.GetRecords(period=PERIOD_H1, limit=50)
records_daily = exchange.GetRecords(period=PERIOD_D1, limit=30)❌ 不推荐:使用数字字符串
python
# 可读性差,需要计算
records = exchange.GetRecords(period="300", limit=100) # 这是几分钟?
records_1h = exchange.GetRecords(period="3600", limit=50) # 这是多久?转换原理
常量值为秒数字符串,系统自动转换为交易所API格式:
| 输入(秒) | 转换逻辑 | 输出 |
|---|---|---|
"60" | 60 ÷ 60 = 1分钟 | 1m |
"300" | 300 ÷ 60 = 5分钟 | 5m |
"3600" | 3600 ÷ 3600 = 1小时 | 1h |
"7200" | 7200 ÷ 3600 = 2小时 | 2h |
"86400" | 86400 ÷ 86400 = 1天 | 1d |
转换规则:
- 能被86400整除 → 转为天(
Xd) - 能被3600整除 → 转为小时(
Xh) - 能被60整除 → 转为分钟(
Xm) - 其他数字 → 秒(
Xs)
示例
使用周期常量(推荐方式)
python
# 周期常量已自动注入,无需 import
def main():
# 获取5分钟K线
records_5m = exchange.GetRecords(period=PERIOD_M5, limit=100)
Log(f"获取到 {len(records_5m)} 条5分钟K线")
# 获取1小时K线
records_1h = exchange.GetRecords(period=PERIOD_H1, limit=50)
Log(f"获取到 {len(records_1h)} 条1小时K线")
# 获取日线
records_daily = exchange.GetRecords(period=PERIOD_D1, limit=30)
Log(f"获取到 {len(records_daily)} 条日线")
# 获取最新K线
if len(records_5m) > 0:
latest = records_5m[-1]
Log(f"最新价格: {latest['Close']:.2f}")基础用法
python
# 获取最近100根1分钟K线
records = exchange.GetRecords('1m', 100)
latest = records[-1]
Log("最新K线:")
Log(f" 时间: {latest['Time']}")
Log(f" 开: {latest['Open']}")
Log(f" 高: {latest['High']}")
Log(f" 低: {latest['Low']}")
Log(f" 收: {latest['Close']}")
Log(f" 量: {latest['Volume']}")多周期分析
python
def analyze_multi_timeframe():
"""使用周期常量进行多周期分析"""
# 5分钟周期 - 短线信号
records_5m = exchange.GetRecords(period=PERIOD_M5, limit=100)
ma5_short = sum([r['Close'] for r in records_5m[-5:]]) / 5
ma20_short = sum([r['Close'] for r in records_5m[-20:]]) / 20
# 15分钟周期 - 中线信号
records_15m = exchange.GetRecords(period=PERIOD_M15, limit=100)
ma5_mid = sum([r['Close'] for r in records_15m[-5:]]) / 5
ma20_mid = sum([r['Close'] for r in records_15m[-20:]]) / 20
# 1小时周期 - 长线趋势
records_1h = exchange.GetRecords(period=PERIOD_H1, limit=100)
ma5_long = sum([r['Close'] for r in records_1h[-5:]]) / 5
ma20_long = sum([r['Close'] for r in records_1h[-20:]]) / 20
# 多周期共振判断
short_bullish = ma5_short > ma20_short
mid_bullish = ma5_mid > ma20_mid
long_bullish = ma5_long > ma20_long
if short_bullish and mid_bullish and long_bullish:
Log("多周期共振:多头趋势 ↑↑↑")
return "BUY"
elif not short_bullish and not mid_bullish and not long_bullish:
Log("多周期共振:空头趋势 ↓↓↓")
return "SELL"
else:
Log("多周期不一致:观望")
return "HOLD"
def main():
signal = analyze_multi_timeframe()
Log(f"交易信号: {signal}")趋势跟踪策略
python
def trend_following():
"""使用日线判断大趋势,小时线寻找入场点"""
# 使用日线判断大趋势
daily_records = exchange.GetRecords(period=PERIOD_D1, limit=30)
if len(daily_records) < 20:
return
daily_ma20 = sum([r['Close'] for r in daily_records[-20:]]) / 20
# 使用1小时线寻找入场点
hourly_records = exchange.GetRecords(period=PERIOD_H1, limit=100)
if len(hourly_records) < 20:
return
hourly_ma5 = sum([r['Close'] for r in hourly_records[-5:]]) / 5
hourly_ma20 = sum([r['Close'] for r in hourly_records[-20:]]) / 20
current_price = hourly_records[-1]['Close']
Log(f"日线MA20: {daily_ma20:.2f}")
Log(f"1小时MA5: {hourly_ma5:.2f}")
Log(f"1小时MA20: {hourly_ma20:.2f}")
Log(f"当前价格: {current_price:.2f}")
# 大趋势向上 + 小时线金叉 → 做多
if current_price > daily_ma20 and hourly_ma5 > hourly_ma20:
Log("✅ 大趋势向上 + 小时线金叉 → 做多信号")
return "BUY"
# 大趋势向下 + 小时线死叉 → 做空
elif current_price < daily_ma20 and hourly_ma5 < hourly_ma20:
Log("⚠️ 大趋势向下 + 小时线死叉 → 做空信号")
return "SELL"
else:
Log("➡️ 趋势不明确,观望")
return "HOLD"计算移动平均线
python
def calculate_ma(records, period=20):
"""计算移动平均线"""
if len(records) < period:
return None
closes = [r['Close'] for r in records[-period:]]
ma = sum(closes) / period
return ma
# 使用周期常量获取K线
records = exchange.GetRecords(period=PERIOD_H1, limit=200)
ma20 = calculate_ma(records, 20)
ma50 = calculate_ma(records, 50)
Log(f"MA20: {ma20:.2f}")
Log(f"MA50: {ma50:.2f}")
if ma20 > ma50:
Log("短期均线在长期均线上方,多头排列")
else:
Log("短期均线在长期均线下方,空头排列")识别K线形态
python
def is_bullish_engulfing(records):
"""判断是否为看涨吞没形态"""
if len(records) < 2:
return False
prev = records[-2]
curr = records[-1]
# 前一根为阴线,当前为阳线
prev_bearish = prev['Close'] < prev['Open']
curr_bullish = curr['Close'] > curr['Open']
# 当前K线实体完全吞没前一根
engulfing = (curr['Open'] < prev['Close'] and
curr['Close'] > prev['Open'])
return prev_bearish and curr_bullish and engulfing
records = exchange.GetRecords('1h', 100)
if is_bullish_engulfing(records):
Log("检测到看涨吞没形态!")计算布林带
python
def calculate_bollinger_bands(records, period=20, std_dev=2):
"""计算布林带"""
if len(records) < period:
return None, None, None
closes = [r['Close'] for r in records[-period:]]
# 计算中轨(移动平均)
middle = sum(closes) / period
# 计算标准差
variance = sum((x - middle) ** 2 for x in closes) / period
std = variance ** 0.5
# 上轨和下轨
upper = middle + (std_dev * std)
lower = middle - (std_dev * std)
return upper, middle, lower
records = exchange.GetRecords('1h', 100)
upper, middle, lower = calculate_bollinger_bands(records)
current_price = records[-1]['Close']
Log(f"当前价格: {current_price:.2f}")
Log(f"布林带上轨: {upper:.2f}")
Log(f"布林带中轨: {middle:.2f}")
Log(f"布林带下轨: {lower:.2f}")
if current_price >= upper:
Log("价格触及上轨,可能超买")
elif current_price <= lower:
Log("价格触及下轨,可能超卖")计算RSI指标
python
def calculate_rsi(records, period=14):
"""计算RSI相对强弱指标"""
if len(records) < period + 1:
return None
closes = [r['Close'] for r in records[-(period+1):]]
gains = []
losses = []
for i in range(1, len(closes)):
change = closes[i] - closes[i-1]
if change > 0:
gains.append(change)
losses.append(0)
else:
gains.append(0)
losses.append(abs(change))
avg_gain = sum(gains) / period
avg_loss = sum(losses) / period
if avg_loss == 0:
return 100
rs = avg_gain / avg_loss
rsi = 100 - (100 / (1 + rs))
return rsi
records = exchange.GetRecords('1h', 100)
rsi = calculate_rsi(records, 14)
Log(f"RSI(14): {rsi:.2f}")
if rsi > 70:
Log("RSI超过70,市场超买")
elif rsi < 30:
Log("RSI低于30,市场超卖")注意事项
- 数据延迟:当前K线可能尚未收盘,数据会持续更新
- 周期支持:不同交易所支持的周期可能略有不同
- 数量限制:部分交易所限制单次返回的K线数量
- 历史数据:某些交易所的历史数据可能不完整
python
# 推荐:检查数据有效性
records = exchange.GetRecords('1h', 100)
if len(records) < 20:
Log("K线数据不足,无法计算指标")
# 等待更多数据