1. 程式人生 > >CTP Java 版(Swig)

CTP Java 版(Swig)

log export {0} ide java size_t ati parameter vat

參考文檔 感謝這個博主

https://blog.csdn.net/pjjing/article/details/53186394

https://my.oschina.net/qutterrtl/blog/1490097

https://www.cnblogs.com/ppgeneve/p/7118017.html

http://www.zhimengzhe.com/windows/156189.html


下載 api文件

下載 api文檔

安裝 VS2012

安裝Swig軟件,

用的Swig是swigwin-2.0.11版本

解壓後 配置windows 環境變量

安裝JDK,

註意要安裝32位版本,將環境變量配置好。是1.8.0_111版本

然後將你安裝jdk目錄\Java\jdk1.8.0_111\include下的jni.h和win32文件夾下的jni_md.h, jawt_md.h

一共三個文件拷貝到安裝vs的include目錄底下\Microsoft Visual Studio 12.0\VC\include。


安裝libiconv-1.9.2-1(重要 處理中文使用)

C:\Program Files (x86)\GnuWin32\*

將你安裝的libiconv目錄下文件夾\GnuWin32\include中的iconv.h文件

同樣拷貝到剛才的C++ include目錄\Microsoft Visual Studio 12.0\VC\include下。

\GnuWin32\bin文件夾下的libiconv2.dll 這個是後面要用到的


安裝Eclipse 32版



如果需要我提供可以留言




將api文件解壓

拿到 32版的

創建 c:\ctp3文件

api 放入 ctp3文件

創建 srcmd srctr 文件夾

創建 various.i,thosttraderapi.i,thostmduserapi.i三個文件

=================================================================================================

=================================================================================================

various.i:

/* -----------------------------------------------------------------------------
 * See the LICENSE file for information on copyright, usage and redistribution
 * of SWIG, and the README file for authors - http://www.swig.org/release.html.
 *
 * various.i
 *
 * SWIG Typemap library for Java.
 * Various useful typemaps.
 * ----------------------------------------------------------------------------- */
/* 
 * char **STRING_ARRAY typemaps. 
 * These typemaps are for C String arrays which are NULL terminated.
 *   char *values[] = { "one", "two", "three", NULL }; // note NULL
 * char ** is mapped to a Java String[].
 *
 * Example usage wrapping:
 *   %apply char **STRING_ARRAY { char **input };
 *   char ** foo(char **input);
 *  
 * Java usage:
 *   String numbers[] = { "one", "two", "three" };
 *   String[] ret = modulename.foo( numbers };
 */
%typemap(jni) char **STRING_ARRAY "jobjectArray"
%typemap(jtype) char **STRING_ARRAY "String[]"
%typemap(jstype) char **STRING_ARRAY "String[]"
%typemap(in) char **STRING_ARRAY (jint size) {
int i = 0;
size = JCALL1(GetArrayLength, jenv, $input);
#ifdef __cplusplus
$1 = new char*[size+1];
#else
$1 = (char **)calloc(size+1, sizeof(char *));
#endif
for (i = 0; i<size; i++) {
jstring j_string = (jstring)JCALL2(GetObjectArrayElement, jenv, $input, i);
const char *c_string = JCALL2(GetStringUTFChars, jenv, j_string, 0);
#ifdef __cplusplus
$1[i] = new char [strlen(c_string)+1];
#else
$1[i] = (char *)calloc(strlen(c_string)+1, sizeof(const char *));
#endif
strcpy($1[i], c_string);
JCALL2(ReleaseStringUTFChars, jenv, j_string, c_string);
JCALL1(DeleteLocalRef, jenv, j_string);
}
$1[i] = 0;
}
%typemap(freearg) char **STRING_ARRAY {
int i;
for (i=0; i<size$argnum-1; i++)
#ifdef __cplusplus
  delete[] $1[i];
delete[] $1;
#else
  free($1[i]);
free($1);
#endif
}
%typemap(out) char **STRING_ARRAY {
int i;
int len=0;
jstring temp_string;
const jclass clazz = JCALL1(FindClass, jenv, "java/lang/String");
while ($1[len]) len++;    
jresult = JCALL3(NewObjectArray, jenv, len, clazz, NULL);
/* exception checking omitted */
for (i=0; i<len; i++) {
  temp_string = JCALL1(NewStringUTF, jenv, *result++);
  JCALL3(SetObjectArrayElement, jenv, jresult, i, temp_string);
  JCALL1(DeleteLocalRef, jenv, temp_string);
}
}
%typemap(javain) char **STRING_ARRAY "$javainput"
%typemap(javaout) char **STRING_ARRAY  {
return $jnicall;
  }
