: | : | :期货程序化 | :期货程序化研究 | :期货量化学习 | :期货量化 |
返回列表 发帖

TWS API 开发手记——连接到TWS平台

TWS API 开发手记——连接到TWS平台

TWS 是世界著名的盈透证券的交易平台,可以交易全球股票、期货、外汇等金融产品。而盈透证券的老板,又是一个以量化交易起家的传奇人物,因此在盈透很早的时候,就提供了基于TWS的API,供全世界的玩家开发出自己的交易系统。

因为个人兴趣爱好的原因,所以一直想开发一款属于自己的交易软件,后来注意到这个产品后,决定自己也试一试。

想要使用TWS,需要先去册盈透证券的官网注册投资者账号,并且在账号开通后三个月内向你的投资人账号打款以激活账号,否则注册了账号而不打款,三个月后账户就会被注销掉,也意味着你不能使用TWS进行下一步的开发了。

注册了账户、打入资金后,就可以在盈透证券的官网下载TWS交易客户端,同时还有IB API。IB API目前提供有Linux,Windows,MacOS三个系统的版本,根据你自己擅长的系统和语言,选择对应的API进行下载就行。这里笔者选择的是Windows,因为之后考虑做UI的时候,C#.NET 会十分方便。当然,笔者本人会Java,Python等语言技术,而且IB API的使用方法基本一致,所以也就无所谓语言的优劣,只要方便使用就好。

通信前准备

使用Windows编程,需要准备的是Visual Studio或者支持相关语言的开发工具和IDE,因为笔者用C#做这个项目,所以选择了Visual Studio。另一方面,因为Windows系统的限制,需要提前准备好程序的通信端口,并在防火墙、杀毒软件设置为打开。

通信前还需要做最后一个操作,打开TWS,并在全局设置中将允许连接打开,如果你只允许本地连接,那么点击“Allow connection from localhost only”就行,推荐这样做,因为比较安全。

开始编程

打开Visual studio并新建一个C#的工程,同时在工程“Solution Explorer”位置,找到工程的“References”,并添加IB API的DLL链接库。

IB API的库文件,存储于你安装的位置,只要找一找就能很容易找到。

工程目前包含两个主要文件,一个是Program.cs和TWSDeliverInterfaceImp.cs。

TWSDeliverInterfaceImp,是对EWrapper类的实现,这个是非常重要的一个类,包含了对所有事件的处理和响应,不过当前我们并不需要做太多的事件处理,因此可以把所有需要实现的方法空置即可。

  1. using IBApi;
  2. using System;
  3. using System.Collections.Generic;

  4. namespace AbsZeroTWS
  5. {
  6.     class TWSDeliverInterfaceImp : EWrapper
  7.     {
  8.         private EClientSocket clientSocket;
  9.         private int nextOrderId;
  10.         private int clientId;

  11.         public TWSDeliverInterfaceImp(EReaderSignal signal)
  12.         {
  13.             clientSocket = new EClientSocket(this, signal);
  14.         }

  15.         public int ClientId
  16.         {
  17.             get { return clientId; }
  18.             set { clientId = value; }
  19.         }

  20.         public EClientSocket ClientSocket
  21.         {
  22.             get { return clientSocket; }
  23.             set { clientSocket = value; }
  24.         }

  25.         public int NextOrderId
  26.         {
  27.             get { return nextOrderId; }
  28.             set { nextOrderId = value; }
  29.         }

  30.         public void accountDownloadEnd(string account) { }
  31.         public void accountSummary(int reqId, string account, string tag, string value, string currency) { }
  32.         public void accountSummaryEnd(int reqId) { }
  33.         public void accountUpdateMulti(int requestId, string account, string modelCode, string key, string value, string currency) { }
  34.         public void accountUpdateMultiEnd(int requestId) { }
  35.         public void bondContractDetails(int reqId, ContractDetails contract) { }
  36.         public void commissionReport(CommissionReport commissionReport) { }
  37.         public void connectAck() { }
  38.         public void connectionClosed() { }
  39.         public void contractDetails(int reqId, ContractDetails contractDetails) { }
  40.         public void contractDetailsEnd(int reqId) { }
  41.         public void currentTime(long time) { }
  42.         public void deltaNeutralValidation(int reqId, UnderComp underComp) { }
  43.         public void displayGroupList(int reqId, string groups) { }
  44.         public void displayGroupUpdated(int reqId, string contractInfo) { }
  45.         public void error(string str) { }
  46.         public void error(Exception e) { }
  47.         public void error(int id, int errorCode, string errorMsg) { }
  48.         public void execDetails(int reqId, Contract contract, Execution execution) { }
  49.         public void execDetailsEnd(int reqId) { }
  50.         public void fundamentalData(int reqId, string data) { }
  51.         public void historicalData(int reqId, string date, double open, double high, double low, double close, int volume, int count, double WAP, bool hasGaps) { }
  52.         public void historicalDataEnd(int reqId, string start, string end) { }
  53.         public void managedAccounts(string accountsList) { }
  54.         public void marketDataType(int reqId, int marketDataType) { }
  55.         public void nextValidId(int orderId) { }
  56.         public void openOrder(int orderId, Contract contract, Order order, OrderState orderState) { }
  57.         public void openOrderEnd() { }
  58.         public void orderStatus(int orderId, string status, double filled, double remaining, double avgFillPrice, int permId, int parentId, double lastFillPrice, int clientId, string whyHeld) { }
  59.         public void position(string account, Contract contract, double pos, double avgCost) { }
  60.         public void positionEnd() { }
  61.         public void positionMulti(int requestId, string account, string modelCode, Contract contract, double pos, double avgCost) { }
  62.         public void positionMultiEnd(int requestId) { }
  63.         public void realtimeBar(int reqId, long time, double open, double high, double low, double close, long volume, double WAP, int count) { }
  64.         public void receiveFA(int faDataType, string faXmlData) { }
  65.         public void scannerData(int reqId, int rank, ContractDetails contractDetails, string distance, string benchmark, string projection, string legsStr) { }
  66.         public void scannerDataEnd(int reqId) { }
  67.         public void scannerParameters(string xml) { }
  68.         public void securityDefinitionOptionParameter(int reqId, string exchange, int underlyingConId, string tradingClass, string multiplier, HashSet<string> expirations, HashSet<double> strikes) { }
  69.         public void securityDefinitionOptionParameterEnd(int reqId) { }
  70.         public void softDollarTiers(int reqId, SoftDollarTier[] tiers) { }
  71.         public void tickEFP(int tickerId, int tickType, double basisPoints, string formattedBasisPoints, double impliedFuture, int holdDays, string futureLastTradeDate, double dividendImpact, double dividendsToLastTradeDate) { }
  72.         public void tickGeneric(int tickerId, int field, double value) { }
  73.         public void tickOptionComputation(int tickerId, int field, double impliedVolatility, double delta, double optPrice, double pvDividend, double gamma, double vega, double theta, double undPrice) { }
  74.         public void tickPrice(int tickerId, int field, double price, int canAutoExecute) { }
  75.         public void tickSize(int tickerId, int field, int size) { }
  76.         public void tickSnapshotEnd(int tickerId) { }
  77.         public void tickString(int tickerId, int field, string value) { }
  78.         public void updateAccountTime(string timestamp) { }
  79.         public void updateAccountValue(string key, string value, string currency, string accountName) { }
  80.         public void updateMktDepth(int tickerId, int position, int operation, int side, double price, int size) { }
  81.         public void updateMktDepthL2(int tickerId, int position, string marketMaker, int operation, int side, double price, int size) { }
  82.         public void updateNewsBulletin(int msgId, int msgType, string message, string origExchange) { }
  83.         public void updatePortfolio(Contract contract, double position, double marketPrice, double marketValue, double averageCost, double unrealisedPNL, double realisedPNL, string accountName) { }
  84.         public void verifyAndAuthCompleted(bool isSuccessful, string errorText) { }
  85.         public void verifyAndAuthMessageAPI(string apiData, string xyzChallenge) { }
  86.         public void verifyCompleted(bool isSuccessful, string errorText) { }
  87.         public void verifyMessageAPI(string apiData) { }
  88.     }
  89. }
