看帖神器
北美华人网
追帖动态
头条新闻
每日新帖
最新热帖
新闻存档
热帖存档
文学城
虎扑论坛
未名空间
北美华人网
北美微论坛
看帖神器
登录
← 下载
《看帖神器》官方
iOS App
,体验轻松追帖。
给一个坛友的code
查看北美华人网今日新帖
最新回复:2020年11月25日 19点51分 PT
共 (4) 楼
返回列表
订阅追帖
只看未读
更多选项
阅读全帖
只看图片
只看视频
查看原帖
n
nj_guy
接近 4 年
楼主 (北美华人网)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using IBApi; using System.Windows.Forms; using LocalMessage; using UDPApp.IBListener.Contracts; using System.Threading; using UDPApp.IBListener.Orders; using LocalMessage.Constants; using System.Runtime.CompilerServices; using LocalMessage.SQMessages; using MySql.Data.MySqlClient; using System.Diagnostics;
namespace UDPApp.IBListener { public class SQIBClient : EWrapper { static AutoResetEvent autoResetEvent = new AutoResetEvent(false);
private EClientSocket clientSocket; public readonly EReaderSignal signal; private UDPPanel parentUI; private int clientId; private LocalMessage.SyncronizedCounter orderIdCounter;
public bool IsConnected() { return clientSocket.IsConnected(); }
public SQIBClient(UDPPanel parent, int inClinetId) { parentUI = parent; clientId = inClinetId; signal = new EReaderMonitorSignal(); clientSocket = new EClientSocket(this, signal); orderIdCounter = LocalMessage.SyncronizedCounter.newCounter(1); }
public SQIBClient(UDPPanel parent) { parentUI = parent; clientId = ApplicationIds.UDP; signal = new EReaderMonitorSignal(); clientSocket = new EClientSocket(this, signal); orderIdCounter = LocalMessage.SyncronizedCounter.newCounter(1); }
//Additional Method public void Dispose() { if (clientSocket != null && IsConnected()) clientSocket.Close(); if (clientSocket != null) clientSocket = null; }
//Additional Method private void addTextToBox(string text) { SQMessage sqm = Program.allVariables.MessageService. createSQGenericMessage(ApplicationIds.IBClient, ActionIds.GenericInfo, text); parentUI.HandleIBMessage(sqm); }
//Additional public void Connect() { try { this.ClientSocket.eConnect(Program.allVariables.IBIP, Program.allVariables.IBPort, clientId); var reader = new EReader(this.ClientSocket, signal);
reader.Start();
new Thread(() => { while (this.ClientSocket.IsConnected()) { signal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); } catch (Exception e) { string errmsg = "" + e; throw new Exception(errmsg); }
}
//Additional public void SendMktDataReqForContracts(Dictionary<int, Contract> IBContracts) { if (IsConnected()) { List<TagValue> mktDataOptions = new List<TagValue>(); foreach (KeyValuePair<int, Contract> kvp in IBContracts) { ClientSocket.reqMktData(kvp.Key, kvp.Value, "233", false, mktDataOptions); } } else { string errmsg = "IBCLient SendMktDataReqForContracts Exception: not connected"; SQMessage sqm = Program.allVariables.MessageService. createSQMessage( MQTopic.IBContractDetail, ApplicationIds.IBClient, ActionIds.IBMktDataSendRequest, SubjectIds.Error, MessageId.ZERO, errmsg); parentUI.HandleIBMessage(sqm); } }
//Additional [MethodImpl(MethodImplOptions.Synchronized)] public void SendOrder(int AppId, int orderType, List<SQOrder> sqorderList) { if (AppId == ApplicationIds.SpreadBox) { SendSpreadBoxOrder(orderType, sqorderList); } else if(AppId == ApplicationIds.Scalper) { SendFutureOrder(LocalMessage.Constants.MessageId.TICKET_FUT_GTC, sqorderList); } else if (AppId == ApplicationIds.VolVault) { SendFutureOrder(LocalMessage.Constants.MessageId.TICKET_FUT_LMT, sqorderList); } }
private void SendSpreadBoxOrder(int orderType, List<SQOrder> sqorderList) { if (IsConnected()) { bool isOptHedgePair = false; int optIndex = 0; int futIndex = 0; if (sqorderList.Count == 2) { string type0 = sqorderList[0]._ibContract.SecType; string type1 = sqorderList[1]._ibContract.SecType; if (type0 == "FUT" && type1 == "OPT") { isOptHedgePair = true; optIndex = 1; futIndex = 0; if (sqorderList[futIndex]._optOriginalQuantity == 0) { sqorderList[futIndex]._optOriginalQuantity = sqorderList[optIndex]._quantity; sqorderList[futIndex]._optRemainRatio = 1; }
} else if (type0 == "OPT" && type1 == "FUT") { isOptHedgePair = true; optIndex = 0; futIndex = 1; if (sqorderList[futIndex]._optOriginalQuantity == 0) { sqorderList[futIndex]._optOriginalQuantity = sqorderList[optIndex]._quantity; sqorderList[futIndex]._optRemainRatio = 1; } } }
if (isOptHedgePair) { //int sqibId = orderIdCounter.next(); int sqibId = SendOrder(orderType, sqorderList[optIndex]); AllVariables.FutureOrderParkingArea[sqibId] = sqorderList[futIndex]; } else { foreach (SQOrder sqorder in sqorderList) { //int sqibId = orderIdCounter.next(); SendOrder(orderType, sqorder); } }
} else { string errmsg = "IBCLient SendOrder Exception: not connected"; SQMessage sqm = Program.allVariables.MessageService. createSQErrorMessage( ApplicationIds.IBClient, ActionIds.GenericInfo, errmsg); parentUI.HandleIBMessage(sqm); } }
private void SendFutureOrder(int futOrderType, List<SQOrder> sqorderList) { if (IsConnected()) { foreach (SQOrder sqorder in sqorderList) { //int sqibId = orderIdCounter.next(); SendOrder(futOrderType, sqorder); }
} else { string errmsg = "IBCLient SendOrder Exception: not connected"; SQMessage sqm = Program.allVariables.MessageService. createSQErrorMessage( ApplicationIds.IBClient, ActionIds.GenericInfo, errmsg); parentUI.HandleIBMessage(sqm); } }
//return ib order id private int SendOrder(int orderType, SQOrder sqorder) { if (IsConnected()) { string IBAccountId = Program.allVariables.getIBAccountID(); Order order; if (sqorder._ibContract.SecType == "OPT") { if (orderType == LocalMessage.Constants.MessageId.TICKET_OPT_LMT) { order = OrderManager.LimitOrder (IBAccountId, sqorder._buySell, sqorder._quantity, sqorder._prix); } else { order = OrderManager.IOCLimitOrder (IBAccountId, sqorder._buySell, sqorder._quantity, sqorder._prix); } } else { if (orderType == LocalMessage.Constants.MessageId.TICKET_FUT_GTC) { order = OrderManager.GTCLimitOrder (IBAccountId, sqorder._buySell, sqorder._quantity, sqorder._prix); } else { order = OrderManager.LimitOrder (IBAccountId, sqorder._buySell, sqorder._quantity, sqorder._prix); } }
int sqibId = orderIdCounter.next(); ClientSocket.placeOrder(sqibId, sqorder._ibContract, order); Program.allVariables.ticketId2ibIdMap.add(sqorder._tktId, sqibId); //string logmsg = "BuySell=" + BuySell + ",Quantity=" + quantity // + ",Price=" + price + ",SQTicketId=" + SQTicketId; //Program.allVariables.ibOrderLogger.log(logmsg); return sqibId; } else { string errmsg = "IBCLient SendOrder Exception: not connected"; SQMessage sqm = Program.allVariables.MessageService. createSQErrorMessage( ApplicationIds.IBClient, ActionIds.GenericInfo, errmsg); parentUI.HandleIBMessage(sqm); return Int32.MinValue; } }
public void CancelOrder(int ibOrderId) { ClientSocket.cancelOrder(ibOrderId); }
public void SendAccountUpdateRequest(bool isStart) { if (IsConnected()) { string IBAccountId = Program.allVariables.getIBAccountID(); ClientSocket.reqAccountUpdates(isStart, IBAccountId); } else { string errmsg = "IBCLient reqAccountUpdates Exception: not connected"; SQMessage sqm = Program.allVariables.MessageService. createSQErrorMessage( ApplicationIds.IBClient, ActionIds.GenericInfo, errmsg); parentUI.HandleIBMessage(sqm); } }
public void SendAutoOpenOrderStatusRequest(bool isStart) { if (IsConnected()) { string IBAccountId = Program.allVariables.getIBAccountID(); ClientSocket.reqAutoOpenOrders(isStart); } else { string errmsg = "IBCLient reqAccountUpdates Exception: not connected"; SQMessage sqm = Program.allVariables.MessageService. createSQErrorMessage( ApplicationIds.IBClient, ActionIds.GenericInfo, errmsg); parentUI.HandleIBMessage(sqm); } }
//Aditional public void SyncOrderIdWithIB() { ClientSocket.reqIds(-1); autoResetEvent.WaitOne(); }
//Additional public void SendMktDataReqForContract(int reqId, Contract aIBContract) { if (IsConnected()) { List<TagValue> mktDataOptions = new List<TagValue>(); ClientSocket.reqMktData(reqId, aIBContract, "233", false, mktDataOptions); } else { string errmsg = "IBCLient SendMktDataReqForContract Exception: not connected"; SQMessage sqm = Program.allVariables.MessageService. createSQErrorMessage( ApplicationIds.IBClient, ActionIds.IBMktDataSendRequest, errmsg); parentUI.HandleIBMessage(sqm); } }
//Additional public void SendDetailReqForContract(int reqId, Contract aIBContract) { if (IsConnected()) { List<TagValue> mktDataOptions = new List<TagValue>(); ClientSocket.reqContractDetails(reqId, aIBContract); } else { string errmsg = "IBCLient SendDetailReqForContract Exception: not connected"; SQMessage sqm = Program.allVariables.MessageService. createSQErrorMessage( ApplicationIds.IBClient, ActionIds.IBContractDetailSendRequest, errmsg); parentUI.HandleIBMessage(sqm); } }
public EClientSocket ClientSocket { get { return clientSocket; } set { clientSocket = value; } }
//interface req public virtual void error(Exception e) { string errmsg = "Error: " + e; SQMessage sqm = Program.allVariables.MessageService. createSQMessage( MQTopic.NOACTIVE_IB, ApplicationIds.IBClient, ActionIds.IBResponse, SubjectIds.IBError, MessageId.ZERO, errmsg); parentUI.HandleIBMessage(sqm); }
//interface req public virtual void error(string str) { SQMessage sqm = Program.allVariables.MessageService. createSQMessage( MQTopic.NOACTIVE_IB, ApplicationIds.IBClient, ActionIds.IBResponse, SubjectIds.IBError, MessageId.ZERO, "Error: " + str); parentUI.HandleIBMessage(sqm); }
//interface req public virtual void error(int reqid, int errorCode, string errorMsg) { SQMessage sqm = Program.allVariables.MessageService. createSQMessage( MQTopic.NOACTIVE_IB, ApplicationIds.IBClient, ActionIds.IBResponse, SubjectIds.IBError, reqid, "Error Code:" + errorCode + ", " + errorMsg); parentUI.HandleIBMessage(sqm); }
//interface req public virtual void connectionClosed() { SQMessage sqm = Program.allVariables.MessageService. createSQMessage( MQTopic.NOACTIVE_IB, ApplicationIds.IBClient, ActionIds.IBResponse, SubjectIds.GenericText, MessageId.ZERO, StdStringMessage.IBConnectionClosed); parentUI.HandleIBMessage(sqm); }
//interface req public virtual void currentTime(long time) { string msgstr = "Current Time: " + time + "\n"; SQMessage sqm = Program.allVariables.MessageService. createSQMessage( MQTopic.NOACTIVE_IB, ApplicationIds.IBClient, ActionIds.IBResponse, SubjectIds.Time, MessageId.ZERO, msgstr); parentUI.HandleIBMessage(sqm); }
//interface req public virtual void tickPrice(int tickerId, int field, double price, int canAutoExecute) { int contractId = tickerId - AllVariables.IBMktDataRequestIdBase; int subjectId; if (field == 1) subjectId = SubjectIds.TickPriceBid; else if (field == 2) subjectId = SubjectIds.TickPriceAsk; else if (field == 4) subjectId = SubjectIds.TickPriceLast; else if (field == 9) subjectId = SubjectIds.TickPriceClose; else subjectId = SubjectIds.IBError; //addTextToBox("Tick Price. Ticker Id:" + tickerId + ", Type: " + TickType.getField(field) + ", Price: " + price + "\n"); //parentUI.HandleIBMessage(new TickPriceMessage(tickerId, field, price, canAutoExecute)); SQMessage sqm = Program.allVariables.MessageService. createSQMessage( MQTopic.MktData, ApplicationIds.IBClient, ActionIds.MktDataPublish, subjectId, contractId, price); parentUI.HandleIBMessage(sqm); }
n
nj_guy
接近 4 年
2 楼
//interface req public virtual void tickSize(int tickerId, int field, int size) { int contractId = tickerId - AllVariables.IBMktDataRequestIdBase; int subjectId; if (field == 0) subjectId = SubjectIds.TickSizeBid; else if (field == 3) subjectId = SubjectIds.TickSizeAsk; else if (field == 5) subjectId = SubjectIds.TickSizeLast; else if (field == 8) subjectId = SubjectIds.TickSizeVolumn; else subjectId = SubjectIds.IBError;
//addTextToBox("Tick Size. Ticker Id:" + tickerId + ", Type: " + TickType.getField(field) + ", Size: " + size + "\n"); //parentUI.HandleIBMessage(new TickSizeMessage(tickerId, field, size)); SQMessage sqm = Program.allVariables.MessageService. createSQMessage( MQTopic.MktData, ApplicationIds.IBClient, ActionIds.MktDataPublish, subjectId, contractId, size); parentUI.HandleIBMessage(sqm); }
//interface req public virtual void tickString(int tickerId, int tickType, string value) { //addTextToBox("Tick string. Ticker Id:" + tickerId + ", Type: " + TickType.getField(tickType) + ", Value: " + value + "\n"); int contractId = tickerId - AllVariables.IBMktDataRequestIdBase; if (tickType == 48) { int subjectId = SubjectIds.TickRTVolume; //Debug.WriteLine("RT48 Value=" + value); value = value.Replace(';', '='); SQMessage sqm = Program.allVariables.MessageService. createSQMessage( MQTopic.MktData, ApplicationIds.IBClient, ActionIds.MktDataPublish, subjectId, contractId, value); parentUI.HandleIBMessage(sqm); } }
//interface req public virtual void tickGeneric(int tickerId, int field, double value) { addTextToBox("Tick Generic. Ticker Id:" + tickerId + ", Field: " + TickType.getField(field) + ", Value: " + value + "\n"); }
//interface req public virtual void tickEFP(int tickerId, int tickType, double basisPoints, string formattedBasisPoints, double impliedFuture, int holdDays, string futureExpiry, double dividendImpact, double dividendsToExpiry) { addTextToBox("TickEFP. " + tickerId + ", Type: " + tickType + ", BasisPoints: " + basisPoints + ", FormattedBasisPoints: " + formattedBasisPoints + ", ImpliedFuture: " + impliedFuture + ", HoldDays: " + holdDays + ", FutureExpiry: " + futureExpiry + ", DividendImpact: " + dividendImpact + ", DividendsToExpiry: " + dividendsToExpiry + "\n"); }
//interface req public virtual void tickSnapshotEnd(int tickerId) { addTextToBox("TickSnapshotEnd: " + tickerId + "\n"); }
//interface req public virtual void nextValidId(int orderId) { //isConnected = true; //nextOrderId = orderId; orderIdCounter.reset(orderId); autoResetEvent.Set(); string msg = "IBCLient Sync Next Available Order ID:" + orderId; SQMessage sqm = Program.allVariables. MessageService.createSQGenericMessage ( ApplicationIds.IBClient, ActionIds.IBResponse, msg); parentUI.HandleIBMessage(sqm); }
//interface req public virtual void deltaNeutralValidation(int reqId, UnderComp underComp) { addTextToBox("DeltaNeutralValidation. " + reqId + ", ConId: " + underComp.ConId + ", Delta: " + underComp.Delta + ", Price: " + underComp.Price + "\n"); }
//interface req public virtual void managedAccounts(string accountsList) { addTextToBox("managedAccounts. \n"); //parentUI.HandleMessage(new ManagedAccountsMessage(accountsList)); }
//interface req public virtual void tickOptionComputation(int tickerId, int field, double impliedVolatility, double delta, double optPrice, double pvDividend, double gamma, double vega, double theta, double undPrice) { }
//interface req public virtual void accountSummary(int reqId, string account, string tag, string value, string currency) { //parentUI.HandleMessage(new AccountSummaryMessage(reqId, account, tag, value, currency)); addTextToBox("accountSummary. \n"); }
//interface req public virtual void accountSummaryEnd(int reqId) { //parentUI.HandleMessage(new AccountSummaryEndMessage(reqId)); addTextToBox("accountSummaryEnd. \n"); }
//interface req public virtual void updateAccountValue(string key, string value, string currency, string accountName) { //parentUI.HandleMessage(new AccountValueMessage(key, value, currency, accountName)); addTextToBox("updateAccountValue. \n"); }
//interface req public virtual void updateAccountTime(string timestamp) { addTextToBox("updateAccountTime. \n"); //parentUI.HandleMessage(new UpdateAccountTimeMessage(timestamp)); }
//interface req public virtual void accountDownloadEnd(string account) { addTextToBox("accountDownloadEnd. \n"); //parentUI.HandleMessage(new AccountDownloadEndMessage(account)); }
[MethodImpl(MethodImplOptions.Synchronized)] private void sendHedgeFutureOrders(int orderId, double optfilled, double remaining) { List<SQOrder> matchFut = new List<SQOrder>(); SQOrder futOrder = AllVariables.FutureOrderParkingArea[orderId]; SQOrder futOrderNew = new SQOrder(futOrder); if (futOrder._futRemainRatio < 0.01 || futOrder._futRemainQuantity < 0.5) return;
futOrderNew._optRemainRatio = remaining / futOrder._optOriginalQuantity; futOrderNew._optFilledRatio = 1 - futOrderNew._optFilledRatio;
if (futOrderNew._optRemainRatio < 0.01) { AllVariables.FutureOrderParkingArea.Remove(orderId); futOrder._quantity = futOrder._futRemainQuantity; matchFut.Add(futOrder); } else { double ratoDiff = futOrder._futRemainRatio - futOrderNew._optRemainRatio; if (ratoDiff < 0.01) return; int tradeQuantity = (int) Math.Round(ratoDiff * futOrder._futOriginalQuantity); if (tradeQuantity < 1) return; futOrderNew._futRemainRatio = futOrderNew._optRemainRatio; futOrderNew._futFilledRatio = futOrderNew._optFilledRatio; futOrderNew._futRemainQuantity = futOrder._futRemainQuantity - tradeQuantity; if (futOrderNew._futRemainQuantity < 1) return; AllVariables.FutureOrderParkingArea[orderId] = futOrderNew; futOrder._quantity = tradeQuantity; matchFut.Add(futOrder); } this.SendFutureOrder (LocalMessage.Constants.MessageId.TICKET_FUT_LMT, matchFut); }
//interface req public virtual void orderStatus(int orderId, string status, double filled, double remaining, double avgFillPrice, int permId, int parentId, double lastFillPrice, int clientId, string whyHeld) { //addTextToBox("orderStatus. \n"); if (AllVariables.FutureOrderParkingArea.ContainsKey(orderId) && filled > 0.9) { sendHedgeFutureOrders(orderId, filled, remaining); }
string sqTktId = Program.allVariables.ticketId2ibIdMap.getTicketId(orderId); if (sqTktId != "") { SQMessage sqm = new SQTicketStatusMessage( LocalMessage.Constants.ApplicationIds.UDP, sqTktId, orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld); parentUI.HandleIBMessage(sqm); } else { SQMessage sqm = Program.allVariables.MessageService. createSQErrorMessage( LocalMessage.Constants.ApplicationIds.UDP, LocalMessage.Constants.ActionIds.GenericInfo, "IB orderStatus error: ib reqid not matched in sqTicketId"); sqm._mqTopic = LocalMessage.Constants.MQTopic.TicketStatus; parentUI.HandleIBMessage(sqm); } //parentUI.HandleMessage(new OrderStatusMessage(orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld)); }
//interface req public virtual void openOrder(int orderId, Contract contract, Order order, OrderState orderState) { //parentUI.HandleMessage(new OpenOrderMessage(orderId, contract, order, orderState)); addTextToBox("openOrder. \n"); }
//interface req public virtual void openOrderEnd() { //parentUI.HandleMessage(new OpenOrderEndMessage()); addTextToBox("openOrderEnd. \n"); }
//interface req public virtual void contractDetails(int reqId, ContractDetails contractDetails) { int dtlReqId = reqId; int sqConId = dtlReqId - AllVariables.IBContractDetailReqIdBase; string tsymbol = contractDetails.Summary.Symbol; string secType = contractDetails.Summary.SecType; int conId = contractDetails.Summary.ConId; string exchange = contractDetails.Summary.Exchange; SQMessage sqm = Program.allVariables.MessageService.createSQConDetailMessage ( LocalMessage.Constants.ApplicationIds.UDP, sqConId, conId, tsymbol, secType, exchange); parentUI.HandleIBMessage(sqm); }
//interface req public virtual void contractDetailsEnd(int reqId) { addTextToBox("contractDetailsEnd message:" + reqId); //parentUI.HandleIBConDetailEndCallback(reqId); //parentUI.HandleMessage(new ContractDetailsEndMessage()); }
//interface req public virtual void execDetails(int reqId, Contract contract, Execution execution) { //parentUI.HandleMessage(new ExecutionMessage(reqId, contract, execution)); addTextToBox("execDetails. " + reqId + "\n"); }
//interface req public virtual void execDetailsEnd(int reqId) { addTextToBox("ExecDetailsEnd. " + reqId + "\n"); }
//interface req public virtual void commissionReport(CommissionReport commissionReport) { //parentUI.HandleMessage(new CommissionMessage(commissionReport)); addTextToBox("commissionReport \n"); }
//interface req public virtual void fundamentalData(int reqId, string data) { //parentUI.HandleMessage(new FundamentalsMessage(data)); addTextToBox("fundamentalData \n"); }
//interface req public virtual void historicalData(int reqId, string date, double open, double high, double low, double close, int volume, int count, double WAP, bool hasGaps) { addTextToBox("historicalData \n"); // parentUI.HandleMessage(new HistoricalDataMessage(reqId, date, open, high, low, close, volume, count, WAP, hasGaps)); }
//interface req public virtual void historicalDataEnd(int reqId, string startDate, string endDate) { addTextToBox("historicalDataEnd \n"); //parentUI.HandleMessage(new HistoricalDataEndMessage(reqId, startDate, endDate)); }
//interface req public virtual void marketDataType(int reqId, int marketDataType) { addTextToBox("MarketDataType. " + reqId + ", Type: " + marketDataType + "\n"); }
//interface req public virtual void updateMktDepth(int tickerId, int position, int operation, int side, double price, int size) { addTextToBox("updateMktDepth \n"); // parentUI.HandleMessage(new DeepBookMessage(tickerId, position, operation, side, price, size, "")); }
//interface req public virtual void updateMktDepthL2(int tickerId, int position, string marketMaker, int operation, int side, double price, int size) { addTextToBox("updateMktDepthL2 \n"); //parentUI.HandleMessage(new DeepBookMessage(tickerId, position, operation, side, price, size, marketMaker)); }
//interface req public virtual void updateNewsBulletin(int msgId, int msgType, String message, String origExchange) { addTextToBox("News Bulletins. " + msgId + " - Type: " + msgType + ", Message: " + message + ", Exchange of Origin: " + origExchange + "\n"); }
//interface req public virtual void position(string account, Contract contract, double pos, double avgCost) { //parentUI.HandleMessage(new PositionMessage(account, contract, pos, avgCost)); addTextToBox("Position \n"); }
//interface req public virtual void positionEnd() { addTextToBox("PositionEnd \n"); }
//interface req public virtual void realtimeBar(int reqId, long time, double open, double high, double low, double close, long volume, double WAP, int count) { addTextToBox("realtimeBar.\n"); //parentUI.HandleIBMessage(new RealTimeBarMessage(reqId, time, open, high, low, close, volume, WAP, count)); }
//interface req public virtual void scannerParameters(string xml) { addTextToBox("ScannerParameters. " + xml + "\n"); }
//interface req public virtual void scannerData(int reqId, int rank, ContractDetails contractDetails, string distance, string benchmark, string projection, string legsStr) { addTextToBox("scannerData\r\n"); }
//interface req public virtual void scannerDataEnd(int reqId) { addTextToBox("ScannerDataEnd. " + reqId + "\r\n"); }
//interface req public virtual void receiveFA(int faDataType, string faXmlData) { //parentUI.HandleMessage(new AdvisorDataMessage(faDataType, faXmlData)); addTextToBox("Receiving receiveFA."); }
//interface req public virtual void bondContractDetails(int requestId, ContractDetails contractDetails) { addTextToBox("Receiving bond contract details."); }
//interface req public virtual void verifyMessageAPI(string apiData) { addTextToBox("verifyMessageAPI: " + apiData); }
//interface req public virtual void verifyCompleted(bool isSuccessful, string errorText) { addTextToBox("verifyCompleted. IsSuccessfule: " + isSuccessful + " - Error: " + errorText); }
//interface req public virtual void displayGroupList(int reqId, string groups) { addTextToBox("DisplayGroupList. Request: " + reqId + ", Groups" + groups); }
//interface req public virtual void displayGroupUpdated(int reqId, string contractInfo) { addTextToBox("displayGroupUpdated. Request: " + reqId + ", ContractInfo: " + contractInfo); }
//interface req public virtual void updatePortfolio(Contract con, double position, double marketPrice, double marketValue, double averageCost, double unrealisedPNL, double realizedPnL, string accntName) { double strike = 0; string tright = "F"; if (con.SecType == "OPT") { strike = con.Strike; tright = con.Right; } SQIBPortPositionMessage sqibpmsg = new SQIBPortPositionMessage( ApplicationIds.UDP, con.ConId, con.Symbol, con.SecType, con.LastTradeDateOrContractMonth, strike, tright, con.Multiplier, con.Exchange, con.Currency, position, marketPrice, marketValue, averageCost, unrealisedPNL, realizedPnL, accntName, Program.allVariables.getIBAccountID() ); parentUI.HandleIBMessage(sqibpmsg); addTextToBox("updatePortfolio"); }
//interface req public virtual void verifyAndAuthMessageAPI(string apiData, string xyzChallenge) { addTextToBox("verifyAndAuthMessageAPI"); }
//interface req public virtual void verifyAndAuthCompleted(bool apiData, string errText) { addTextToBox("verifyAndAuthCompleted"); }
//interface req -- not implemenetd? public virtual void connectAck() { SQMessage sqm = Program.allVariables.MessageService. createSQMessage( MQTopic.NOACTIVE_IB, ApplicationIds.IBClient, ActionIds.IBResponse, SubjectIds.GenericText, MessageId.ZERO, "IB connectAck: connection established."); parentUI.HandleIBMessage(sqm); }
//interface req public virtual void positionMulti(int requestId, string accnt, string modelCode, Contract contract, double pos, double avgCost) { addTextToBox("positionMulti"); } //interface req public virtual void positionMultiEnd(int requestId) { addTextToBox("positionMultiEnd"); }
//interface req public virtual void accountUpdateMulti(int requestId, string account, string modelCode, string key, string value, string ccy) { addTextToBox("accountUpdateMulti"); }
//interface req public virtual void accountUpdateMultiEnd(int requestId) { addTextToBox("accountUpdateMultiEnd"); }
//interface req public virtual void securityDefinitionOptionParameter(int requestId, string exchange, int underlyingConId, string tradingClass, string multiplier, HashSet<string> expirations, HashSet<double> strikes) { addTextToBox("securityDefinitionOptionParameter"); }
//interface req public virtual void securityDefinitionOptionParameterEnd(int requestId) { addTextToBox("securityDefinitionOptionParameterEnd"); }
//interface req public virtual void softDollarTiers(int requestId, SoftDollarTier[] tiers) { addTextToBox("softDollarTiers"); } } }
m
magicflute
接近 4 年
3 楼
太赞了 大牛 多谢分享
n
nj_guy
接近 4 年
4 楼
回复
3楼magicflute的帖子
不客气,这是以前自己没事儿在IB上trade写的玩的code,后来自己工作的公司对员工个人交易各种限制,实在无法继续,就不玩了。应该包括期货和期权下单和市场数据的接口。
很多年以前的事了,有些自己也忘了。
请输入帖子链接
收藏帖子
namespace UDPApp.IBListener { public class SQIBClient : EWrapper { static AutoResetEvent autoResetEvent = new AutoResetEvent(false);
private EClientSocket clientSocket; public readonly EReaderSignal signal; private UDPPanel parentUI; private int clientId; private LocalMessage.SyncronizedCounter orderIdCounter;
public bool IsConnected() { return clientSocket.IsConnected(); }
public SQIBClient(UDPPanel parent, int inClinetId) { parentUI = parent; clientId = inClinetId; signal = new EReaderMonitorSignal(); clientSocket = new EClientSocket(this, signal); orderIdCounter = LocalMessage.SyncronizedCounter.newCounter(1); }
public SQIBClient(UDPPanel parent) { parentUI = parent; clientId = ApplicationIds.UDP; signal = new EReaderMonitorSignal(); clientSocket = new EClientSocket(this, signal); orderIdCounter = LocalMessage.SyncronizedCounter.newCounter(1); }
//Additional Method public void Dispose() { if (clientSocket != null && IsConnected()) clientSocket.Close(); if (clientSocket != null) clientSocket = null; }
//Additional Method private void addTextToBox(string text) { SQMessage sqm = Program.allVariables.MessageService. createSQGenericMessage(ApplicationIds.IBClient, ActionIds.GenericInfo, text); parentUI.HandleIBMessage(sqm); }
//Additional public void Connect() { try { this.ClientSocket.eConnect(Program.allVariables.IBIP, Program.allVariables.IBPort, clientId); var reader = new EReader(this.ClientSocket, signal);
reader.Start();
new Thread(() => { while (this.ClientSocket.IsConnected()) { signal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); } catch (Exception e) { string errmsg = "" + e; throw new Exception(errmsg); }
}
//Additional public void SendMktDataReqForContracts(Dictionary<int, Contract> IBContracts) { if (IsConnected()) { List<TagValue> mktDataOptions = new List<TagValue>(); foreach (KeyValuePair<int, Contract> kvp in IBContracts) { ClientSocket.reqMktData(kvp.Key, kvp.Value, "233", false, mktDataOptions); } } else { string errmsg = "IBCLient SendMktDataReqForContracts Exception: not connected"; SQMessage sqm = Program.allVariables.MessageService. createSQMessage( MQTopic.IBContractDetail, ApplicationIds.IBClient, ActionIds.IBMktDataSendRequest, SubjectIds.Error, MessageId.ZERO, errmsg); parentUI.HandleIBMessage(sqm); } }
//Additional [MethodImpl(MethodImplOptions.Synchronized)] public void SendOrder(int AppId, int orderType, List<SQOrder> sqorderList) { if (AppId == ApplicationIds.SpreadBox) { SendSpreadBoxOrder(orderType, sqorderList); } else if(AppId == ApplicationIds.Scalper) { SendFutureOrder(LocalMessage.Constants.MessageId.TICKET_FUT_GTC, sqorderList); } else if (AppId == ApplicationIds.VolVault) { SendFutureOrder(LocalMessage.Constants.MessageId.TICKET_FUT_LMT, sqorderList); } }
private void SendSpreadBoxOrder(int orderType, List<SQOrder> sqorderList) { if (IsConnected()) { bool isOptHedgePair = false; int optIndex = 0; int futIndex = 0; if (sqorderList.Count == 2) { string type0 = sqorderList[0]._ibContract.SecType; string type1 = sqorderList[1]._ibContract.SecType; if (type0 == "FUT" && type1 == "OPT") { isOptHedgePair = true; optIndex = 1; futIndex = 0; if (sqorderList[futIndex]._optOriginalQuantity == 0) { sqorderList[futIndex]._optOriginalQuantity = sqorderList[optIndex]._quantity; sqorderList[futIndex]._optRemainRatio = 1; }
} else if (type0 == "OPT" && type1 == "FUT") { isOptHedgePair = true; optIndex = 0; futIndex = 1; if (sqorderList[futIndex]._optOriginalQuantity == 0) { sqorderList[futIndex]._optOriginalQuantity = sqorderList[optIndex]._quantity; sqorderList[futIndex]._optRemainRatio = 1; } } }
if (isOptHedgePair) { //int sqibId = orderIdCounter.next(); int sqibId = SendOrder(orderType, sqorderList[optIndex]); AllVariables.FutureOrderParkingArea[sqibId] = sqorderList[futIndex]; } else { foreach (SQOrder sqorder in sqorderList) { //int sqibId = orderIdCounter.next(); SendOrder(orderType, sqorder); } }
} else { string errmsg = "IBCLient SendOrder Exception: not connected"; SQMessage sqm = Program.allVariables.MessageService. createSQErrorMessage( ApplicationIds.IBClient, ActionIds.GenericInfo, errmsg); parentUI.HandleIBMessage(sqm); } }
private void SendFutureOrder(int futOrderType, List<SQOrder> sqorderList) { if (IsConnected()) { foreach (SQOrder sqorder in sqorderList) { //int sqibId = orderIdCounter.next(); SendOrder(futOrderType, sqorder); }
} else { string errmsg = "IBCLient SendOrder Exception: not connected"; SQMessage sqm = Program.allVariables.MessageService. createSQErrorMessage( ApplicationIds.IBClient, ActionIds.GenericInfo, errmsg); parentUI.HandleIBMessage(sqm); } }
//return ib order id private int SendOrder(int orderType, SQOrder sqorder) { if (IsConnected()) { string IBAccountId = Program.allVariables.getIBAccountID(); Order order; if (sqorder._ibContract.SecType == "OPT") { if (orderType == LocalMessage.Constants.MessageId.TICKET_OPT_LMT) { order = OrderManager.LimitOrder (IBAccountId, sqorder._buySell, sqorder._quantity, sqorder._prix); } else { order = OrderManager.IOCLimitOrder (IBAccountId, sqorder._buySell, sqorder._quantity, sqorder._prix); } } else { if (orderType == LocalMessage.Constants.MessageId.TICKET_FUT_GTC) { order = OrderManager.GTCLimitOrder (IBAccountId, sqorder._buySell, sqorder._quantity, sqorder._prix); } else { order = OrderManager.LimitOrder (IBAccountId, sqorder._buySell, sqorder._quantity, sqorder._prix); } }
int sqibId = orderIdCounter.next(); ClientSocket.placeOrder(sqibId, sqorder._ibContract, order); Program.allVariables.ticketId2ibIdMap.add(sqorder._tktId, sqibId); //string logmsg = "BuySell=" + BuySell + ",Quantity=" + quantity // + ",Price=" + price + ",SQTicketId=" + SQTicketId; //Program.allVariables.ibOrderLogger.log(logmsg); return sqibId; } else { string errmsg = "IBCLient SendOrder Exception: not connected"; SQMessage sqm = Program.allVariables.MessageService. createSQErrorMessage( ApplicationIds.IBClient, ActionIds.GenericInfo, errmsg); parentUI.HandleIBMessage(sqm); return Int32.MinValue; } }
public void CancelOrder(int ibOrderId) { ClientSocket.cancelOrder(ibOrderId); }
public void SendAccountUpdateRequest(bool isStart) { if (IsConnected()) { string IBAccountId = Program.allVariables.getIBAccountID(); ClientSocket.reqAccountUpdates(isStart, IBAccountId); } else { string errmsg = "IBCLient reqAccountUpdates Exception: not connected"; SQMessage sqm = Program.allVariables.MessageService. createSQErrorMessage( ApplicationIds.IBClient, ActionIds.GenericInfo, errmsg); parentUI.HandleIBMessage(sqm); } }
public void SendAutoOpenOrderStatusRequest(bool isStart) { if (IsConnected()) { string IBAccountId = Program.allVariables.getIBAccountID(); ClientSocket.reqAutoOpenOrders(isStart); } else { string errmsg = "IBCLient reqAccountUpdates Exception: not connected"; SQMessage sqm = Program.allVariables.MessageService. createSQErrorMessage( ApplicationIds.IBClient, ActionIds.GenericInfo, errmsg); parentUI.HandleIBMessage(sqm); } }
//Aditional public void SyncOrderIdWithIB() { ClientSocket.reqIds(-1); autoResetEvent.WaitOne(); }
//Additional public void SendMktDataReqForContract(int reqId, Contract aIBContract) { if (IsConnected()) { List<TagValue> mktDataOptions = new List<TagValue>(); ClientSocket.reqMktData(reqId, aIBContract, "233", false, mktDataOptions); } else { string errmsg = "IBCLient SendMktDataReqForContract Exception: not connected"; SQMessage sqm = Program.allVariables.MessageService. createSQErrorMessage( ApplicationIds.IBClient, ActionIds.IBMktDataSendRequest, errmsg); parentUI.HandleIBMessage(sqm); } }
//Additional public void SendDetailReqForContract(int reqId, Contract aIBContract) { if (IsConnected()) { List<TagValue> mktDataOptions = new List<TagValue>(); ClientSocket.reqContractDetails(reqId, aIBContract); } else { string errmsg = "IBCLient SendDetailReqForContract Exception: not connected"; SQMessage sqm = Program.allVariables.MessageService. createSQErrorMessage( ApplicationIds.IBClient, ActionIds.IBContractDetailSendRequest, errmsg); parentUI.HandleIBMessage(sqm); } }
public EClientSocket ClientSocket { get { return clientSocket; } set { clientSocket = value; } }
//interface req public virtual void error(Exception e) { string errmsg = "Error: " + e; SQMessage sqm = Program.allVariables.MessageService. createSQMessage( MQTopic.NOACTIVE_IB, ApplicationIds.IBClient, ActionIds.IBResponse, SubjectIds.IBError, MessageId.ZERO, errmsg); parentUI.HandleIBMessage(sqm); }
//interface req public virtual void error(string str) { SQMessage sqm = Program.allVariables.MessageService. createSQMessage( MQTopic.NOACTIVE_IB, ApplicationIds.IBClient, ActionIds.IBResponse, SubjectIds.IBError, MessageId.ZERO, "Error: " + str); parentUI.HandleIBMessage(sqm); }
//interface req public virtual void error(int reqid, int errorCode, string errorMsg) { SQMessage sqm = Program.allVariables.MessageService. createSQMessage( MQTopic.NOACTIVE_IB, ApplicationIds.IBClient, ActionIds.IBResponse, SubjectIds.IBError, reqid, "Error Code:" + errorCode + ", " + errorMsg); parentUI.HandleIBMessage(sqm); }
//interface req public virtual void connectionClosed() { SQMessage sqm = Program.allVariables.MessageService. createSQMessage( MQTopic.NOACTIVE_IB, ApplicationIds.IBClient, ActionIds.IBResponse, SubjectIds.GenericText, MessageId.ZERO, StdStringMessage.IBConnectionClosed); parentUI.HandleIBMessage(sqm); }
//interface req public virtual void currentTime(long time) { string msgstr = "Current Time: " + time + "\n"; SQMessage sqm = Program.allVariables.MessageService. createSQMessage( MQTopic.NOACTIVE_IB, ApplicationIds.IBClient, ActionIds.IBResponse, SubjectIds.Time, MessageId.ZERO, msgstr); parentUI.HandleIBMessage(sqm); }
//interface req public virtual void tickPrice(int tickerId, int field, double price, int canAutoExecute) { int contractId = tickerId - AllVariables.IBMktDataRequestIdBase; int subjectId; if (field == 1) subjectId = SubjectIds.TickPriceBid; else if (field == 2) subjectId = SubjectIds.TickPriceAsk; else if (field == 4) subjectId = SubjectIds.TickPriceLast; else if (field == 9) subjectId = SubjectIds.TickPriceClose; else subjectId = SubjectIds.IBError; //addTextToBox("Tick Price. Ticker Id:" + tickerId + ", Type: " + TickType.getField(field) + ", Price: " + price + "\n"); //parentUI.HandleIBMessage(new TickPriceMessage(tickerId, field, price, canAutoExecute)); SQMessage sqm = Program.allVariables.MessageService. createSQMessage( MQTopic.MktData, ApplicationIds.IBClient, ActionIds.MktDataPublish, subjectId, contractId, price); parentUI.HandleIBMessage(sqm); }
//addTextToBox("Tick Size. Ticker Id:" + tickerId + ", Type: " + TickType.getField(field) + ", Size: " + size + "\n"); //parentUI.HandleIBMessage(new TickSizeMessage(tickerId, field, size)); SQMessage sqm = Program.allVariables.MessageService. createSQMessage( MQTopic.MktData, ApplicationIds.IBClient, ActionIds.MktDataPublish, subjectId, contractId, size); parentUI.HandleIBMessage(sqm); }
//interface req public virtual void tickString(int tickerId, int tickType, string value) { //addTextToBox("Tick string. Ticker Id:" + tickerId + ", Type: " + TickType.getField(tickType) + ", Value: " + value + "\n"); int contractId = tickerId - AllVariables.IBMktDataRequestIdBase; if (tickType == 48) { int subjectId = SubjectIds.TickRTVolume; //Debug.WriteLine("RT48 Value=" + value); value = value.Replace(';', '='); SQMessage sqm = Program.allVariables.MessageService. createSQMessage( MQTopic.MktData, ApplicationIds.IBClient, ActionIds.MktDataPublish, subjectId, contractId, value); parentUI.HandleIBMessage(sqm); } }
//interface req public virtual void tickGeneric(int tickerId, int field, double value) { addTextToBox("Tick Generic. Ticker Id:" + tickerId + ", Field: " + TickType.getField(field) + ", Value: " + value + "\n"); }
//interface req public virtual void tickEFP(int tickerId, int tickType, double basisPoints, string formattedBasisPoints, double impliedFuture, int holdDays, string futureExpiry, double dividendImpact, double dividendsToExpiry) { addTextToBox("TickEFP. " + tickerId + ", Type: " + tickType + ", BasisPoints: " + basisPoints + ", FormattedBasisPoints: " + formattedBasisPoints + ", ImpliedFuture: " + impliedFuture + ", HoldDays: " + holdDays + ", FutureExpiry: " + futureExpiry + ", DividendImpact: " + dividendImpact + ", DividendsToExpiry: " + dividendsToExpiry + "\n"); }
//interface req public virtual void tickSnapshotEnd(int tickerId) { addTextToBox("TickSnapshotEnd: " + tickerId + "\n"); }
//interface req public virtual void nextValidId(int orderId) { //isConnected = true; //nextOrderId = orderId; orderIdCounter.reset(orderId); autoResetEvent.Set(); string msg = "IBCLient Sync Next Available Order ID:" + orderId; SQMessage sqm = Program.allVariables. MessageService.createSQGenericMessage ( ApplicationIds.IBClient, ActionIds.IBResponse, msg); parentUI.HandleIBMessage(sqm); }
//interface req public virtual void deltaNeutralValidation(int reqId, UnderComp underComp) { addTextToBox("DeltaNeutralValidation. " + reqId + ", ConId: " + underComp.ConId + ", Delta: " + underComp.Delta + ", Price: " + underComp.Price + "\n"); }
//interface req public virtual void managedAccounts(string accountsList) { addTextToBox("managedAccounts. \n"); //parentUI.HandleMessage(new ManagedAccountsMessage(accountsList)); }
//interface req public virtual void tickOptionComputation(int tickerId, int field, double impliedVolatility, double delta, double optPrice, double pvDividend, double gamma, double vega, double theta, double undPrice) { }
//interface req public virtual void accountSummary(int reqId, string account, string tag, string value, string currency) { //parentUI.HandleMessage(new AccountSummaryMessage(reqId, account, tag, value, currency)); addTextToBox("accountSummary. \n"); }
//interface req public virtual void accountSummaryEnd(int reqId) { //parentUI.HandleMessage(new AccountSummaryEndMessage(reqId)); addTextToBox("accountSummaryEnd. \n"); }
//interface req public virtual void updateAccountValue(string key, string value, string currency, string accountName) { //parentUI.HandleMessage(new AccountValueMessage(key, value, currency, accountName)); addTextToBox("updateAccountValue. \n"); }
//interface req public virtual void updateAccountTime(string timestamp) { addTextToBox("updateAccountTime. \n"); //parentUI.HandleMessage(new UpdateAccountTimeMessage(timestamp)); }
//interface req public virtual void accountDownloadEnd(string account) { addTextToBox("accountDownloadEnd. \n"); //parentUI.HandleMessage(new AccountDownloadEndMessage(account)); }
[MethodImpl(MethodImplOptions.Synchronized)] private void sendHedgeFutureOrders(int orderId, double optfilled, double remaining) { List<SQOrder> matchFut = new List<SQOrder>(); SQOrder futOrder = AllVariables.FutureOrderParkingArea[orderId]; SQOrder futOrderNew = new SQOrder(futOrder); if (futOrder._futRemainRatio < 0.01 || futOrder._futRemainQuantity < 0.5) return;
futOrderNew._optRemainRatio = remaining / futOrder._optOriginalQuantity; futOrderNew._optFilledRatio = 1 - futOrderNew._optFilledRatio;
if (futOrderNew._optRemainRatio < 0.01) { AllVariables.FutureOrderParkingArea.Remove(orderId); futOrder._quantity = futOrder._futRemainQuantity; matchFut.Add(futOrder); } else { double ratoDiff = futOrder._futRemainRatio - futOrderNew._optRemainRatio; if (ratoDiff < 0.01) return; int tradeQuantity = (int) Math.Round(ratoDiff * futOrder._futOriginalQuantity); if (tradeQuantity < 1) return; futOrderNew._futRemainRatio = futOrderNew._optRemainRatio; futOrderNew._futFilledRatio = futOrderNew._optFilledRatio; futOrderNew._futRemainQuantity = futOrder._futRemainQuantity - tradeQuantity; if (futOrderNew._futRemainQuantity < 1) return; AllVariables.FutureOrderParkingArea[orderId] = futOrderNew; futOrder._quantity = tradeQuantity; matchFut.Add(futOrder); } this.SendFutureOrder (LocalMessage.Constants.MessageId.TICKET_FUT_LMT, matchFut); }
//interface req public virtual void orderStatus(int orderId, string status, double filled, double remaining, double avgFillPrice, int permId, int parentId, double lastFillPrice, int clientId, string whyHeld) { //addTextToBox("orderStatus. \n"); if (AllVariables.FutureOrderParkingArea.ContainsKey(orderId) && filled > 0.9) { sendHedgeFutureOrders(orderId, filled, remaining); }
string sqTktId = Program.allVariables.ticketId2ibIdMap.getTicketId(orderId); if (sqTktId != "") { SQMessage sqm = new SQTicketStatusMessage( LocalMessage.Constants.ApplicationIds.UDP, sqTktId, orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld); parentUI.HandleIBMessage(sqm); } else { SQMessage sqm = Program.allVariables.MessageService. createSQErrorMessage( LocalMessage.Constants.ApplicationIds.UDP, LocalMessage.Constants.ActionIds.GenericInfo, "IB orderStatus error: ib reqid not matched in sqTicketId"); sqm._mqTopic = LocalMessage.Constants.MQTopic.TicketStatus; parentUI.HandleIBMessage(sqm); } //parentUI.HandleMessage(new OrderStatusMessage(orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld)); }
//interface req public virtual void openOrder(int orderId, Contract contract, Order order, OrderState orderState) { //parentUI.HandleMessage(new OpenOrderMessage(orderId, contract, order, orderState)); addTextToBox("openOrder. \n"); }
//interface req public virtual void openOrderEnd() { //parentUI.HandleMessage(new OpenOrderEndMessage()); addTextToBox("openOrderEnd. \n"); }
//interface req public virtual void contractDetails(int reqId, ContractDetails contractDetails) { int dtlReqId = reqId; int sqConId = dtlReqId - AllVariables.IBContractDetailReqIdBase; string tsymbol = contractDetails.Summary.Symbol; string secType = contractDetails.Summary.SecType; int conId = contractDetails.Summary.ConId; string exchange = contractDetails.Summary.Exchange; SQMessage sqm = Program.allVariables.MessageService.createSQConDetailMessage ( LocalMessage.Constants.ApplicationIds.UDP, sqConId, conId, tsymbol, secType, exchange); parentUI.HandleIBMessage(sqm); }
//interface req public virtual void contractDetailsEnd(int reqId) { addTextToBox("contractDetailsEnd message:" + reqId); //parentUI.HandleIBConDetailEndCallback(reqId); //parentUI.HandleMessage(new ContractDetailsEndMessage()); }
//interface req public virtual void execDetails(int reqId, Contract contract, Execution execution) { //parentUI.HandleMessage(new ExecutionMessage(reqId, contract, execution)); addTextToBox("execDetails. " + reqId + "\n"); }
//interface req public virtual void execDetailsEnd(int reqId) { addTextToBox("ExecDetailsEnd. " + reqId + "\n"); }
//interface req public virtual void commissionReport(CommissionReport commissionReport) { //parentUI.HandleMessage(new CommissionMessage(commissionReport)); addTextToBox("commissionReport \n"); }
//interface req public virtual void fundamentalData(int reqId, string data) { //parentUI.HandleMessage(new FundamentalsMessage(data)); addTextToBox("fundamentalData \n"); }
//interface req public virtual void historicalData(int reqId, string date, double open, double high, double low, double close, int volume, int count, double WAP, bool hasGaps) { addTextToBox("historicalData \n"); // parentUI.HandleMessage(new HistoricalDataMessage(reqId, date, open, high, low, close, volume, count, WAP, hasGaps)); }
//interface req public virtual void historicalDataEnd(int reqId, string startDate, string endDate) { addTextToBox("historicalDataEnd \n"); //parentUI.HandleMessage(new HistoricalDataEndMessage(reqId, startDate, endDate)); }
//interface req public virtual void marketDataType(int reqId, int marketDataType) { addTextToBox("MarketDataType. " + reqId + ", Type: " + marketDataType + "\n"); }
//interface req public virtual void updateMktDepth(int tickerId, int position, int operation, int side, double price, int size) { addTextToBox("updateMktDepth \n"); // parentUI.HandleMessage(new DeepBookMessage(tickerId, position, operation, side, price, size, "")); }
//interface req public virtual void updateMktDepthL2(int tickerId, int position, string marketMaker, int operation, int side, double price, int size) { addTextToBox("updateMktDepthL2 \n"); //parentUI.HandleMessage(new DeepBookMessage(tickerId, position, operation, side, price, size, marketMaker)); }
//interface req public virtual void updateNewsBulletin(int msgId, int msgType, String message, String origExchange) { addTextToBox("News Bulletins. " + msgId + " - Type: " + msgType + ", Message: " + message + ", Exchange of Origin: " + origExchange + "\n"); }
//interface req public virtual void position(string account, Contract contract, double pos, double avgCost) { //parentUI.HandleMessage(new PositionMessage(account, contract, pos, avgCost)); addTextToBox("Position \n"); }
//interface req public virtual void positionEnd() { addTextToBox("PositionEnd \n"); }
//interface req public virtual void realtimeBar(int reqId, long time, double open, double high, double low, double close, long volume, double WAP, int count) { addTextToBox("realtimeBar.\n"); //parentUI.HandleIBMessage(new RealTimeBarMessage(reqId, time, open, high, low, close, volume, WAP, count)); }
//interface req public virtual void scannerParameters(string xml) { addTextToBox("ScannerParameters. " + xml + "\n"); }
//interface req public virtual void scannerData(int reqId, int rank, ContractDetails contractDetails, string distance, string benchmark, string projection, string legsStr) { addTextToBox("scannerData\r\n"); }
//interface req public virtual void scannerDataEnd(int reqId) { addTextToBox("ScannerDataEnd. " + reqId + "\r\n"); }
//interface req public virtual void receiveFA(int faDataType, string faXmlData) { //parentUI.HandleMessage(new AdvisorDataMessage(faDataType, faXmlData)); addTextToBox("Receiving receiveFA."); }
//interface req public virtual void bondContractDetails(int requestId, ContractDetails contractDetails) { addTextToBox("Receiving bond contract details."); }
//interface req public virtual void verifyMessageAPI(string apiData) { addTextToBox("verifyMessageAPI: " + apiData); }
//interface req public virtual void verifyCompleted(bool isSuccessful, string errorText) { addTextToBox("verifyCompleted. IsSuccessfule: " + isSuccessful + " - Error: " + errorText); }
//interface req public virtual void displayGroupList(int reqId, string groups) { addTextToBox("DisplayGroupList. Request: " + reqId + ", Groups" + groups); }
//interface req public virtual void displayGroupUpdated(int reqId, string contractInfo) { addTextToBox("displayGroupUpdated. Request: " + reqId + ", ContractInfo: " + contractInfo); }
//interface req public virtual void updatePortfolio(Contract con, double position, double marketPrice, double marketValue, double averageCost, double unrealisedPNL, double realizedPnL, string accntName) { double strike = 0; string tright = "F"; if (con.SecType == "OPT") { strike = con.Strike; tright = con.Right; } SQIBPortPositionMessage sqibpmsg = new SQIBPortPositionMessage( ApplicationIds.UDP, con.ConId, con.Symbol, con.SecType, con.LastTradeDateOrContractMonth, strike, tright, con.Multiplier, con.Exchange, con.Currency, position, marketPrice, marketValue, averageCost, unrealisedPNL, realizedPnL, accntName, Program.allVariables.getIBAccountID() ); parentUI.HandleIBMessage(sqibpmsg); addTextToBox("updatePortfolio"); }
//interface req public virtual void verifyAndAuthMessageAPI(string apiData, string xyzChallenge) { addTextToBox("verifyAndAuthMessageAPI"); }
//interface req public virtual void verifyAndAuthCompleted(bool apiData, string errText) { addTextToBox("verifyAndAuthCompleted"); }
//interface req -- not implemenetd? public virtual void connectAck() { SQMessage sqm = Program.allVariables.MessageService. createSQMessage( MQTopic.NOACTIVE_IB, ApplicationIds.IBClient, ActionIds.IBResponse, SubjectIds.GenericText, MessageId.ZERO, "IB connectAck: connection established."); parentUI.HandleIBMessage(sqm); }
//interface req public virtual void positionMulti(int requestId, string accnt, string modelCode, Contract contract, double pos, double avgCost) { addTextToBox("positionMulti"); } //interface req public virtual void positionMultiEnd(int requestId) { addTextToBox("positionMultiEnd"); }
//interface req public virtual void accountUpdateMulti(int requestId, string account, string modelCode, string key, string value, string ccy) { addTextToBox("accountUpdateMulti"); }
//interface req public virtual void accountUpdateMultiEnd(int requestId) { addTextToBox("accountUpdateMultiEnd"); }
//interface req public virtual void securityDefinitionOptionParameter(int requestId, string exchange, int underlyingConId, string tradingClass, string multiplier, HashSet<string> expirations, HashSet<double> strikes) { addTextToBox("securityDefinitionOptionParameter"); }
//interface req public virtual void securityDefinitionOptionParameterEnd(int requestId) { addTextToBox("securityDefinitionOptionParameterEnd"); }
//interface req public virtual void softDollarTiers(int requestId, SoftDollarTier[] tiers) { addTextToBox("softDollarTiers"); } } }
不客气,这是以前自己没事儿在IB上trade写的玩的code,后来自己工作的公司对员工个人交易各种限制,实在无法继续,就不玩了。应该包括期货和期权下单和市场数据的接口。
很多年以前的事了,有些自己也忘了。