/* 
 * char **STRING_OUT typemaps. 
 * These are typemaps for returning strings when using a C char ** parameter type.
 * The returned string appears in the 1st element of the passed in Java String array.
 *
 * Example usage wrapping:
 *   void foo(char **string_out);
 *  
 * Java usage:
 *   String stringOutArray[] = { "" };
 *   modulename.foo(stringOutArray);
 *   System.out.println( stringOutArray[0] );
 */
%typemap(jni) char **STRING_OUT "jobjectArray"
%typemap(jtype) char **STRING_OUT "String[]"
%typemap(jstype) char **STRING_OUT "String[]"
%typemap(javain) char **STRING_OUT "$javainput"
%typemap(in) char **STRING_OUT($*1_ltype temp) {
  if (!$input) {
SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "array null");
return $null;
  }
  if (JCALL1(GetArrayLength, jenv, $input) == 0) {
SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array must contain at least 1 element");
return $null;
  }
  $1 = &temp; 
}
%typemap(argout) char **STRING_OUT {
  jstring jnewstring = NULL;
  if($1) {
 jnewstring = JCALL1(NewStringUTF, jenv, *$1);
  }
  JCALL3(SetObjectArrayElement, jenv, $input, 0, jnewstring); 
}
/* 
 * char *BYTE typemaps. 
 * These are input typemaps for mapping a Java byte[] array to a C char array.
 * Note that as a Java array is used and thus passeed by reference, the C routine 
 * can return data to Java via the parameter.
 *
 * Example usage wrapping:
 *   void foo(char *array);
 *  
 * Java usage:
 *   byte b[] = new byte[20];
 *   modulename.foo(b);
 */
%typemap(jni) char *BYTE "jbyteArray"
%typemap(jtype) char *BYTE "byte[]"
%typemap(jstype) char *BYTE "byte[]"
%typemap(in) char *BYTE {
$1 = (char *) JCALL2(GetByteArrayElements, jenv, $input, 0); 
}
%typemap(argout) char *BYTE {
JCALL3(ReleaseByteArrayElements, jenv, $input, (jbyte *) $1, 0); 
}
%typemap(javain) char *BYTE "$javainput"
/* Prevent default freearg typemap from being used */
%typemap(freearg) char *BYTE ""

=================================================================================================

thosttraderapi.i:

%module(directors="1") thosttradeapi
%include "various.i"
%apply char **STRING_ARRAY { char *ppInstrumentID[] }
%{
#include "ThostFtdcTraderApi.h"
%}
%feature("director") CThostFtdcTraderSpi;
%include "ThostFtdcUserApiDataType.h"
%include "ThostFtdcUserApiStruct.h"
%include "ThostFtdcTraderApi.h"

=================================================================================================

thostmduserapi.i:

%module(directors="1") thostmduserapi  
%include "various.i"  
%apply char **STRING_ARRAY { char *ppInstrumentID[]};  
%{  
#include "ThostFtdcMdApi.h"  
%}  
%feature("director") CThostFtdcMdSpi;  
%include "ThostFtdcUserApiDataType.h"  
%include "ThostFtdcUserApiStruct.h"  
%include "ThostFtdcMdApi.h"

=================================================================================================

=================================================================================================


完成後 ctp3目錄中的文件:


C:\ctp3 的目錄


2018/07/17  21:43    <DIR>          .
2018/07/17  21:43    <DIR>          ..
2017/11/23  15:42               184 error.dtd
2017/11/23  15:42            16,121 error.xml
2018/07/17  21:43    <DIR>          srcmd
2018/07/17  21:44    <DIR>          srctr
2017/11/23  15:57             5,560 ThostFtdcMdApi.h
2017/11/23  15:56            34,436 ThostFtdcTraderApi.h
2017/11/23  15:57           248,505 ThostFtdcUserApiDataType.h
2017/11/23  15:57           231,072 ThostFtdcUserApiStruct.h
2017/11/23  15:59           907,264 thostmduserapi.dll
2018/07/16  19:35               297 thostmduserapi.i
2017/11/23  15:59             3,710 thostmduserapi.lib
2017/11/23  15:57         1,982,976 thosttraderapi.dll
2018/07/16  20:56               306 thosttraderapi.i
2017/11/23  15:57             3,846 thosttraderapi.lib
2018/07/16  19:35             4,678 various.i
2018/07/16  20:27                27 version.txt
              16 個文件      9,179,259 字節
               4 個目錄 15,771,103,232 可用字節