复制代码

令一个类是主类,我们实现以下代码。

  1. using IBApi;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;

  8. namespace AbsZeroTWS
  9. {
  10.     class Program
  11.     {
  12.         static void Main(string[] args)
  13.         {
  14.             EReaderMonitorSignal signal = new EReaderMonitorSignal();
  15.             TWSDeliverInterfaceImp tws = new TWSDeliverInterfaceImp(signal);
  16.             tws.ClientSocket.eConnect("localhost", 7000, 0);

  17.             var reader = new EReader(tws.ClientSocket, signal);
  18.             reader.Start();

  19.             if (tws.ClientSocket.IsConnected())
  20.             {
  21.                 Console.WriteLine("Connection is established!");
  22.             }
  23.             /*
  24.             new Thread(() => {
  25.                 while (tws.ClientSocket.IsConnected())
  26.                 {
  27.                     signal.waitForSignal();
  28.                     reader.processMsgs();
  29.                 }
  30.             }) { IsBackground = true }.Start();
  31.             */
  32.             Console.ReadKey();
  33.         }
  34.     }
  35. }
复制代码

点击运行后,程序就能跟TWS进行连接,并打印出connection is established.


论坛官方微信、群(期货热点、量化探讨、开户与绑定实盘)
 
期货论坛 - 版权/免责声明   1.本站发布源码(包括函数、指标、策略等)均属开放源码,用意在于让使用者学习程序化语法撰写,使用者可以任意修改语法內容并调整参数。仅限用于个人学习使用,请勿转载、滥用,严禁私自连接实盘账户交易
  2.本站发布资讯(包括文章、视频、历史记录、教材、评论、资讯、交易方案等)均系转载自网络主流媒体,内容仅为作者当日个人观点,本网转载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。本网不对该类信息或数据做任何保证。不对您构成任何投资建议,不能依靠信息而取代自身独立判断,不对因使用本篇文章所诉信息或观点等导致的损失承担任何责任。
  3.本站发布资源(包括书籍、杂志、文档、软件等)均从互联网搜索而来,仅供个人免费交流学习,不可用作商业用途,本站不对显示的内容承担任何责任。请在下载后24小时内删除。如果喜欢,请购买正版,谢谢合作!
  4.龙听期货论坛原创文章属本网版权作品,转载须注明来源“龙听期货论坛”,违者本网将保留追究其相关法律责任的权力。本论坛除发布原创文章外,亦致力于优秀财经文章的交流分享,部分文章推送时若未能及时与原作者取得联系并涉及版权问题时,请及时联系删除。联系方式:http://www.qhlt.cn/thread-262-1-1.html
如何访问权限为100/255贴子:/thread-37840-1-1.html;注册后仍无法回复:/thread-23-1-1.html;微信/QQ群:/thread-262-1-1.html;网盘链接失效解决办法:/thread-93307-1-1.html

返回列表