TAMath ops
SUB - 向量减法
TA.SUB() - 数组元素相减
语法
python
result = TA.SUB(array1, array2)参数
| 参数 | 类型 | 说明 |
|---|---|---|
| array1 | array | 被减数数组 |
| array2 | array | 减数数组 |
返回值
返回一个新数组,每个元素是 array1[i] - array2[i]。
计算方法
plaintext
result[i] = array1[i] - array2[i]使用场景
- 价差计算:两个资产的价格差
- 指标背离:价格与指标的差异
- 趋势强度:快慢线差值
基础示例
python
def onTick():
exchange.SetContractType("swap")
records = exchange.GetRecords()
if len(records) < 30:
return
# 计算收盘价与开盘价的差值(实体大小)
closes = [r.Close for r in records]
opens = [r.Open for r in records]
body_size = TA.SUB(closes, opens)
Log("最新K线实体:", body_size[-1])
if body_size[-1] > 0:
Log("阳线,实体大小:", body_size[-1])
else:
Log("阴线,实体大小:", abs(body_size[-1]))高级应用
1. MACD柱状图计算
python
def onTick():
records = exchange.GetRecords()
# 计算MACD
macd = TA.MACD(records, 12, 26, 9)
dif = macd[0] # DIF线
dea = macd[1] # DEA线
# 计算MACD柱 = DIF - DEA
macd_hist = TA.SUB(dif, dea)
if macd_hist[-1] > 0 and macd_hist[-2] <= 0:
Log("MACD金叉,柱状图转正")
exchange.SetDirection("buy")
exchange.Buy(-1, 1)2. 配对交易价差
python
def onTick():
# 获取两个相关资产的价格
records1 = exchange.GetRecords()
exchange.SetCurrency("ETH_USDT")
records2 = exchange.GetRecords()
closes1 = [r.Close for r in records1[-100:]]
closes2 = [r.Close for r in records2[-100:]]
# 计算价差
spread = TA.SUB(closes1, closes2)
# 计算价差均线
spread_ma = TA.MA([{'Close': s} for s in spread], 20)
spread_std = TA.STDDEV([{'Close': s} for s in spread], 20)
current_spread = spread[-1]
# 价差偏离均线超过2倍标准差
if current_spread > spread_ma[-1] + 2 * spread_std[-1]:
Log("价差过大,做空价差(买ETH,卖BTC)")
elif current_spread < spread_ma[-1] - 2 * spread_std[-1]:
Log("价差过小,做多价差(买BTC,卖ETH)")3. 趋势强度分析
python
def onTick():
records = exchange.GetRecords()
# 快慢均线
ma5 = TA.MA(records, 5)
ma20 = TA.MA(records, 20)
# 均线差值
ma_diff = TA.SUB(ma5, ma20)
# 差值百分比
ma_diff_pct = TA.DIV(ma_diff, ma20)
if ma_diff_pct[-1] > 0.05: # 快线高于慢线5%以上
Log("强势上涨趋势,差值百分比:", ma_diff_pct[-1] * 100, "%")
# 回调买入
if records[-1].Close < ma5[-1]:
exchange.SetDirection("buy")
exchange.Buy(-1, 1)
elif ma_diff_pct[-1] < -0.05: # 快线低于慢线5%以上
Log("强势下跌趋势,差值百分比:", ma_diff_pct[-1] * 100, "%")
# 反弹卖出
if records[-1].Close > ma5[-1]:
exchange.SetDirection("sell")
exchange.Sell(-1, 1)4. 价格动量
python
def onTick():
records = exchange.GetRecords()
closes = [r.Close for r in records]
# 当前价格与N日前价格的差值
period = 10
current_prices = closes[period:]
past_prices = closes[:-period]
# 价格变化
price_change = TA.SUB(current_prices, past_prices)
# 价格变化百分比
pct_change = TA.DIV(price_change, past_prices)
Log(f"过去{period}天价格变化:", pct_change[-1] * 100, "%")注意事项
- 数组长度:两个数组长度必须相同
- 顺序重要:array1 - array2 ≠ array2 - array1
- 单位一致:确保两个数组的单位相同