cmd 進入ctp3


C:\ctp3>swig.exe -c++ -java -package com.stevezong.thosttraderapi -outdir srctr -o thosttraderapi_wrap.cpp thosttraderapi.i
ThostFtdcTraderApi.h(30) : Warning 514: Director base class CThostFtdcTraderSpihas no virtual destructor.

在ctp3中生成下面兩個文件:

2018/07/17  21:44         5,722,812 thosttraderapi_wrap.cpp
2018/07/17  21:44            17,465 thosttraderapi_wrap.h

在 ctp3/srctr/*.java 文件 打包這些文件 com.stevezong.thosttraderapi.jar


在vs12 中

文件-》新建-》項目-》模板-》Visual C++ -》Win32-》Win32項目

名稱:thosttraderapi_wrap

位置:C:\ctp\tr\

確認創建-》下一步-》DLL(空項目)-》完成

在解決方案資源管理器-》thosttraderapi_wrap-》源文件-》添加-》現有項

libiconv.lib //C:\Program Files (x86)\GnuWin32\lib

ThostFtdcTraderApi.h //C:\ctp3

ThostFtdcUserApiDataType.h //C:\ctp3

ThostFtdcUserApiStruct.h //C:\ctp3

thosttraderapi.lib //C:\ctp3

thosttraderapi_wrap.cpp //C:\ctp3

thosttraderapi_wrap.h //C:\ctp3

將這7個文件添加好

對thosttraderapi_wrap.cpp文件進行一些編輯:

將下面這些註釋掉或者刪掉

註釋快捷鍵 先選中 CTRL+K 在CTRL+C

=====================================================================================================================================

=====================================================================================================================================

//SWIGEXPORT jchar JNICALL Java_com_stevezong_thosttraderapi_thosttradeapiJNI_THOST_1FTDC_1VTC_1BankBankToFuture_1get(JNIEnv *jenv, jclass jcls) {
//  jchar jresult = 0 ;
//  char result;
//  
//  (void)jenv;
//  (void)jcls;
//  result = (char)('102001');
//  jresult = (jchar)result; 
//  return jresult;
//}
=====================================================================================================================================
//SWIGEXPORT jchar JNICALL Java_com_stevezong_thosttraderapi_thosttradeapiJNI_THOST_1FTDC_1VTC_1BankFutureToBank_1get(JNIEnv *jenv, jclass jcls) {
//  jchar jresult = 0 ;
//  char result;
//  
//  (void)jenv;
//  (void)jcls;
//  result = (char)('102002');
//  jresult = (jchar)result; 
//  return jresult;
//}
=====================================================================================================================================
//SWIGEXPORT jchar JNICALL Java_com_stevezong_thosttraderapi_thosttradeapiJNI_THOST_1FTDC_1VTC_1FutureBankToFuture_1get(JNIEnv *jenv, jclass jcls) {
//  jchar jresult = 0 ;
//  char result;
//  
//  (void)jenv;
//  (void)jcls;
//  result = (char)('202001');
//  jresult = (jchar)result; 
//  return jresult;
//}
=====================================================================================================================================
//SWIGEXPORT jchar JNICALL Java_com_stevezong_thosttraderapi_thosttradeapiJNI_THOST_1FTDC_1VTC_1FutureFutureToBank_1get(JNIEnv *jenv, jclass jcls) {
//  jchar jresult = 0 ;
//  char result;
//  
//  (void)jenv;
//  (void)jcls;
//  result = (char)('202002');
//  jresult = (jchar)result; 
//  return jresult;
//}
=====================================================================================================================================
//SWIGEXPORT jchar JNICALL Java_com_stevezong_thosttraderapi_thosttradeapiJNI_THOST_1FTDC_1FTC_1BankLaunchBankToBroker_1get(JNIEnv *jenv, jclass jcls) {
//  jchar jresult = 0 ;
//  char result;
//  
//  (void)jenv;
//  (void)jcls;
//  result = (char)('102001');
//  jresult = (jchar)result; 
//  return jresult;
//}
=====================================================================================================================================
//SWIGEXPORT jchar JNICALL Java_com_stevezong_thosttraderapi_thosttradeapiJNI_THOST_1FTDC_1FTC_1BrokerLaunchBankToBroker_1get(JNIEnv *jenv, jclass jcls) {
//  jchar jresult = 0 ;
//  char result;
//  
//  (void)jenv;
//  (void)jcls;
//  result = (char)('202001');
//  jresult = (jchar)result; 
//  return jresult;
//}
=====================================================================================================================================
//SWIGEXPORT jchar JNICALL Java_com_stevezong_thosttraderapi_thosttradeapiJNI_THOST_1FTDC_1FTC_1BankLaunchBrokerToBank_1get(JNIEnv *jenv, jclass jcls) {
//  jchar jresult = 0 ;
//  char result;
//  
//  (void)jenv;
//  (void)jcls;
//  result = (char)('102002');
//  jresult = (jchar)result; 
//  return jresult;
//}
=====================================================================================================================================
//SWIGEXPORT jchar JNICALL Java_com_stevezong_thosttraderapi_thosttradeapiJNI_THOST_1FTDC_1FTC_1BrokerLaunchBrokerToBank_1get(JNIEnv *jenv, jclass jcls) {
//  jchar jresult = 0 ;
//  char result;
//  
//  (void)jenv;
//  (void)jcls;
//  result = (char)('202002');
//  jresult = (jchar)result; 
//  return jresult;
//}

=====================================================================================================================================

=====================================================================================================================================


CTP是GB2312編碼,Java輸出是UTF-8編碼,

所以要進行字節轉換。

在thosttraderapi_wrap.cpp文件開頭添加如下代碼:

=================================================================================================================================

=================================================================================================================================

thosttraderapi_wrap.cpp:

#pragma warning(disable:4996)
#include <iconv.h>
int code_convert(const char *from_charset, const char *to_charset, char *inbuf, size_t inlen, char *outbuf, size_t outlen)
{
iconv_t cd;
int rc;
char **pin = &inbuf;
char **pout = &outbuf;
cd = iconv_open(to_charset, from_charset);
int argument = 1;
if (cd == 0) return -1;
if (iconv(cd, (const char **)pin, &inlen, pout, &outlen) == -1)
{
iconv_close(cd);
return -1;
}
iconv_close(cd);
return 0;
}
#define GB2312TOUTF8FORCONTENT                     char result_utf8[1000]={0};                    if(result)                                     {                                              unsigned int inlength=strlen(result);      int rsp=code_convert("gb2312","utf-8",result,inlength,result_utf8,1000);if(rsp!=-1) jresult = jenv->NewStringUTF((const char *)result_utf8);}

=================================================================================================================================

=================================================================================================================================

搜索文件thosttraderapi_wrap.cpp將

=====================================================================

if (result) jresult = jenv->NewStringUTF((const char *)result);

替換為下面的

GB2312TOUTF8FORCONTENT

=====================================================================

完成後 F7生成解決方案就會在:


C:\ctp3\tr\thosttraderapi_wrap\Debug\thosttraderapi_wrap.dll

thosttraderapi.dll //C:\ctp3\thosttraderapi.dll

thosttraderapi_wrap.dll //C:\ctp3\tr\thosttraderapi_wrap\Debug\thosttraderapi_wrap.dll

libiconv2.dll //C:\Program Files (x86)\GnuWin32\bin\libiconv2.dll


三個文件拷貝到你電腦環境變量path路徑底下,如果自己不清楚

C:\Program Files\Java\jre1.8.0_111\bin

C:\Program Files\Java\jdk1.8.0_111\bin

C:\Program Files\Java\jdk1.8.0_111\jre\bin

都放一下


到這裏 基本的處理工作基本完成

可以編寫java 代碼 要先看cpp文件和api文檔我這裏就寫的一個通過交易api 獲取所有的交易所 -》每個交易所的商品-》每個商品的所有合約

這裏就先寫一個最簡單的demo 以後有時間在補上正式代碼

有需要也可以留言給我


package com.stevezong.ctp.test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.stevezong.thosttraderapi.*;
class TraderSpiImpl extends CThostFtdcTraderSpi {
final static String m_BrokerId = "BrokerId";
final static String m_UserId = "用戶名";
final static String m_InvestorId = "用戶名";
final static String m_AccountId = "用戶名";
final static String m_PassWord = "密碼";
private List<String> ListExchanges = new ArrayList<String>();
private List<String> ListProducts = new ArrayList<String>();
private List<String> ListInstruments = new ArrayList<String>();
TraderSpiImpl(CThostFtdcTraderApi traderapi) {
m_traderapi = traderapi;
}
@Override
public void OnFrontConnected() {
System.out.println("On Front Connected");
CThostFtdcReqUserLoginField field = new CThostFtdcReqUserLoginField();
field.setBrokerID(m_BrokerId);
field.setUserID(m_UserId);
field.setPassword(m_PassWord);
field.setUserProductInfo("JAVA_API");
int a = m_traderapi.ReqUserLogin(field, 0);
System.out.println("a:" + a);
System.out.println("Send login ok");
}
@Override
public void OnRspUserLogin(CThostFtdcRspUserLoginField pRspUserLogin, CThostFtdcRspInfoField pRspInfo,
int nRequestID, boolean bIsLast) {
if (pRspInfo != null && pRspInfo.getErrorID() != 0) {
System.out.printf("Login ErrorID[%d] ErrMsg[%s]\n", pRspInfo.getErrorID(), pRspInfo.getErrorMsg());
return;
}
System.out.println(pRspUserLogin);
System.out.println("Login success!!!");
CThostFtdcQryExchangeField pQryExchange = new CThostFtdcQryExchangeField();
int b = m_traderapi.ReqQryExchange(pQryExchange, 1);
System.out.println("b:" + b);
}
@Override
public void OnRspQryExchange(CThostFtdcExchangeField pExchange, CThostFtdcRspInfoField pRspInfo, int nRequestID,
boolean bIsLast) {
System.out.println(pExchange.toString());
String str;
try {
str = new String(pExchange.getExchangeName().getBytes("ISO-8859-1"),"GBK");
//System.out.println(str);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ListExchanges.add(pExchange.toString());
/*
 * CThostFtdcQryProductField pQryProduct = new CThostFtdcQryProductField();
 * pQryProduct.setExchangeID(pExchange.getExchangeID());
 * pQryProduct.setProductClass(pExchange.getExchangeProperty()); int c =
 * m_traderapi.ReqQryProduct(pQryProduct, 2); System.out.println("c:" + c);
 */
