如何写一个函数返回当前持仓总手数 传递的参数为 多或空。
//------------------------------------------------------------------------
// 简称: GetCurrentPosition
// 名称: 获取当前多空持仓状态
// 类别: 用户函数
// 类型: 自定义函数
// 输出: 整数型(1=多单持仓,-1=空单持仓,0=无持仓;绝对值为持仓手数)
// 说明: 适配TB3所有版本,不依赖扩展函数,返回值兼顾持仓方向和手数
//------------------------------------------------------------------------
Params
// 无参数(直接遍历订单获取持仓,无需外部传入参数)
Vars
// 函数内部局部变量(仅函数内有效)
Integer i; // 订单循环索引
Integer ordType; // 订单类型(2=多单,3=空单)
Integer ordStatus; // 订单状态(3=未平仓持仓)
Integer ordLots; // 单个订单手数
Integer totalLong; // 累计多单持仓手数
Integer totalShort; // 累计空单持仓手数
Integer totalOrders; // 订单总数(缓存,提升效率)
Integer OrderCount;
Integer SELECT_BY_POS;
Integer MODE_TRADES;
Begin
// 1. 初始化变量(避免残留值影响结果)
totalLong = 0;
totalShort = 0;
totalOrders = OrderCount; // 获取当前所有交易订单总数
// 2. 遍历所有订单,统计未平仓持仓
For i = 0 To totalOrders - 1
{
// 按位置选中第i个订单(MODE_TRADES=交易订单池)
If (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
ordType = OrderType(); // 获取订单类型
ordStatus = OrderStatus();// 获取订单状态
ordLots = OrderLots(); // 获取订单手数
// 仅统计"未平仓持仓订单"(状态=3)
If (ordStatus == 3)
{
If (ordType == 2) // 2=BUY多单
{
totalLong = totalLong + ordLots;
}
Else If (ordType == 3)// 3=SELLSHORT空单
{
totalShort = totalShort + ordLots;
}
}
}
}
// 3. 返回持仓结果(兼顾方向和手数)
If (totalLong > 0)
{
Return totalLong; // 多单持仓:返回正的持仓手数(如1=1手多单)
}
Else If (totalShort > 0)
{
Return -totalShort; // 空单持仓:返回负的持仓手数(如-1=1手空单)
}
Else
{
Return 0; // 无持仓:返回0
}
End
//------------------------------------------------------------------------
// 编译版本 2025/11/25
// 版权所有 用户自定义
// 更改声明 保留函数修改权利,适配TB3所有版本
//------------------------------------------------------------------------
请优化完善以上代码逻辑或有无更简单的方法,系统帮助中关于 返回持仓的函数介绍太过简单,翻阅全部交易策略示例也没有找到相关用法
发代写板块或者投稿
当前持仓总手数,这个函数不是有么?