/// <summary> /// Sends a request for the history /// </summary> public string RequestHistory(TransportHistoryRequest request) { O2GRequestFactory factory = mSession.getRequestFactory(); O2GTimeframeCollection timeframes = factory.Timeframes; O2GTimeframe timeframe = timeframes[request.Timeframe]; int count = request.Count > 300 ? 300 : request.Count; O2GRequest rq = factory.createMarketDataSnapshotRequestInstrument(request.Instrument, timeframe, count); if (request.From != factory.ZERODATE || request.To != factory.ZERODATE) { DateTime from, to; from = request.From; to = request.To; /* * if (request.From != factory.ZERODATE) * from = mTimeConverter.convert(request.From, O2GTimeConverterTimeZone.EST, O2GTimeConverterTimeZone.UTC); * else * from = factory.ZERODATE; * * if (request.To != factory.ZERODATE) * to = mTimeConverter.convert(request.To, O2GTimeConverterTimeZone.EST, O2GTimeConverterTimeZone.UTC); * else * to = factory.ZERODATE; */ factory.fillMarketDataSnapshotRequestTime(rq, from, to, false); } mHistoryRequests[rq.RequestID] = request; mSession.sendRequest(rq); return(rq.RequestID); }
/***************************************************************************************************************/ /***** TRUE MARKET ORDERS *****/ /***************************************************************************************************************/ /* True Market Order */ public void CreateTrueMarketOrder(string sOfferID, string sAccountID, int iAmount, string sBuySell) { try { O2GRequestFactory factory = m_o2gsession.getRequestFactory(); if (factory == null) { return; } O2GValueMap valuemap = factory.createValueMap(); valuemap.setString(O2GRequestParamsEnum.Command, Constants.Commands.CreateOrder); valuemap.setString(O2GRequestParamsEnum.OrderType, Constants.Orders.TrueMarketOpen); valuemap.setString(O2GRequestParamsEnum.AccountID, sAccountID); // The identifier of the account the order should be placed for. valuemap.setString(O2GRequestParamsEnum.OfferID, sOfferID); // The identifier of the instrument the order should be placed for. valuemap.setString(O2GRequestParamsEnum.BuySell, sBuySell); // The order direction: Constants.Sell for "Sell", Constants.Buy for "Buy". valuemap.setInt(O2GRequestParamsEnum.Amount, iAmount); // The quantity of the instrument to be bought or sold. valuemap.setString(O2GRequestParamsEnum.CustomID, "TrueMarketOrder"); // The custom identifier of the order. if (sBuySell == "Buy") { valuemap.setString(O2GRequestParamsEnum.BuySell, Constants.Buy); } else { valuemap.setString(O2GRequestParamsEnum.BuySell, Constants.Sell); } O2GRequest request = factory.createOrderRequest(valuemap); m_o2gsession.sendRequest(request); } catch { } }
/// <summary> /// Request historical prices for the specified timeframe of the specified period /// </summary> /// <param name="session"></param> /// <param name="sInstrument"></param> /// <param name="sTimeframe"></param> /// <param name="dtFrom"></param> /// <param name="dtTo"></param> /// <param name="responseListener"></param> public void GetHistoryPrices(O2GSession session, string sInstrument, string sTimeframe, DateTime dtFrom, DateTime dtTo, ResponseListener responseListener) { O2GRequestFactory factory = session.getRequestFactory(); O2GTimeframe timeframe = factory.Timeframes[sTimeframe]; if (timeframe == null) { throw new Exception(string.Format("Timeframe '{0}' is incorrect!", sTimeframe)); } O2GRequest request = factory.createMarketDataSnapshotRequestInstrument(sInstrument, timeframe, 300); DateTime dtFirst = dtTo; do // cause there is limit for returned candles amount { factory.fillMarketDataSnapshotRequestTime(request, dtFrom, dtFirst, false); responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } // shift "to" bound to oldest datetime of returned data O2GResponse response = responseListener.GetResponse(); if (response != null && response.Type == O2GResponseType.MarketDataSnapshot) { O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory != null) { O2GMarketDataSnapshotResponseReader reader = readerFactory.createMarketDataSnapshotReader(response); if (reader.Count > 0) { if (DateTime.Compare(dtFirst, reader.getDate(0)) != 0) { dtFirst = reader.getDate(0); // earliest datetime of returned data } else { break; } } else { // Console.WriteLine("0 rows received"); updateLogDelegate(string.Format("0 rows received")); break; } } // PrintPrices(session, response); storeHistoryPriceToDataTable(session, response, sInstrument); // DateTime.Subtraction(dtTo, dtFirst)/ Subtraction long percent = (dtTo.Ticks - dtFirst.Ticks) * 100 / (dtTo.Ticks - dtFrom.Ticks); updateProcessDelegate((int)percent, this.InstrumentDT.Rows.Count); } else { break; } } while (dtFirst > dtFrom); }
/// <summary> /// Get initial Trades state /// </summary> /// <param name="session"></param> /// <param name="sAccountID"></param> /// <param name="responseListener"></param> /// <returns>TradesTable</returns> private static O2GTradesTableResponseReader GetTradesTable(O2GSession session, string sAccountID, ResponseListener responseListener) { O2GTradesTableResponseReader tradesTable = null; O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GRequest refreshTrades = requestFactory.createRefreshTableRequestByAccount(O2GTableType.Trades, sAccountID); responseListener.SetRequestID(refreshTrades.RequestID); session.sendRequest(refreshTrades); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } O2GResponse tradeResponse = responseListener.GetResponse(); if (tradeResponse != null) { O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory != null) { tradesTable = readerFactory.createTradesTableReader(tradeResponse); } } return(tradesTable); }
public async Task <IEnumerable <HistoricalData> > GetHistoricalDataAsync(string symbol) { return(await Task.Run(() => { var factory = _session.getRequestFactory(); var timeframes = factory.Timeframes; var timeframe = timeframes["m1"]; var request = factory.createMarketDataSnapshotRequestInstrument(symbol, timeframe, 300); var timeFrom = DateTime.Now.AddDays(-1); var timeTo = DateTime.Now; factory.fillMarketDataSnapshotRequestTime(request, timeFrom, timeTo, false); _session.sendRequest(request); _syncHistoryEvent.WaitOne(30000); var historyData = new List <HistoricalData>(); for (int i = 0; i < _marketDataSnapshotResponse.Count; i++) { historyData.Add(new HistoricalData { Date = _marketDataSnapshotResponse.getDate(i), Open = GetPrice(_marketDataSnapshotResponse.getAskOpen(i), _marketDataSnapshotResponse.getBidOpen(i)), High = GetPrice(_marketDataSnapshotResponse.getAskHigh(i), _marketDataSnapshotResponse.getBidHigh(i)), Low = GetPrice(_marketDataSnapshotResponse.getAskLow(i), _marketDataSnapshotResponse.getBidLow(i)), Close = GetPrice(_marketDataSnapshotResponse.getAskLow(i), _marketDataSnapshotResponse.getBidLow(i)), Volume = _marketDataSnapshotResponse.getVolume(i) }); } return historyData; })); }
/// <summary> /// Update margin requirements /// </summary> /// <param name="session"></param> /// <param name="responseListener"></param> private static void UpdateMargins(O2GSession session, ResponseListener responseListener) { O2GRequest request = null; O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GValueMap valueMap = requestFactory.createValueMap(); valueMap.setString(O2GRequestParamsEnum.Command, Constants.Commands.UpdateMarginRequirements); request = requestFactory.createOrderRequest(valueMap); responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } O2GResponse response = responseListener.GetResponse(); if (response != null && response.Type == O2GResponseType.MarginRequirementsResponse) { O2GResponseReaderFactory responseFactory = session.getResponseReaderFactory(); if (responseFactory != null) { responseFactory.processMarginRequirementsResponse(response); Console.WriteLine("Margin requirements have been updated"); } } }
/// <summary> /// Check if order exists /// </summary> /// <param name="session"></param> /// <param name="sAccountID"></param> /// <param name="sOrderID"></param> /// <param name="responseListener"></param> /// <returns></returns> private static bool IsOrderExists(O2GSession session, string sAccountID, string sOrderID, ResponseListener responseListener) { bool bHasOrder = false; O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GRequest request = requestFactory.createRefreshTableRequestByAccount(O2GTableType.Orders, sAccountID); if (request == null) { throw new Exception("Cannot create request"); } responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } O2GResponse response = responseListener.GetResponse(); O2GResponseReaderFactory responseReaderFactory = session.getResponseReaderFactory(); O2GOrdersTableResponseReader responseReader = responseReaderFactory.createOrdersTableReader(response); for (int i = 0; i < responseReader.Count; i++) { O2GOrderRow orderRow = responseReader.getRow(i); if (sOrderID.Equals(orderRow.OrderID)) { bHasOrder = true; break; } } return bHasOrder; }
/// <summary> /// Get orders data for closing all positions /// </summary> /// <param name="session"></param> /// <param name="sAccountID"></param> /// <param name="sOfferID"></param> /// <param name="responseListener"></param> /// <returns></returns> private static bool GetCloseOrdersData(O2GSession session, string sAccountID, string sOfferID, ResponseListener responseListener, out CloseOrdersData closeOrdersData) { O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GRequest request = requestFactory.createRefreshTableRequestByAccount(O2GTableType.Trades, sAccountID); responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } O2GResponse response = responseListener.GetResponse(); bool bIsTradesFound = false; closeOrdersData = new CloseOrdersData(); if (response != null) { O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory != null) { O2GTradesTableResponseReader tradesResponseReader = readerFactory.createTradesTableReader(response); for (int i = 0; i < tradesResponseReader.Count; i++) { O2GTradeRow trade = tradesResponseReader.getRow(i); if (!trade.OfferID.Equals(sOfferID)) { continue; } bIsTradesFound = true; string sBuySell = trade.BuySell; // Set opposite side OrderSide side = (sBuySell.Equals(Constants.Buy) ? OrderSide.Sell : OrderSide.Buy); if (closeOrdersData.OfferID.Equals(sOfferID)) { OrderSide currentSide = closeOrdersData.Side; if (currentSide != OrderSide.Both && currentSide != side) { closeOrdersData.Side = OrderSide.Both; } } else { closeOrdersData.OfferID = sOfferID; closeOrdersData.AccountID = sAccountID; closeOrdersData.Side = side; } } } } return(bIsTradesFound); }
/// <summary> /// Request historical prices for the specified timeframe of the specified period /// </summary> /// <param name="session"></param> /// <param name="sInstrument"></param> /// <param name="sTimeframe"></param> /// <param name="dtFrom"></param> /// <param name="dtTo"></param> /// <param name="responseListener"></param> public static void GetHistoryPrices(O2GSession session, string sInstrument, string sTimeframe, DateTime dtFrom, DateTime dtTo, ResponseListener responseListener) { O2GRequestFactory factory = session.getRequestFactory(); O2GTimeframe timeframe = factory.Timeframes[sTimeframe]; if (timeframe == null) { throw new Exception(string.Format("Timeframe '{0}' is incorrect!", sTimeframe)); } O2GRequest request = factory.createMarketDataSnapshotRequestInstrument(sInstrument, timeframe, 300); DateTime dtFirst = dtTo; do // cause there is limit for returned candles amount { factory.fillMarketDataSnapshotRequestTime(request, dtFrom, dtFirst, false, O2GCandleOpenPriceMode.PreviousClose); responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } // shift "to" bound to oldest datetime of returned data O2GResponse response = responseListener.GetResponse(); if (response != null && response.Type == O2GResponseType.MarketDataSnapshot) { O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory != null) { O2GMarketDataSnapshotResponseReader reader = readerFactory.createMarketDataSnapshotReader(response); if (reader.Count > 0) { if (DateTime.Compare(dtFirst, reader.getDate(0)) != 0) { dtFirst = reader.getDate(0); // earliest datetime of returned data } else { break; } } else { Console.WriteLine("0 rows received"); break; } } PrintPrices(session, response); } else { break; } } while (dtFirst > dtFrom); }
private List <FxBar> getHistoryPrices(O2GSession session, string instrument, Resolution resolution, DateTime startDateTime, DateTime endDateTime, int maxBars, GetHistoricalDataResponseListener responseListener) { O2GRequestFactory factory = session.getRequestFactory(); var tf = convert_Resolution_To_string(resolution); O2GTimeframe timeframe = factory.Timeframes[tf]; if (timeframe == null) { throw new TimeframeNotFoundException($"Timeframe '{resolution.TimeFrame}:{resolution.Size}' is incorrect!"); } O2GRequest request = factory.createMarketDataSnapshotRequestInstrument(instrument, timeframe, maxBars); factory.fillMarketDataSnapshotRequestTime(request, startDateTime, endDateTime, false); responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception($"{responseListener.Error}"); } O2GResponse response = responseListener.GetResponse(); List <FxBar> barList = new List <FxBar>(); if (response != null && response.Type == O2GResponseType.MarketDataSnapshot) { O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory != null) { O2GMarketDataSnapshotResponseReader reader = readerFactory.createMarketDataSnapshotReader(response); if (reader.Count > 0) { for (int i = 0; i < reader.Count; i++) { barList.Add(new FxBar { Open = reader.getBidOpen(i), High = reader.getBidHigh(i), Low = reader.getBidLow(i), Close = reader.getBidClose(i), Volume = reader.getVolume(i), DateTime = reader.getDate(i) }); } } } } return(barList); }
/// <summary> /// Request historical prices for the specified timeframe of the specified period /// </summary> /// <param name="session"></param> /// <param name="sInstrument"></param> /// <param name="sTimeframe"></param> /// <param name="dtFrom"></param> /// <param name="dtTo"></param> /// <param name="responseListener"></param> public static void GetHistoryPrices(O2GSession session, string sInstrument, string sTimeframe, DateTime dtFrom, DateTime dtTo, ResponseListener responseListener) { O2GRequestFactory factory = session.getRequestFactory(); O2GTimeframe timeframe = factory.Timeframes[sTimeframe]; if (timeframe == null) { throw new Exception(string.Format("Timeframe '{0}' is incorrect!", sTimeframe)); } O2GRequest request = factory.createMarketDataSnapshotRequestInstrument(sInstrument, timeframe, 300); DateTime dtFirst = dtTo; do // cause there is limit for returned candles amount { factory.fillMarketDataSnapshotRequestTime(request, dtFrom, dtFirst, false); responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } // shift "to" bound to oldest datetime of returned data O2GResponse response = responseListener.GetResponse(); if (response != null && response.Type == O2GResponseType.MarketDataSnapshot) { O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory != null) { O2GMarketDataSnapshotResponseReader reader = readerFactory.createMarketDataSnapshotReader(response); if (reader.Count > 0) { if (DateTime.Compare(dtFirst, reader.getDate(0)) != 0) { dtFirst = reader.getDate(0); // earliest datetime of returned data } else { break; } } else { Console.WriteLine("0 rows received"); break; } } PrintPrices(session, response); } else { break; } } while (dtFirst > dtFrom); }
/// <summary> /// Get orders data for closing all positions /// </summary> /// <param name="session"></param> /// <param name="sAccountID"></param> /// <param name="responseListener"></param> /// <returns></returns> private static Dictionary <string, CloseOrdersData> GetCloseOrdersData(O2GSession session, string sAccountID, ResponseListener responseListener) { Dictionary <string, CloseOrdersData> closeOrdersData = new Dictionary <string, CloseOrdersData>(); O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GRequest request = requestFactory.createRefreshTableRequestByAccount(O2GTableType.Trades, sAccountID); responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } O2GResponse response = responseListener.GetResponse(); if (response != null) { O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory != null) { O2GTradesTableResponseReader tradesResponseReader = readerFactory.createTradesTableReader(response); for (int i = 0; i < tradesResponseReader.Count; i++) { O2GTradeRow trade = tradesResponseReader.getRow(i); string sOfferID = trade.OfferID; string sBuySell = trade.BuySell; // Set opposite side OrderSide side = (sBuySell.Equals(Constants.Buy) ? OrderSide.Sell : OrderSide.Buy); if (closeOrdersData.ContainsKey(sOfferID)) { OrderSide currentSide = closeOrdersData[sOfferID].Side; if (currentSide != OrderSide.Both && currentSide != side) { closeOrdersData[sOfferID].Side = OrderSide.Both; } } else { CloseOrdersData data = new CloseOrdersData(sAccountID, side); closeOrdersData.Add(sOfferID, data); } } } } return(closeOrdersData); }
/// <summary> /// Find order by id and print it /// </summary> /// <param name="session"></param> /// <param name="sAccountID"></param> /// <param name="sOrderID"></param> /// <param name="responseListener"></param> private static void FindOrder(O2GSession session, string sAccountID, string sOrderID, ResponseListener responseListener) { O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GRequest request = requestFactory.createRefreshTableRequestByAccount(O2GTableType.Orders, sAccountID); if (request != null) { responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } O2GResponse orderResponse = responseListener.GetResponse(); if (orderResponse != null) { if (orderResponse.Type == O2GResponseType.GetOrders) { O2GResponseReaderFactory responseReaderFactory = session.getResponseReaderFactory(); bool bFound = false; O2GOrdersTableResponseReader responseReader = responseReaderFactory.createOrdersTableReader(orderResponse); for (int i = 0; i < responseReader.Count; i++) { O2GOrderRow orderRow = responseReader.getRow(i); if (sOrderID.Equals(orderRow.OrderID)) { Console.WriteLine("OrderID={0}; AccountID={1}; Type={2}; Status={3}; OfferID={4}; Amount={5}; BuySell={6}; Rate={7}", orderRow.OrderID, orderRow.AccountID, orderRow.Type, orderRow.Status, orderRow.OfferID, orderRow.Amount, orderRow.BuySell, orderRow.Rate); bFound = true; break; } } if (!bFound) { Console.WriteLine("OrderID={0} is not found!", sOrderID); } } } } else { Console.WriteLine("Cannot create request"); } }
/// <summary> /// Find the first opened position by AccountID and OfferID /// </summary> /// <param name="session"></param> /// <param name="sAccountID"></param> /// <param name="sOfferID"></param> /// <param name="responseListener"></param> /// <returns></returns> private static O2GTradeRow GetTrade(O2GSession session, string sAccountID, string sOfferID, ResponseListener responseListener) { O2GTradeRow trade = null; bool bHasTrade = false; O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GRequest request = requestFactory.createRefreshTableRequestByAccount(O2GTableType.Trades, sAccountID); responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } O2GResponse response = responseListener.GetResponse(); if (response != null) { O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory != null) { O2GTradesTableResponseReader tradesResponseReader = readerFactory.createTradesTableReader(response); for (int i = 0; i < tradesResponseReader.Count; i++) { trade = tradesResponseReader.getRow(i); if (sOfferID.Equals(trade.OfferID)) { bHasTrade = true; break; } } } } if (!bHasTrade) { return(null); } else { return(trade); } }
/// <summary> /// Find order by ID and print information about it /// </summary> /// <param name="session"></param> /// <param name="sOrderID"></param> /// <param name="sAccountID"></param> /// <param name="responseListener"></param> private static void FindOrder(O2GSession session, string sOrderID, string sAccountID, ResponseListener responseListener) { O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GRequest request = requestFactory.createRefreshTableRequestByAccount(O2GTableType.Orders, sAccountID); responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } O2GResponse response = responseListener.GetResponse(); if (response != null) { O2GResponseReaderFactory responseFactory = session.getResponseReaderFactory(); O2GOrdersTableResponseReader ordersReader = responseFactory.createOrdersTableReader(response); for (int i = 0; i < ordersReader.Count; i++) { O2GOrderRow order = ordersReader.getRow(i); if (sOrderID.Equals(order.OrderID)) { Console.WriteLine("Information for OrderID = {0}", sOrderID); Console.WriteLine("Account: {0}", order.AccountID); Console.WriteLine("Amount: {0}", order.Amount); Console.WriteLine("Rate: {0}", order.Rate); Console.WriteLine("Type: {0}", order.Type); Console.WriteLine("Buy/Sell: {0}", order.BuySell); Console.WriteLine("Stage: {0}", order.Stage); Console.WriteLine("Status: {0}", order.Status); } } } else { throw new Exception("Cannot get response"); } }
/// <summary> /// Print trades table for account /// </summary> /// <param name="session"></param> /// <param name="sAccountID"></param> /// <param name="responseListener"></param> private static void PrintTrades(O2GSession session, string sAccountID, ResponseListener responseListener) { O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GRequest request = requestFactory.createRefreshTableRequestByAccount(O2GTableType.Trades, sAccountID); if (request != null) { Console.WriteLine("Trades table for account {0}", sAccountID); responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } O2GResponse response = responseListener.GetResponse(); if (response != null) { O2GResponseReaderFactory responseReaderFactory = session.getResponseReaderFactory(); O2GTradesTableResponseReader responseReader = responseReaderFactory.createTradesTableReader(response); for (int i = 0; i < responseReader.Count; i++) { O2GTradeRow tradeRow = responseReader.getRow(i); Console.WriteLine("TradeID: {0}, Amount: {1}, Dividends: {2}", tradeRow.TradeID, tradeRow.Amount, tradeRow.Dividends); } } else { throw new Exception("Cannot get response"); } } else { throw new Exception("Cannot create request"); } }
/// <summary> /// Get trade by order ID /// </summary> private static O2GTradeRow FindPosition(O2GSession session, string sAccountID, string sOrderID, ResponseListener responseListener) { O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GRequest request = requestFactory.createRefreshTableRequestByAccount(O2GTableType.Trades, sAccountID); if (request != null) { responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } O2GResponse tradeResponse = responseListener.GetResponse(); if (tradeResponse != null) { if (tradeResponse.Type == O2GResponseType.GetTrades) { O2GResponseReaderFactory responseReaderFactory = session.getResponseReaderFactory(); O2GTradesTableResponseReader responseReader = responseReaderFactory.createTradesTableReader(tradeResponse); for (int i = 0; i < responseReader.Count; i++) { O2GTradeRow tradeRow = responseReader.getRow(i); if (sOrderID.Equals(tradeRow.OpenOrderID)) { return(tradeRow); } } } } } return(null); }
/// <summary> /// Check if order exists /// </summary> /// <param name="session"></param> /// <param name="sAccountID"></param> /// <param name="sOrderID"></param> /// <param name="responseListener"></param> /// <returns></returns> private static bool IsOrderExists(O2GSession session, string sAccountID, string sOrderID, ResponseListener responseListener) { bool bHasOrder = false; O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GRequest request = requestFactory.createRefreshTableRequestByAccount(O2GTableType.Orders, sAccountID); if (request == null) { throw new Exception("Cannot create request"); } responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } O2GResponse response = responseListener.GetResponse(); O2GResponseReaderFactory responseReaderFactory = session.getResponseReaderFactory(); O2GOrdersTableResponseReader responseReader = responseReaderFactory.createOrdersTableReader(response); for (int i = 0; i < responseReader.Count; i++) { O2GOrderRow orderRow = responseReader.getRow(i); if (sOrderID.Equals(orderRow.OrderID)) { bHasOrder = true; break; } } return(bHasOrder); }
static void Main(string[] args) { O2GSession session = null; SessionStatusListener statusListener = null; ResponseListener responseListener = null; int iContingencyGroupType = 1; // OCO group try { Console.WriteLine("JoinNewGroup sample\n"); ArgumentParser argParser = new ArgumentParser(args, "JoinNewGroup"); argParser.AddArguments(ParserArgument.Login, ParserArgument.Password, ParserArgument.Url, ParserArgument.Connection, ParserArgument.SessionID, ParserArgument.Pin, ParserArgument.PrimaryID, ParserArgument.SecondaryID, ParserArgument.AccountID); argParser.ParseArguments(); if (!argParser.AreArgumentsValid) { argParser.PrintUsage(); return; } argParser.PrintArguments(); LoginParams loginParams = argParser.LoginParams; SampleParams sampleParams = argParser.SampleParams; session = O2GTransport.createSession(); statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin); session.subscribeSessionStatus(statusListener); session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection); if (statusListener.WaitEvents() && statusListener.Connected) { responseListener = new ResponseListener(session); session.subscribeResponse(responseListener); O2GAccountRow account = GetAccount(session, sampleParams.AccountID); if (account == null) { if (string.IsNullOrEmpty(sampleParams.AccountID)) { throw new Exception("No valid accounts"); } else { throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID)); } } sampleParams.AccountID = account.AccountID; O2GRequest request = JoinToNewGroupRequest(session, sampleParams.AccountID, sampleParams.PrimaryID, sampleParams.SecondaryID, iContingencyGroupType); if (request == null) { throw new Exception("Cannot create request"); } List <string> orderIDList = new List <string>(); orderIDList.Add(sampleParams.PrimaryID); orderIDList.Add(sampleParams.SecondaryID); foreach (string sOrderID in orderIDList) { if (!IsOrderExists(session, sampleParams.AccountID, sOrderID, responseListener)) { throw new Exception(string.Format("Order '{0}' does not exist", sOrderID)); } } responseListener.SetOrderIDs(orderIDList); session.sendRequest(request); if (responseListener.WaitEvents()) { Console.WriteLine("Done!"); } else { throw new Exception("Response waiting timeout expired"); } } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { if (statusListener.Connected) { statusListener.Reset(); session.logout(); statusListener.WaitEvents(); if (responseListener != null) { session.unsubscribeResponse(responseListener); } } session.unsubscribeSessionStatus(statusListener); session.Dispose(); } } }
static void Main(string[] args) { O2GSession session = null; SessionStatusListener statusListener = null; ResponseListener responseListener = null; try { Console.WriteLine("CreateOCO sample\n"); ArgumentParser argParser = new ArgumentParser(args, "CreateOCO"); argParser.AddArguments(ParserArgument.Login, ParserArgument.Password, ParserArgument.Url, ParserArgument.Connection, ParserArgument.SessionID, ParserArgument.Pin, ParserArgument.Instrument, ParserArgument.Lots, ParserArgument.AccountID); argParser.ParseArguments(); if (!argParser.AreArgumentsValid) { argParser.PrintUsage(); return; } argParser.PrintArguments(); LoginParams loginParams = argParser.LoginParams; SampleParams sampleParams = argParser.SampleParams; session = O2GTransport.createSession(); statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin); session.subscribeSessionStatus(statusListener); session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection); if (statusListener.WaitEvents() && statusListener.Connected) { responseListener = new ResponseListener(session); session.subscribeResponse(responseListener); O2GAccountRow account = GetAccount(session, sampleParams.AccountID); if (account == null) { if (string.IsNullOrEmpty(sampleParams.AccountID)) { throw new Exception("No valid accounts"); } else { throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID)); } } sampleParams.AccountID = account.AccountID; O2GOfferRow offer = GetOffer(session, sampleParams.Instrument); if (offer == null) { throw new Exception(string.Format("The instrument '{0}' is not valid", sampleParams.Instrument)); } O2GLoginRules loginRules = session.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider(); int iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(sampleParams.Instrument, account); int iAmount = iBaseUnitSize * sampleParams.Lots; // For the purpose of this example we will place entry orders 30 pips from the current market price double dRateUp = offer.Ask + 30.0 * offer.PointSize; double dRateDown = offer.Bid - 30.0 * offer.PointSize; O2GRequest request = CreateOCORequest(session, offer.OfferID, account.AccountID, iAmount, dRateUp, dRateDown); if (request == null) { throw new Exception("Cannot create request"); } List <string> requestIDList = new List <string>(); for (int i = 0; i < request.ChildrenCount; i++) { requestIDList.Add(request.getChildRequest(i).RequestID); } responseListener.SetRequestIDs(requestIDList); session.sendRequest(request); if (responseListener.WaitEvents()) { Console.WriteLine("Done!"); } else { throw new Exception("Response waiting timeout expired"); } } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { if (statusListener.Connected) { statusListener.Reset(); session.logout(); statusListener.WaitEvents(); if (responseListener != null) { session.unsubscribeResponse(responseListener); } session.unsubscribeSessionStatus(statusListener); } session.Dispose(); } } }
/// <summary> /// Get orders data for closing all positions /// </summary> /// <param name="session"></param> /// <param name="sAccountID"></param> /// <param name="sOfferID"></param> /// <param name="responseListener"></param> /// <returns></returns> private static bool GetCloseOrdersData(O2GSession session, string sAccountID, string sOfferID, ResponseListener responseListener, out CloseOrdersData closeOrdersData) { O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GRequest request = requestFactory.createRefreshTableRequestByAccount(O2GTableType.Trades, sAccountID); responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } O2GResponse response = responseListener.GetResponse(); bool bIsTradesFound = false; closeOrdersData = new CloseOrdersData(); if (response != null) { O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory != null) { O2GTradesTableResponseReader tradesResponseReader = readerFactory.createTradesTableReader(response); for (int i = 0; i < tradesResponseReader.Count; i++) { O2GTradeRow trade = tradesResponseReader.getRow(i); if (!trade.OfferID.Equals(sOfferID)) { continue; } bIsTradesFound = true; string sBuySell = trade.BuySell; // Set opposite side OrderSide side = (sBuySell.Equals(Constants.Buy) ? OrderSide.Sell : OrderSide.Buy); if (closeOrdersData.OfferID.Equals(sOfferID)) { OrderSide currentSide = closeOrdersData.Side; if (currentSide != OrderSide.Both && currentSide != side) { closeOrdersData.Side = OrderSide.Both; } } else { closeOrdersData.OfferID = sOfferID; closeOrdersData.AccountID = sAccountID; closeOrdersData.Side = side; } } } } return bIsTradesFound; }
static void Main(string[] args) { O2GSession session = null; int iLots = 10; try { LoginParams loginParams = new LoginParams(ConfigurationManager.AppSettings); SampleParams sampleParams = new SampleParams(ConfigurationManager.AppSettings); PrintSampleParams("PatrialFill", loginParams, sampleParams); session = O2GTransport.createSession(); session.useTableManager(O2GTableManagerMode.Yes, null); statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin); session.subscribeSessionStatus(statusListener); statusListener.Reset(); session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection); if (statusListener.WaitEvents() && statusListener.Connected) { responseListener = new ResponseListener(); TableListener tableListener = new TableListener(responseListener); session.subscribeResponse(responseListener); O2GTableManager tableManager = session.getTableManager(); O2GTableManagerStatus managerStatus = tableManager.getStatus(); while (managerStatus == O2GTableManagerStatus.TablesLoading) { Thread.Sleep(50); managerStatus = tableManager.getStatus(); } if (managerStatus == O2GTableManagerStatus.TablesLoadFailed) { throw new Exception("Cannot refresh all tables of table manager"); } O2GAccountRow account = GetAccount(tableManager, sampleParams.AccountID); if (account == null) { if (string.IsNullOrEmpty(sampleParams.AccountID)) { throw new Exception("No valid accounts"); } else { throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID)); } } else { if (!account.AccountID.Equals(sampleParams.AccountID)) { sampleParams.AccountID = account.AccountID; Console.WriteLine("AccountID='{0}'", sampleParams.AccountID); } } O2GOfferRow offer = GetOffer(tableManager, sampleParams.Instrument); if (offer == null) { throw new Exception(string.Format("The instrument '{0}' is not valid", sampleParams.Instrument)); } O2GLoginRules loginRules = session.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider(); int iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(sampleParams.Instrument, account); int iAmount = iBaseUnitSize * iLots; tableListener.SubscribeEvents(tableManager); O2GRequest request = CreateTrueMarketOrderRequest(session, offer.OfferID, sampleParams.AccountID, iAmount, sampleParams.BuySell); if (request == null) { throw new Exception("Cannot create request"); } responseListener.SetRequestID(request.RequestID); tableListener.SetRequestID(request.RequestID); session.sendRequest(request); if (responseListener.WaitEvents()) { Thread.Sleep(1000); // Wait for the balance update Console.WriteLine("Done!"); } else { throw new Exception("Response waiting timeout expired"); } tableListener.UnsubscribeEvents(tableManager); } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { if (statusListener.Connected) { if (responseListener != null) { session.unsubscribeResponse(responseListener); } statusListener.Reset(); session.logout(); statusListener.WaitEvents(); } session.unsubscribeSessionStatus(statusListener); session.Dispose(); } } }
static void Main(string[] args) { O2GSession session = null; SessionStatusListener statusListener = null; ResponseListener responseListener = null; string sInstrument = "EUR/USD"; string sBuySell = Constants.Buy; try { Console.WriteLine("CreateOTO sample\n"); ArgumentParser argParser = new ArgumentParser(args, "CloseAllPositions"); argParser.AddArguments(ParserArgument.Login, ParserArgument.Password, ParserArgument.Url, ParserArgument.Connection, ParserArgument.SessionID, ParserArgument.Pin, ParserArgument.AccountID); argParser.ParseArguments(); if (!argParser.AreArgumentsValid) { argParser.PrintUsage(); return; } argParser.PrintArguments(); LoginParams loginParams = argParser.LoginParams; SampleParams sampleParams = argParser.SampleParams; session = O2GTransport.createSession(); statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin); session.subscribeSessionStatus(statusListener); statusListener.Reset(); session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection); if (statusListener.WaitEvents() && statusListener.Connected) { responseListener = new ResponseListener(session); session.subscribeResponse(responseListener); O2GAccountRow account = GetAccount(session, sampleParams.AccountID); if (account == null) { if (string.IsNullOrEmpty(sampleParams.AccountID)) { throw new Exception("No valid accounts"); } else { throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID)); } } sampleParams.AccountID = account.AccountID; O2GOfferRow offer = GetOffer(session, sInstrument); if (offer == null) { throw new Exception(string.Format("The instrument '{0}' is not valid", sInstrument)); } O2GLoginRules loginRules = session.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider(); int iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(sInstrument, account); int iAmount = iBaseUnitSize * 1; double dRate = offer.Ask - (offer.PointSize * 10); O2GRequest request; request = CreateEntryOrderRequest(session, offer.OfferID, account.AccountID, iAmount, dRate, sBuySell, Constants.Orders.LimitEntry); if (request == null) { throw new Exception("Cannot create request"); } responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } string sOrderID = responseListener.GetOrderID(); if (!string.IsNullOrEmpty(sOrderID)) { request = RemoveOrderRequest(session, account.AccountID, sOrderID); if (request == null) { throw new Exception("Cannot create request"); } responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (responseListener.WaitEvents()) { Console.WriteLine("Done!"); } else { throw new Exception("Response waiting timeout expired"); } } } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { if (statusListener.Connected) { statusListener.Reset(); session.logout(); statusListener.WaitEvents(); if (responseListener != null) { session.unsubscribeResponse(responseListener); } } session.unsubscribeSessionStatus(statusListener); session.Dispose(); } } }
static void Main(string[] args) { O2GSession session = null; try { LoginParams loginParams = new LoginParams(ConfigurationManager.AppSettings); SampleParams sampleParams = new SampleParams(ConfigurationManager.AppSettings); PrintSampleParams("CreateOTO", loginParams, sampleParams); session = O2GTransport.createSession(); session.useTableManager(O2GTableManagerMode.Yes, null); statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin); session.subscribeSessionStatus(statusListener); statusListener.Reset(); session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection); if (statusListener.WaitEvents() && statusListener.Connected) { responseListener = new ResponseListener(); TableListener tableListener = new TableListener(responseListener); session.subscribeResponse(responseListener); O2GTableManager tableManager = session.getTableManager(); O2GTableManagerStatus managerStatus = tableManager.getStatus(); while (managerStatus == O2GTableManagerStatus.TablesLoading) { Thread.Sleep(50); managerStatus = tableManager.getStatus(); } if (managerStatus == O2GTableManagerStatus.TablesLoadFailed) { throw new Exception("Cannot refresh all tables of table manager"); } O2GAccountRow account = GetAccount(tableManager, sampleParams.AccountID); if (account == null) { if (string.IsNullOrEmpty(sampleParams.AccountID)) { throw new Exception("No valid accounts"); } else { throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID)); } } sampleParams.AccountID = account.AccountID; O2GOfferRow offer = GetOffer(tableManager, sampleParams.Instrument); if (offer == null) { throw new Exception(string.Format("The instrument '{0}' is not valid", sampleParams.Instrument)); } O2GLoginRules loginRules = session.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider(); int iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(sampleParams.Instrument, account); int iAmount = iBaseUnitSize * sampleParams.Lots; // For the purpose of this example we will place primary order 30 pips below the current market price // and our secondary order 15 pips below the current market price double dRatePrimary = offer.Ask - 30.0 * offer.PointSize; double dRateSecondary = offer.Ask - 15.0 * offer.PointSize; O2GRequest request = CreateOTORequest(session, offer.OfferID, account.AccountID, iAmount, dRatePrimary, dRateSecondary); if (request == null) { throw new Exception("Cannot create request"); } tableListener.SubscribeEvents(tableManager); List <string> requestIDList = new List <string>(); for (int i = 0; i < request.ChildrenCount; i++) { requestIDList.Add(request.getChildRequest(i).RequestID); } responseListener.SetRequestIDs(requestIDList); tableListener.SetRequestIDs(requestIDList); session.sendRequest(request); if (responseListener.WaitEvents()) { Console.WriteLine("Done!"); } else { throw new Exception("Response waiting timeout expired"); } tableListener.UnsubscribeEvents(tableManager); } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { if (statusListener.Connected) { if (responseListener != null) { session.unsubscribeResponse(responseListener); } statusListener.Reset(); session.logout(); statusListener.WaitEvents(); } session.unsubscribeSessionStatus(statusListener); session.Dispose(); } } }
static void Main(string[] args) { O2GSession session = null; try { LoginParams loginParams = new LoginParams(ConfigurationManager.AppSettings); SampleParams sampleParams = new SampleParams(ConfigurationManager.AppSettings); PrintSampleParams("CreateOrderBySymbol", loginParams, sampleParams); session = O2GTransport.createSession(); statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin); session.subscribeSessionStatus(statusListener); statusListener.Reset(); session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection); if (statusListener.WaitEvents() && statusListener.Connected) { responseListener = new ResponseListener(session); session.subscribeResponse(responseListener); O2GAccountRow account = GetAccount(session, sampleParams.AccountID); if (account == null) { if (string.IsNullOrEmpty(sampleParams.AccountID)) { throw new Exception("No valid accounts"); } else { throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID)); } } sampleParams.AccountID = account.AccountID; O2GOfferRow offer = GetOffer(session, sampleParams.Instrument); if (offer == null) { throw new Exception(string.Format("The instrument '{0}' is not valid", sampleParams.Instrument)); } O2GLoginRules loginRules = session.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider(); int iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(sampleParams.Instrument, account); int iAmount = iBaseUnitSize * sampleParams.Lots; int iCondDistEntryLimit = tradingSettingsProvider.getCondDistEntryLimit(sampleParams.Instrument); int iCondDistEntryStop = tradingSettingsProvider.getCondDistEntryStop(sampleParams.Instrument); string sOrderType = GetEntryOrderType(offer.Bid, offer.Ask, sampleParams.Rate, sampleParams.BuySell, offer.PointSize, iCondDistEntryLimit, iCondDistEntryStop); O2GRequest request = CreateEntryOrderRequest(session, offer.Instrument, sampleParams.AccountID, iAmount, sampleParams.Rate, sampleParams.BuySell, sOrderType); if (request == null) { throw new Exception("Cannot create request"); } responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (responseListener.WaitEvents()) { Console.WriteLine("Done!"); } else { throw new Exception("Response waiting timeout expired"); } } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { if (statusListener.Connected) { if (responseListener != null) { session.unsubscribeResponse(responseListener); } statusListener.Reset(); session.logout(); statusListener.WaitEvents(); } session.unsubscribeSessionStatus(statusListener); session.Dispose(); } } }
static void Main(string[] args) { O2GSession session = null; try { LoginParams loginParams = new LoginParams(ConfigurationManager.AppSettings); SampleParams sampleParams = new SampleParams(ConfigurationManager.AppSettings); PrintSampleParams("CloseAllPositions", loginParams, sampleParams); session = O2GTransport.createSession(); session.useTableManager(O2GTableManagerMode.Yes, null); SessionStatusListener statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin); session.subscribeSessionStatus(statusListener); statusListener.Reset(); session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection); if (statusListener.WaitEvents() && statusListener.Connected) { ResponseListener responseListener = new ResponseListener(session); TableListener tableListener = new TableListener(responseListener); session.subscribeResponse(responseListener); O2GTableManager tableManager = session.getTableManager(); O2GTableManagerStatus managerStatus = tableManager.getStatus(); while (managerStatus == O2GTableManagerStatus.TablesLoading) { Thread.Sleep(50); managerStatus = tableManager.getStatus(); } if (managerStatus == O2GTableManagerStatus.TablesLoadFailed) { throw new Exception("Cannot refresh all tables of table manager"); } O2GAccountRow account = GetAccount(tableManager, sampleParams.AccountID); if (account == null) { if (string.IsNullOrEmpty(sampleParams.AccountID)) { throw new Exception("No valid accounts"); } else { throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID)); } } sampleParams.AccountID = account.AccountID; Dictionary <string, CloseOrdersData> closeOrdersData = GetCloseOrdersData(tableManager, sampleParams.AccountID); if (closeOrdersData.Values.Count == 0) { throw new Exception("There are no opened positions"); } tableListener.SubscribeEvents(tableManager); O2GRequest request = CreateCloseAllRequest(session, closeOrdersData); if (request == null) { throw new Exception("Cannot create request"); } List <string> requestIDs = new List <string>(); for (int i = 0; i < request.ChildrenCount; i++) { requestIDs.Add(request.getChildRequest(i).RequestID); } responseListener.SetRequestIDs(requestIDs); tableListener.SetRequestIDs(requestIDs); session.sendRequest(request); if (responseListener.WaitEvents()) { Console.WriteLine("Done!"); } else { throw new Exception("Response waiting timeout expired"); } tableListener.UnsubscribeEvents(tableManager); statusListener.Reset(); session.logout(); statusListener.WaitEvents(); session.unsubscribeResponse(responseListener); } session.unsubscribeSessionStatus(statusListener); } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { session.Dispose(); } } }
/// <summary> /// Get initial Trades state /// </summary> /// <param name="session"></param> /// <param name="sAccountID"></param> /// <param name="responseListener"></param> /// <returns>TradesTable</returns> private static O2GTradesTableResponseReader GetTradesTable(O2GSession session, string sAccountID, ResponseListener responseListener) { O2GTradesTableResponseReader tradesTable = null; O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GRequest refreshTrades = requestFactory.createRefreshTableRequestByAccount(O2GTableType.Trades, sAccountID); responseListener.SetRequestID(refreshTrades.RequestID); session.sendRequest(refreshTrades); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } O2GResponse tradeResponse = responseListener.GetResponse(); if (tradeResponse != null) { O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory != null) { tradesTable = readerFactory.createTradesTableReader(tradeResponse); } } return tradesTable; }
/// <summary> /// Print orders table for account /// </summary> /// <param name="session"></param> /// <param name="sAccountID"></param> /// <param name="responseListener"></param> private static void PrintOrders(O2GSession session, string sAccountID, ResponseListener responseListener) { O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GRequest request = requestFactory.createRefreshTableRequestByAccount(O2GTableType.Orders, sAccountID); if (request != null) { Console.WriteLine("Orders table for account {0}", sAccountID); responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } O2GResponse response = responseListener.GetResponse(); if (response != null) { O2GResponseReaderFactory responseReaderFactory = session.getResponseReaderFactory(); O2GOrdersTableResponseReader responseReader = responseReaderFactory.createOrdersTableReader(response); for (int i = 0; i < responseReader.Count; i++) { O2GOrderRow orderRow = responseReader.getRow(i); Console.WriteLine("OrderID: {0}, Status: {1}, Amount: {2}", orderRow.OrderID, orderRow.Status, orderRow.Amount); } } else { throw new Exception("Cannot get response"); } } else { throw new Exception("Cannot create request"); } }
static void Main(string[] args) { O2GSession session = null; string sInstrument = "EUR/USD"; string sBuySell = Constants.Buy; try { LoginParams loginParams = new LoginParams(ConfigurationManager.AppSettings); SampleParams sampleParams = new SampleParams(ConfigurationManager.AppSettings); PrintSampleParams("RemoveOrder", loginParams, sampleParams); session = O2GTransport.createSession(); session.useTableManager(O2GTableManagerMode.Yes, null); SessionStatusListener statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin); session.subscribeSessionStatus(statusListener); statusListener.Reset(); session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection); if (statusListener.WaitEvents() && statusListener.Connected) { ResponseListener responseListener = new ResponseListener(); TableListener tableListener = new TableListener(responseListener); session.subscribeResponse(responseListener); O2GTableManager tableManager = session.getTableManager(); O2GTableManagerStatus managerStatus = tableManager.getStatus(); while (managerStatus == O2GTableManagerStatus.TablesLoading) { Thread.Sleep(50); managerStatus = tableManager.getStatus(); } if (managerStatus == O2GTableManagerStatus.TablesLoadFailed) { throw new Exception("Cannot refresh all tables of table manager"); } O2GAccountRow account = GetAccount(tableManager, sampleParams.AccountID); if (account == null) { if (string.IsNullOrEmpty(sampleParams.AccountID)) { throw new Exception("No valid accounts"); } else { throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID)); } } sampleParams.AccountID = account.AccountID; O2GOfferRow offer = GetOffer(tableManager, sInstrument); if (offer == null) { throw new Exception(string.Format("The instrument '{0}' is not valid", sInstrument)); } O2GLoginRules loginRules = session.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider(); int iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(sInstrument, account); int iAmount = iBaseUnitSize * 1; double dRate = offer.Ask - (offer.PointSize * 10); tableListener.SubscribeEvents(tableManager); O2GRequest request = CreateEntryOrderRequest(session, offer.OfferID, account.AccountID, iAmount, dRate, sBuySell, Constants.Orders.LimitEntry); if (request == null) { throw new Exception("Cannot create request"); } responseListener.SetRequestID(request.RequestID); tableListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } string sOrderID = tableListener.GetOrderID(); if (!string.IsNullOrEmpty(sOrderID)) { request = RemoveOrderRequest(session, account.AccountID, sOrderID); if (request == null) { throw new Exception("Cannot create request"); } responseListener.SetRequestID(request.RequestID); tableListener.SetRequestID(request.RequestID); session.sendRequest(request); if (responseListener.WaitEvents()) { Console.WriteLine("Done!"); } else { throw new Exception("Response waiting timeout expired"); } } tableListener.UnsubscribeEvents(tableManager); statusListener.Reset(); session.logout(); statusListener.WaitEvents(); session.unsubscribeResponse(responseListener); } session.unsubscribeSessionStatus(statusListener); } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { session.Dispose(); } } }
static void Main(string[] args) { O2GSession session = null; try { LoginParams loginParams = new LoginParams(ConfigurationManager.AppSettings); SampleParams sampleParams = new SampleParams(ConfigurationManager.AppSettings); PrintSampleParams("CreateELS", loginParams, sampleParams); session = O2GTransport.createSession(); statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin); session.subscribeSessionStatus(statusListener); statusListener.Reset(); session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection); if (statusListener.WaitEvent() && statusListener.Connected) { responseListener = new ResponseListener(session); session.subscribeResponse(responseListener); O2GAccountRow account = GetAccount(session, sampleParams.AccountID); if (account == null) { if (string.IsNullOrEmpty(sampleParams.AccountID)) { throw new Exception("No valid accounts"); } else { throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID)); } } sampleParams.AccountID = account.AccountID; O2GOfferRow offer = GetOffer(session, sampleParams.Instrument); if (offer == null) { throw new Exception(string.Format("The instrument '{0}' is not valid", sampleParams.Instrument)); } O2GLoginRules loginRules = session.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider(); int iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(sampleParams.Instrument, account); int iAmount = iBaseUnitSize * sampleParams.Lots; double dRate; double dRateStop; double dRateLimit; double dBid = offer.Bid; double dAsk = offer.Ask; double dPointSize = offer.PointSize; // For the purpose of this example we will place entry order 8 pips from the current market price // and attach stop and limit orders 10 pips from an entry order price if (sampleParams.OrderType.Equals(Constants.Orders.LimitEntry)) { if (sampleParams.BuySell.Equals(Constants.Buy)) { dRate = dAsk - 8 * dPointSize; dRateLimit = dRate + 10 * dPointSize; dRateStop = dRate - 10 * dPointSize; } else { dRate = dBid + 8 * dPointSize; dRateLimit = dRate - 10 * dPointSize; dRateStop = dRate + 10 * dPointSize; } } else { if (sampleParams.BuySell.Equals(Constants.Buy)) { dRate = dAsk + 8 * dPointSize; dRateLimit = dRate + 10 * dPointSize; dRateStop = dRate - 10 * dPointSize; } else { dRate = dBid - 8 * dPointSize; dRateLimit = dRate - 10 * dPointSize; dRateStop = dRate + 10 * dPointSize; } } O2GRequest request = CreateELSRequest(session, offer.OfferID, sampleParams.AccountID, iAmount, dRate, dRateLimit, dRateStop, sampleParams.BuySell, sampleParams.OrderType); if (request == null) { throw new Exception("Cannot create request; probably some arguments are missing or incorrect"); } responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (responseListener.WaitEvents()) { Console.WriteLine("Done!"); } else { throw new Exception("Response waiting timeout expired"); } } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { if (statusListener.Connected) { if (responseListener != null) session.unsubscribeResponse(responseListener); statusListener.Reset(); session.logout(); statusListener.WaitEvent(); } session.unsubscribeSessionStatus(statusListener); session.Dispose(); } } }
/// <summary> /// Find the first opened position by AccountID and OfferID /// </summary> /// <param name="session"></param> /// <param name="sAccountID"></param> /// <param name="sOfferID"></param> /// <param name="responseListener"></param> /// <returns></returns> private static O2GTradeRow GetTrade(O2GSession session, string sAccountID, string sOfferID, ResponseListener responseListener) { O2GTradeRow trade = null; bool bHasTrade = false; O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GRequest request = requestFactory.createRefreshTableRequestByAccount(O2GTableType.Trades, sAccountID); responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } O2GResponse response = responseListener.GetResponse(); if (response != null) { O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory != null) { O2GTradesTableResponseReader tradesResponseReader = readerFactory.createTradesTableReader(response); for (int i = 0; i < tradesResponseReader.Count; i++) { trade = tradesResponseReader.getRow(i); if (sOfferID.Equals(trade.OfferID)) { bHasTrade = true; break; } } } } if(!bHasTrade) { return null; } else { return trade; } }
private static void GetHistoryPrices(O2GSession session, string sInstrument, string sTimeframe, DateTime dtFrom, DateTime dtTo, ResponseListener responseListener) { try { StreamWriter m_data = new StreamWriter(OutData); string m_string_to_write = ""; O2GRequestFactory factory = session.getRequestFactory(); O2GTimeframe timeframe = factory.Timeframes[sTimeframe]; if (timeframe == null) { throw new Exception(string.Format("Timeframe '{0}' is incorrect!", sTimeframe)); } O2GRequest request = factory.createMarketDataSnapshotRequestInstrument(sInstrument, timeframe, 300); DateTime dtFirst = dtTo; do // cause there is limit for returned candles amount { factory.fillMarketDataSnapshotRequestTime(request, dtFrom, dtFirst, false); responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } // shift "to" bound to oldest datetime of returned data O2GResponse response = responseListener.GetResponse(); if (response != null && response.Type == O2GResponseType.MarketDataSnapshot) { O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory != null) { O2GMarketDataSnapshotResponseReader reader = readerFactory.createMarketDataSnapshotReader(response); if (reader.Count > 0) { if (DateTime.Compare(dtFirst, reader.getDate(0)) != 0) { dtFirst = reader.getDate(0); // earliest datetime of returned data for (int nData = reader.Count - 1; nData > -1; nData--) { // reader.getDate(0); m_string_to_write = reader.getDate(nData).ToString() + ";" + reader.getAsk(nData).ToString() + ";" + reader.getAskOpen(nData).ToString() + ";" + reader.getAskClose(nData).ToString() + ";" + reader.getAskLow(nData).ToString() + ";" + reader.getAskHigh(nData).ToString() + ";" + reader.getBid(nData).ToString() + ";" + reader.getBidOpen(nData).ToString() + ";" + reader.getBidClose(nData).ToString() + ";" + reader.getBidLow(nData).ToString() + ";" + reader.getBidHigh(nData).ToString() + ";" + reader.getVolume(nData).ToString() + ";" + reader.getLastBarTime().ToString() + ";" + reader.getLastBarVolume().ToString(); m_data.WriteLine(m_string_to_write); } } else { break; } } else { Console.WriteLine("0 rows received"); break; } } // PrintPrices(session, response); } else { break; } } while (dtFirst > dtFrom); m_data.Close(); } catch (Exception e) { int ErrorCounter = 0; if (ErrorCounter > 5) { LogDirector.DoAction(4, e); } else { ErrorCounter++; LogDirector.DoAction(2, e); GetHistoryPrices(session, sInstrument, sTimeframe, dtFrom, dtTo, responseListener); } } }
/// <summary> /// Get orders data for closing all positions /// </summary> /// <param name="session"></param> /// <param name="sAccountID"></param> /// <param name="responseListener"></param> /// <returns></returns> private static Dictionary<string, CloseOrdersData> GetCloseOrdersData(O2GSession session, string sAccountID, ResponseListener responseListener) { Dictionary<string, CloseOrdersData> closeOrdersData = new Dictionary<string, CloseOrdersData>(); O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GRequest request = requestFactory.createRefreshTableRequestByAccount(O2GTableType.Trades, sAccountID); responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } O2GResponse response = responseListener.GetResponse(); if (response != null) { O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory != null) { O2GTradesTableResponseReader tradesResponseReader = readerFactory.createTradesTableReader(response); for (int i = 0; i < tradesResponseReader.Count; i++) { O2GTradeRow trade = tradesResponseReader.getRow(i); string sOfferID = trade.OfferID; string sBuySell = trade.BuySell; // Set opposite side OrderSide side = (sBuySell.Equals(Constants.Buy) ? OrderSide.Sell : OrderSide.Buy); if (closeOrdersData.ContainsKey(sOfferID)) { OrderSide currentSide = closeOrdersData[sOfferID].Side; if (currentSide != OrderSide.Both && currentSide != side) { closeOrdersData[sOfferID].Side = OrderSide.Both; } } else { CloseOrdersData data = new CloseOrdersData(sAccountID, side); closeOrdersData.Add(sOfferID, data); } } } } return closeOrdersData; }
static void Main(string[] args) { O2GSession session = null; SessionStatusListener statusListener = null; ResponseListener responseListener = null; try { Console.WriteLine("OpenPositionNetting sample\n"); ArgumentParser argParser = new ArgumentParser(args, "OpenPositionNetting"); argParser.AddArguments(ParserArgument.Login, ParserArgument.Password, ParserArgument.Url, ParserArgument.Connection, ParserArgument.SessionID, ParserArgument.Pin, ParserArgument.Instrument, ParserArgument.BuySell, ParserArgument.Lots, ParserArgument.AccountID); argParser.ParseArguments(); if (!argParser.AreArgumentsValid) { argParser.PrintUsage(); return; } argParser.PrintArguments(); LoginParams loginParams = argParser.LoginParams; SampleParams sampleParams = argParser.SampleParams; session = O2GTransport.createSession(); session.useTableManager(O2GTableManagerMode.Yes, null); statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin); session.subscribeSessionStatus(statusListener); statusListener.Reset(); session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection); if (statusListener.WaitEvents() && statusListener.Connected) { responseListener = new ResponseListener(); TableListener tableListener = new TableListener(responseListener); session.subscribeResponse(responseListener); O2GTableManager tableManager = session.getTableManager(); O2GTableManagerStatus managerStatus = tableManager.getStatus(); while (managerStatus == O2GTableManagerStatus.TablesLoading) { Thread.Sleep(50); managerStatus = tableManager.getStatus(); } if (managerStatus == O2GTableManagerStatus.TablesLoadFailed) { throw new Exception("Cannot refresh all tables of table manager"); } O2GAccountRow account = GetAccount(tableManager, sampleParams.AccountID); if (account == null) { if (string.IsNullOrEmpty(sampleParams.AccountID)) { throw new Exception("No valid accounts"); } else { throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID)); } } sampleParams.AccountID = account.AccountID; O2GOfferRow offer = GetOffer(tableManager, sampleParams.Instrument); if (offer == null) { throw new Exception(string.Format("The instrument '{0}' is not valid", sampleParams.Instrument)); } O2GTradesTable tradesTable = GetTradesTable(tableManager); if (tradesTable == null) { throw new Exception("Cannot get trades table"); } tableListener.SetTradesTable(tradesTable); O2GLoginRules loginRules = session.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider(); int iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(sampleParams.Instrument, account); int iAmount = iBaseUnitSize * sampleParams.Lots; tableListener.SubscribeEvents(tableManager); O2GRequest request = CreateTrueMarketOrderRequest(session, offer.OfferID, sampleParams.AccountID, iAmount, sampleParams.BuySell); if (request == null) { throw new Exception("Cannot create request"); } responseListener.SetRequestID(request.RequestID); tableListener.SetRequestID(request.RequestID); session.sendRequest(request); if (responseListener.WaitEvents()) { System.Threading.Thread.Sleep(1000); // Wait for the balance update Console.WriteLine("Done!"); } else { throw new Exception("Response waiting timeout expired"); } tableListener.UnsubscribeEvents(tableManager); } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { if (statusListener.Connected) { statusListener.Reset(); session.logout(); statusListener.WaitEvents(); if (responseListener != null) { session.unsubscribeResponse(responseListener); } session.unsubscribeSessionStatus(statusListener); } session.Dispose(); } } }
static void Main(string[] args) { O2GSession session = null; try { LoginParams loginParams = new LoginParams(ConfigurationManager.AppSettings); SampleParams sampleParams = new SampleParams(ConfigurationManager.AppSettings); PrintSampleParams("GetLastOrderUpdate", loginParams, sampleParams); session = O2GTransport.createSession(); statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin); session.subscribeSessionStatus(statusListener); statusListener.Reset(); session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection); if (statusListener.WaitEvent() && statusListener.Connected) { responseListener = new ResponseListener(session); session.subscribeResponse(responseListener); O2GAccountRow account = GetAccount(session, sampleParams.AccountID); if (account == null) { if (string.IsNullOrEmpty(sampleParams.AccountID)) { throw new Exception("No valid accounts"); } else { throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID)); } } sampleParams.AccountID = account.AccountID; O2GOfferRow offer = GetOffer(session, sampleParams.Instrument); if (offer == null) { throw new Exception(string.Format("The instrument '{0}' is not valid", sampleParams.Instrument)); } O2GLoginRules loginRules = session.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider(); int iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(sampleParams.Instrument, account); int iAmount = iBaseUnitSize * sampleParams.Lots; O2GRequest request; request = CreateTrueMarketOrderRequest(session, offer.OfferID, account.AccountID, iAmount, sampleParams.BuySell); if (request == null) { throw new Exception("Cannot create request; probably some arguments are missing or incorrect"); } responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } string sOrderID = responseListener.GetOrderID(); if (!string.IsNullOrEmpty(sOrderID)) { Console.WriteLine("You have successfully created a true market order."); Console.WriteLine("Your order ID is {0}", sOrderID); request = GetLastOrderUpdateRequest(session, sOrderID, account.AccountName); if (request == null) { throw new Exception("Cannot create request; probably some arguments are missing or incorrect"); } responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } O2GResponse response = responseListener.GetResponse(); if (response != null && response.Type == O2GResponseType.GetLastOrderUpdate) { O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory != null) { O2GLastOrderUpdateResponseReader reader = readerFactory.createLastOrderUpdateResponseReader(response); Console.WriteLine("Last order update: UpdateType={0}, OrderID={1}, Status={2}, StatusTime={3}", reader.UpdateType.ToString(), reader.Order.OrderID, reader.Order.Status.ToString(), reader.Order.StatusTime.ToString("yyyy-MM-dd HH:mm:ss")); } } Console.WriteLine("Done!"); } } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { if (statusListener.Connected) { if (responseListener != null) { session.unsubscribeResponse(responseListener); } statusListener.Reset(); session.logout(); statusListener.WaitEvent(); } session.unsubscribeSessionStatus(statusListener); session.Dispose(); } } }
public void Run() { try { string sLogin; string sPassword; string sSessionID; string sPin; if (mIsFirstAccount) { sLogin = mLoginParams.Login; sPassword = mLoginParams.Password; sSessionID = mLoginParams.SessionID; sPin = mLoginParams.Pin; } else { sLogin = mLoginParams.Login2; sPassword = mLoginParams.Password2; sSessionID = mLoginParams.SessionID2; sPin = mLoginParams.Pin2; } statusListener = new SessionStatusListener(mSession, sSessionID, sPin); mSession.subscribeSessionStatus(statusListener); statusListener.Reset(); mSession.login(sLogin, sPassword, mLoginParams.URL, mLoginParams.Connection); if (statusListener.WaitEvents() && statusListener.Connected) { if (!mIsFirstAccount) // Disable receiving price updates for the second account { mSession.setPriceUpdateMode(O2GPriceUpdateMode.NoPrice); } responseListener = new ResponseListener(mSession); mSession.subscribeResponse(responseListener); O2GAccountRow account = null; if (mIsFirstAccount) { bool bIsAccountEmpty = String.IsNullOrEmpty(mSampleParams.AccountID); account = GetAccount(mSession, mSampleParams.AccountID); if (account != null) { if (bIsAccountEmpty) { mSampleParams.AccountID = account.AccountID; Console.WriteLine("Account: " + mSampleParams.AccountID); } } else { throw new Exception(string.Format("The account '{0}' is not valid", mSampleParams.AccountID)); } } else { bool bIsAccountEmpty = String.IsNullOrEmpty(mSampleParams.AccountID2); account = GetAccount(mSession, mSampleParams.AccountID2); if (account != null) { if (bIsAccountEmpty) { mSampleParams.AccountID2 = account.AccountID; Console.WriteLine("Account2: " + mSampleParams.AccountID2); } } else { throw new Exception(string.Format("The account2 '{0}' is not valid", mSampleParams.AccountID2)); } } O2GOfferRow offer = GetOffer(mSession, mSampleParams.Instrument); if (offer == null) { throw new Exception(string.Format("The instrument '{0}' is not valid", mSampleParams.Instrument)); } O2GLoginRules loginRules = mSession.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider(); int iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(mSampleParams.Instrument, account); int iAmount = iBaseUnitSize * mSampleParams.Lots; O2GRequest request; request = CreateTrueMarketOrderRequest(mSession, offer.OfferID, account.AccountID, iAmount, mSampleParams.BuySell); if (request == null) { throw new Exception("Cannot create request"); } responseListener.SetRequestID(request.RequestID); mSession.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } Console.WriteLine("Done!"); } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (statusListener.Connected) { statusListener.Reset(); mSession.logout(); statusListener.WaitEvents(); mSession.unsubscribeResponse(responseListener); } mSession.subscribeSessionStatus(statusListener); mSession.Dispose(); } }
static void Main(string[] args) { O2GSession session = null; try { LoginParams loginParams = new LoginParams(ConfigurationManager.AppSettings); SampleParams sampleParams = new SampleParams(ConfigurationManager.AppSettings); PrintSampleParams("ClosePosition", loginParams, sampleParams); session = O2GTransport.createSession(); session.useTableManager(O2GTableManagerMode.Yes, null); statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin); session.subscribeSessionStatus(statusListener); statusListener.Reset(); session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection); if (statusListener.WaitEvents() && statusListener.Connected) { responseListener = new ResponseListener(); TableListener tableListener = new TableListener(responseListener); session.subscribeResponse(responseListener); O2GTableManager tableManager = session.getTableManager(); O2GTableManagerStatus managerStatus = tableManager.getStatus(); while (managerStatus == O2GTableManagerStatus.TablesLoading) { Thread.Sleep(50); managerStatus = tableManager.getStatus(); } if (managerStatus == O2GTableManagerStatus.TablesLoadFailed) { throw new Exception("Cannot refresh all tables of table manager"); } O2GAccountRow account = GetAccount(tableManager, sampleParams.AccountID); if (account == null) { if (string.IsNullOrEmpty(sampleParams.AccountID)) { throw new Exception("No valid accounts"); } else { throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID)); } } sampleParams.AccountID = account.AccountID; O2GOfferRow offer = GetOffer(tableManager, sampleParams.Instrument); if (offer == null) { throw new Exception(string.Format("The instrument '{0}' is not valid", sampleParams.Instrument)); } O2GTradeRow trade = GetTrade(tableManager, sampleParams.AccountID, offer.OfferID); if (trade == null) { throw new Exception(string.Format("There are no opened positions for instrument '{0}'", sampleParams.Instrument)); } tableListener.SubscribeEvents(tableManager); O2GRequest request = CreateCloseMarketOrderRequest(session, sampleParams.Instrument, trade); if (request == null) { throw new Exception("Cannot create request"); } responseListener.SetRequestID(request.RequestID); tableListener.SetRequestID(request.RequestID); session.sendRequest(request); if (responseListener.WaitEvents()) { Console.WriteLine("Done!"); } else { throw new Exception("Response waiting timeout expired"); } tableListener.UnsubscribeEvents(tableManager); } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { if (statusListener.Connected) { if (responseListener != null) { session.unsubscribeResponse(responseListener); } statusListener.Reset(); session.logout(); statusListener.WaitEvents(); } session.unsubscribeSessionStatus(statusListener); session.Dispose(); } } }