等级: 新手上路
- 注册:
- 2021-7-30
- 曾用名:
|
你还在费劲地向要自动获取主力合约和次主力合约吗?
我给你一个思路,那就是使用Array对象,将指定合约品种的持仓量都存入这个数组,同时使用StringArray来存储这些合约的编码、名称,因为这些是字符串类型的,在Array对象不能保存字符串,这样就有两个数组了。
一个是持仓量数组,不含合约信息,只有持仓量数据,一个是既有持仓量,又有合约信息的字符串数组,然后,你用数组对象的倒序排列,取前两个持仓量,就是主力合约和次主力合约的持仓量了......
关键的地方是......
做个循环,逐个核对含有合约信息的字符串数组,找到与持仓量前两个相同的合约,那就是你要的。
还是不会,那我直接上代码给你吧,当然,如果你连代码也看不懂,也没有关系,加我微信guotx-,我很乐意一对一告诉你是怎么玩的。
private arrCode,arrCodeStr '合约数组
Sub Application_VBAStart()
v=GetTwoCode("SQ","RB")
End Sub
'获取指定合约的主力和此主力合约
function GetTwoCode(byVal sMarket,byVal sPreCode)
if sMarket="" or sPreCode="" then
exit function
end if
set arrCode=CreateObject("Stock.Array")
set arrCodeStr=CreateObject("Stock.ArrayString")
'获取指定市场的合约个数
iCodeCount=MarketData.GetReportCount(sMarket)
'Application.msgout sMarket & "," & iCodeCount
for i=0 to iCodeCount-1
Set report1 = marketdata.GetReportDataByIndex(sMarket, i)
sCode=report1.Label
sName=report1.StockName
sKindCode=GetKindCode(report1.Label)
sMonth=Replace(sCode,sKindCode,"") '获取合约月份
if sKindCode = sPreCode and IsNumeric(sMonth) then
if cdbl(sMonth)>0 and cdbl(sMonth)<=12 then
nOpenInt=report1.OpenInt '持仓量
sCodeStr=nOpenInt & "," & sCode & "," & sName & "," & right(sName,4)
arrCode.AddBack nOpenInt
arrCodeStr.AddBack sCodeStr
end if
end if
next
arrCode.Sort(1) '降序排序
' for i=0 to arrCode.Count-1
' sItem=arrCode.GetAt(i)
' Application.MsgOut "Code:" & i+1 & "," & sItem
' next
nTop1=arrCode.GetAt(0) '获取持仓量最大的第一个合约(主力合约)
nTop2=arrCode.GetAt(1) '获取持仓量次大的合约(次主力合约)
Application.MsgOut "持仓量前二:" & nTop1 & "," & nTop2
for i=0 to arrCodeStr.Count-1
sItem=arrCodeStr.GetAt(i)
vItem=Split(sItem,",") '逗号分隔,获取数组,第一项与nTop1,nTop2对比
'Application.MsgOut vItem(0) & "," & vItem(1) & "," & vItem(2) & "," & vItem(3)
if cdbl(vItem(0))=nTop1 then
sMainCode=vItem(1)
sFirstMonth=left(vItem(3),2) & "-" & right(vItem(3),2) & "-01"
Application.MsgOut "主力合约:" & vItem(1) & "," & vItem(2) & "," & vItem(3)
end if
if cdbl(vItem(0))=nTop2 then
sNextCode=vItem(1)
sSecondMonth=left(vItem(3),2) & "-" & right(vItem(3),2) & "-01"
Application.MsgOut "次主力合约:" & vItem(1) & "," & vItem(2) & "," & vItem(3)
end if
'Application.MsgOut "Code:" & i+1 & "," & sItem
next
nMonthCount=DateDiff("m",sFirstMonth,sSecondMonth)
Application.MsgOut "主力、次主力合约相隔" & nMonthCount & "个月"
end function
'获取合约的品种代码
Function GetKindCode(sCode)
GetKindCode = ""
For i = 1 To Len(sCode)
If IsNumeric(Mid(sCode, i, 1)) Then
GetKindCode = Left(sCode, i - 1)
Exit Function
End If
Next
End Function
-------------------------------------------- |
|