TAMath ops
MAX - 最大值
TA.MAX() - 指定周期内的最大值
语法
python
result = TA.MAX(records, period)参数
| 参数 | 类型 | 说明 |
|---|---|---|
| records | array | K线数据数组 |
| period | int | 周期长度 |
返回值
返回一个数组,每个元素是对应周期内的最大收盘价。
计算方法
对于每个位置i,返回从 i-period+1 到 i 这段时间内的最大值。
使用场景
- 阻力位识别:找出近期最高价
- 突破检测:判断是否创新高
- 止损设置:基于最高价设置止损
基础示例
python
def onTick():
exchange.SetContractType("swap")
records = exchange.GetRecords()
if len(records) < 30:
return
# 计算20周期最高价
max_20 = TA.MAX(records, 20)
current_price = records[-1].Close
Log("20日最高价:", max_20[-1])
# 突破20日新高
if current_price > max_20[-2]:
Log("突破20日新高!")
exchange.SetDirection("buy")
exchange.Buy(-1, 1)高级应用
1. 唐奇安通道
python
def onTick():
records = exchange.GetRecords()
period = 20
# 上轨:N日最高价
upper = TA.MAX(records, period)
# 下轨:N日最低价
lower = TA.MIN(records, period)
current_price = records[-1].Close
# 突破上轨做多
if current_price > upper[-2]:
Log("突破上轨,做多")
exchange.SetDirection("buy")
exchange.Buy(-1, 1)
# 跌破下轨做空
elif current_price < lower[-2]:
Log("跌破下轨,做空")
exchange.SetDirection("sell")
exchange.Sell(-1, 1)2. 新高检测策略
python
def onTick():
records = exchange.GetRecords()
# 不同周期的最高价
max_20 = TA.MAX(records, 20)
max_60 = TA.MAX(records, 60)
max_120 = TA.MAX(records, 120)
current_price = records[-1].Close
# 同时创多个周期新高
new_high_count = 0
if current_price >= max_20[-1]:
new_high_count += 1
Log("创20日新高")
if current_price >= max_60[-1]:
new_high_count += 1
Log("创60日新高")
if current_price >= max_120[-1]:
new_high_count += 1
Log("创120日新高")
if new_high_count >= 2:
Log(f"同时创{new_high_count}个周期新高,强势突破")
# 强势买入
exchange.SetDirection("buy")
exchange.Buy(-1, 2)3. 回撤止损
python
# 全局变量
entry_price = None
highest_price = None
def onTick():
global entry_price, highest_price
records = exchange.GetRecords()
current_price = records[-1].Close
position = exchange.GetPosition()
if len(position) > 0 and position[0].Type == 0: # 持有多单
# 更新最高价
if highest_price is None:
highest_price = current_price
else:
highest_price = max(highest_price, current_price)
# 从最高价回撤5%止损
drawdown = (highest_price - current_price) / highest_price
if drawdown > 0.05:
Log(f"从最高价{highest_price}回撤{drawdown*100:.2f}%,止损")
exchange.SetDirection("closebuy")
exchange.Sell(-1, position[0].Amount)
entry_price = None
highest_price = None4. 强弱判断
python
def onTick():
records = exchange.GetRecords()
# 最近20日最高价
max_20 = TA.MAX(records, 20)
# 最近20日最低价
min_20 = TA.MIN(records, 20)
current_price = records[-1].Close
# 当前价格在区间中的位置(0-1)
position_ratio = (current_price - min_20[-1]) / (max_20[-1] - min_20[-1])
Log(f"价格位置: {position_ratio*100:.2f}%")
if position_ratio > 0.8:
Log("接近区间上沿,强势")
elif position_ratio < 0.2:
Log("接近区间下沿,弱势")
else:
Log("在区间中部,震荡")注意事项
- 前期数据:前period-1个数据点无法计算完整周期
- 实时更新:最新K线未完成时,最大值可能变化
- 性能考虑:长周期计算较慢