if (bIsLast) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
CThostFtdcQryProductField pQryProduct = new CThostFtdcQryProductField();
int c = m_traderapi.ReqQryProduct(pQryProduct, 2);
//System.out.println("c:" + c);
}
}
@Override
public void OnRspQryProduct(CThostFtdcProductField pProduct, CThostFtdcRspInfoField pRspInfo, int nRequestID,
boolean bIsLast) {
System.out.println(pProduct.toString());
ListProducts.add(pProduct.toString());
if(bIsLast) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
CThostFtdcQryInstrumentField pQryInstrument = new CThostFtdcQryInstrumentField();
int d = m_traderapi.ReqQryInstrument(pQryInstrument, nRequestID);
System.out.println("d:"+d);
}
}
@Override
public void OnRspQryInstrument(CThostFtdcInstrumentField pInstrument, CThostFtdcRspInfoField pRspInfo,
int nRequestID, boolean bIsLast) {
//System.out.println(pInstrument.toString());
StringBuffer sb = new StringBuffer();
sb.append("SZ_");
sb.append(pInstrument.getExchangeID());
sb.append("_");
sb.append(pInstrument.getProductID());
sb.append("_");
sb.append(pInstrument.getDeliveryYear());
String DeliveryMonth = String.format("%02d",pInstrument.getDeliveryMonth());
sb.append(DeliveryMonth);
sb.append(":");
sb.append(pInstrument.getInstrumentID());
//System.out.println(sb);
ListInstruments.add(sb.toString());
if(bIsLast) { 
try {
PrintWriter pw = new PrintWriter("C:/123/ctp/CThostFtdcInstrumentField.txt");
Collections.sort(ListInstruments);
for(String sub:ListInstruments) {
//System.out.println(sub);
pw.println(sub);
}
pw.flush();
pw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
private CThostFtdcTraderApi m_traderapi;
}
public class TradeapiDemo {
static {
System.loadLibrary("thosttraderapi");
System.loadLibrary("thosttraderapi_wrap");
}
//用的SIMNOW的
final static String ctp1_TradeAddress = "tcp://180.168.146.187:10030";
public static void main(String[] args) {
CThostFtdcTraderApi traderApi = CThostFtdcTraderApi.CreateFtdcTraderApi();
TraderSpiImpl pTraderSpi = new TraderSpiImpl(traderApi);
traderApi.RegisterSpi(pTraderSpi);
traderApi.RegisterFront(ctp1_TradeAddress);
traderApi.SubscribePublicTopic(THOST_TE_RESUME_TYPE.THOST_TERT_RESTART);
traderApi.SubscribePrivateTopic(THOST_TE_RESUME_TYPE.THOST_TERT_RESTART);
traderApi.Init();
traderApi.Join();
traderApi.Release();
return;
}
}












CTP Java 版(Swig)