TAMath transform
CEIL - 向上取整
函数说明
将数组中每个元素向上取整到最接近的整数。
语法
python
result = TA.CEIL(records)参数
| 参数名 | 类型 | 说明 |
|---|---|---|
| records | array | 数值数组 |
返回值
返回向上取整后的数组
计算方法
对输入数组的每个元素x,返回不小于x的最小整数
使用场景
- 网格交易价格计算(最常用)
- 订单数量规整
- 价格档位调整
- 止损止盈价格设定
基础示例
python
import math
def main():
# 向上取整示例
prices = [1.1, 1.5, 1.9, 2.0]
ceiled = [math.ceil(p) for p in prices]
# 结果: [2, 2, 2, 2]
# 负数向上取整
values = [-1.1, -1.5, -1.9]
ceiled_neg = [math.ceil(v) for v in values]
# 结果: [-1, -1, -1]高级应用
1. 网格交易价格设定
python
def grid_trading_prices():
ticker = exchange.GetTicker()
current_price = ticker['Last']
# 网格间距(例如100元)
grid_spacing = 100
# 向上网格价格(卖出价)
upper_grid = math.ceil(current_price / grid_spacing) * grid_spacing
# 向下网格价格(买入价)
lower_grid = math.floor(current_price / grid_spacing) * grid_spacing
Log(f"当前价格: {current_price}")
Log(f"上方网格: {upper_grid} (卖出)")
Log(f"下方网格: {lower_grid} (买入)")
return upper_grid, lower_grid2. 订单数量规整
python
def round_order_quantity():
account = exchange.GetAccount()
ticker = exchange.GetTicker()
# 可用资金的30%
amount = account['Balance'] * 0.3
# 计算可买数量
quantity = amount / ticker['Last']
# 向上取整到最小交易单位
min_unit = 0.01 # 最小0.01个
rounded_qty = math.ceil(quantity / min_unit) * min_unit
Log(f"计划买入: {rounded_qty} 个")
return rounded_qty3. 价格档位对齐
python
def align_to_price_tick():
# 某些交易所要求价格必须是特定档位的整数倍
price = 1234.56
tick_size = 0.5 # 价格档位0.5
# 向上对齐到0.5的整数倍
aligned_price = math.ceil(price / tick_size) * tick_size
# 结果: 1235.0
Log(f"原价格: {price}, 对齐后: {aligned_price}")
return aligned_price4. 动态止损价格
python
def dynamic_stop_loss():
records = exchange.GetRecords()
current_price = records[-1]['Close']
# ATR作为波动性度量
atr = TA.ATR(records, 14)[-1]
# 止损距离:2倍ATR
stop_distance = 2 * atr
# 向上取整到整数价位(更保守)
stop_loss_price = current_price - math.ceil(stop_distance)
Log(f"当前价: {current_price:.2f}")
Log(f"ATR: {atr:.2f}")
Log(f"止损价: {stop_loss_price:.2f}")
return stop_loss_price5. 分批建仓档位
python
def layered_entry_prices():
ticker = exchange.GetTicker()
current_price = ticker['Last']
# 分5档建仓,每档间隔50元
batch_spacing = 50
num_batches = 5
# 向上取整确定第一档价格
first_batch = math.ceil(current_price / batch_spacing) * batch_spacing
# 生成所有档位
entry_prices = []
for i in range(num_batches):
price = first_batch - i * batch_spacing
entry_prices.append(price)
Log("建仓价格档位:")
for i, price in enumerate(entry_prices, 1):
Log(f" 第{i}档: {price}")
return entry_prices6. 资金分配整数化
python
def allocate_capital():
account = exchange.GetAccount()
total_balance = account['Balance']
# 分配给3个策略
num_strategies = 3
allocation_per_strategy = total_balance / num_strategies
# 向上取整(确保不超分配)
# 注意:应该用floor避免超额分配
safe_allocation = math.floor(allocation_per_strategy)
Log(f"总资金: {total_balance}")
Log(f"每策略分配: {safe_allocation} (向下取整保证安全)")
return safe_allocation注意事项
- ceil(1.1) = 2, ceil(1.9) = 2, ceil(2.0) = 2
- ceil(-1.1) = -1(向上是朝0方向)
- 与floor配合使用处理价格档位
- Python中可使用
math.ceil()替代 - 金融计算中注意取整方向的风险