/// <summary> /// ctor /// </summary> /// <param name="session"></param> public SessionStatusListener(O2GSession session, LoginParams loginParams) { mSession = session; mLoginParams = loginParams; Reset(); mSyncSessionEvent = new EventWaitHandle(false, EventResetMode.AutoReset); }
/// <summary> /// Get reports for all accounts /// </summary> /// <param name="session"></param> public static void GetReports(O2GSession session) { O2GLoginRules loginRules = session.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GResponseReaderFactory responseFactory = session.getResponseReaderFactory(); O2GResponse accountsResponse = loginRules.getTableRefreshResponse(O2GTableType.Accounts); O2GAccountsTableResponseReader accountsReader = responseFactory.createAccountsTableReader(accountsResponse); System.Net.WebClient webClient = new System.Net.WebClient(); for (int i = 0; i < accountsReader.Count; i++) { O2GAccountRow account = accountsReader.getRow(i); string url = session.getReportURL(account, DateTime.Now.AddMonths(-1), DateTime.Now, "html", null, null, 0); Console.WriteLine("AccountID={0}; Balance={1}; UsedMargin={2}; Report URL={3}", account.AccountID, account.Balance, account.UsedMargin, url); string content = webClient.DownloadString(url); string filename = account.AccountID + ".html"; System.IO.File.WriteAllText(filename, content); Console.WriteLine("Report is saved to {0}", filename); } }
/// <summary> /// Create entry order request /// </summary> private static O2GRequest CreateEntryOrderRequest(O2GSession session, string sOfferID, string sAccountID, int iAmount, double dRate, string sBuySell, string sOrderType, string sExpireDate) { 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.CreateOrder); valuemap.setString(O2GRequestParamsEnum.OrderType, sOrderType); valuemap.setString(O2GRequestParamsEnum.AccountID, sAccountID); valuemap.setString(O2GRequestParamsEnum.OfferID, sOfferID); valuemap.setString(O2GRequestParamsEnum.BuySell, sBuySell); valuemap.setInt(O2GRequestParamsEnum.Amount, iAmount); valuemap.setDouble(O2GRequestParamsEnum.Rate, dRate); valuemap.setString(O2GRequestParamsEnum.CustomID, "EntryOrder"); if (!string.IsNullOrEmpty(sExpireDate)) { valuemap.setString(O2GRequestParamsEnum.TimeInForce, Constants.TIF.GTD); valuemap.setString(O2GRequestParamsEnum.ExpireDateTime, sExpireDate); // UTCTimestamp format: "yyyyMMdd-HH:mm:ss.SSS" (milliseconds are optional) } request = requestFactory.createOrderRequest(valuemap); if (request == null) { Console.WriteLine(requestFactory.getLastError()); } return request; }
/// <summary> /// Find valid offer by instrument name /// </summary> /// <param name="session"></param> /// <param name="sInstrument"></param> /// <returns>offer</returns> private static O2GOfferRow GetOffer(O2GSession session, string sInstrument) { O2GOfferRow offer = null; bool bHasOffer = false; O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory == null) { throw new Exception("Cannot create response reader factory"); } O2GLoginRules loginRules = session.getLoginRules(); O2GResponse response = loginRules.getTableRefreshResponse(O2GTableType.Offers); O2GOffersTableResponseReader offersResponseReader = readerFactory.createOffersTableReader(response); for (int i = 0; i < offersResponseReader.Count; i++) { offer = offersResponseReader.getRow(i); if (offer.Instrument.Equals(sInstrument)) { if (offer.SubscriptionStatus.Equals("T")) { bHasOffer = true; break; } } } if (!bHasOffer) { return(null); } else { return(offer); } }
/// <summary> /// ctor /// </summary> /// <param name="session"></param> public ResponseListener(O2GSession session) { mRequestIDs = new List <string>(); mResponse = null; mSyncResponseEvent = new EventWaitHandle(false, EventResetMode.AutoReset); mSession = session; }
/// <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); }
public void storeHistoryPriceToDataTable(O2GSession session, O2GResponse response, string sInstrument) { // string ss = string.Format("Request with RequestID={0} is completed:", response.RequestID); // updateLogDelegate(ss); DataTable tmpTable = InstrumentDT.Clone(); O2GResponseReaderFactory factory = session.getResponseReaderFactory(); if (factory != null) { O2GMarketDataSnapshotResponseReader reader = factory.createMarketDataSnapshotReader(response); for (int ii = reader.Count - 1; ii >= 0; ii--) { if (reader.isBar) { InstrumentDT.Rows.Add(reader.getDate(ii), reader.getBidOpen(ii), reader.getBidHigh(ii), reader.getBidLow(ii), reader.getBidClose(ii), reader.getAskOpen(ii), reader.getAskHigh(ii), reader.getAskLow(ii), reader.getAskClose(ii), reader.getVolume(ii)); tmpTable.Rows.Add(reader.getDate(ii), reader.getBidOpen(ii), reader.getBidHigh(ii), reader.getBidLow(ii), reader.getBidClose(ii), reader.getAskOpen(ii), reader.getAskHigh(ii), reader.getAskLow(ii), reader.getAskClose(ii), reader.getVolume(ii)); } else { InstrumentDT.Rows.Add(reader.getDate(ii), reader.getBidClose(ii), reader.getAskClose(ii)); tmpTable.Rows.Add(reader.getDate(ii), reader.getBidClose(ii), reader.getAskClose(ii)); } } SaveDataToFile(tmpTable, sInstrument); } }
private List <Tick> ReadTicks(O2GSession session, O2GResponse response, Symbol symbol, int blockId) { var ticks = new List <Tick>(); var factory = session.getResponseReaderFactory(); if (factory != null) { var reader = factory.createMarketDataSnapshotReader(response); for (int i = reader.Count - 1; i >= 0; i--) { if (reader.isBar) { throw new Exception( "The prices were unexpectedly returned in \"bar\" format!"); } var tick = new Tick() { Symbol = symbol, TickOn = new DateTime(reader.getDate(i).Ticks, DateTimeKind.Utc).ToEstFromUtc(), BidRate = reader.getBid(i).ToRoundedRate(symbol), AskRate = reader.getAsk(i).ToRoundedRate(symbol) }; ticks.Add(tick); } } return(ticks); }
/// <summary> /// Create request for adding existing order into existing contingency group /// </summary> private static O2GRequest AddOrderIntoGroupRequest(O2GSession session, string sAccountID, string sContingencyID, string sOrderID, int iContingencyType) { O2GRequest request = null; O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GValueMap valuemapMain = requestFactory.createValueMap(); valuemapMain.setString(O2GRequestParamsEnum.Command, Constants.Commands.JoinToExistingContingencyGroup); valuemapMain.setInt(O2GRequestParamsEnum.ContingencyGroupType, iContingencyType); valuemapMain.setString(O2GRequestParamsEnum.ContingencyID, sContingencyID); O2GValueMap valuemapChild = requestFactory.createValueMap(); valuemapChild.setString(O2GRequestParamsEnum.OrderID, sOrderID); valuemapChild.setString(O2GRequestParamsEnum.AccountID, sAccountID); valuemapMain.appendChild(valuemapChild); request = requestFactory.createOrderRequest(valuemapMain); if (request == null) { Console.WriteLine(requestFactory.getLastError()); } return request; }
/// <summary> /// Argument Constructor /// </summary> /// <param name="session"></param> /// <param name="logger"></param> public SessionStatusListener(O2GSession session, AsyncClassLogger logger) { _session = session; _logger = logger; Reset(); _syncSessionEvent = new EventWaitHandle(false, EventResetMode.AutoReset); }
/// <summary> /// Get reports for all accounts /// </summary> /// <param name="session"></param> public static void GetReports(O2GSession session) { O2GLoginRules loginRules = session.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GResponseReaderFactory responseFactory = session.getResponseReaderFactory(); O2GResponse accountsResponse = loginRules.getTableRefreshResponse(O2GTableType.Accounts); O2GAccountsTableResponseReader accountsReader = responseFactory.createAccountsTableReader(accountsResponse); System.Net.WebClient webClient = new System.Net.WebClient(); for (int i = 0; i < accountsReader.Count; i++) { O2GAccountRow account = accountsReader.getRow(i); Uri url = new Uri(session.getReportURL(account.AccountID, DateTime.Now.AddMonths(-1), DateTime.Now, "html", null)); Console.WriteLine("AccountID={0}; Balance={1}; Report URL={2}", account.AccountID, account.Balance, url); string content = webClient.DownloadString(url); string prefix = url.Scheme + Uri.SchemeDelimiter + url.Host; string report = O2GHtmlContentUtils.ReplaceRelativePathWithAbsolute(content, prefix); string filename = account.AccountID + ".html"; System.IO.File.WriteAllText(filename, report); Console.WriteLine("Report is saved to {0}", filename); } }
public static O2GAccountRow GetAccount(this O2GSession session) { O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory == null) { throw new Exception("Cannot create response reader factory"); } var loginRules = session.getLoginRules(); var response = loginRules.getTableRefreshResponse(O2GTableType.Accounts); var accountsResponseReader = readerFactory.createAccountsTableReader(response); for (int i = 0; i < accountsResponseReader.Count; i++) { var account = accountsResponseReader.getRow(i); string sAccountKind = account.AccountKind; if (sAccountKind.Equals("32") || sAccountKind.Equals("36")) { if (account.MarginCallFlag.Equals("N")) { return(account); } } } return(null); }
static void Main(string[] args) { O2GSession session = null; try { LoginParams loginParams = new LoginParams(ConfigurationManager.AppSettings); PrintSampleParams("TradingSettings", loginParams); 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); } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { if (statusListener.Connected) { statusListener.Reset(); session.logout(); statusListener.WaitEvents(); } session.unsubscribeSessionStatus(statusListener); session.Dispose(); } } }
/// <summary> /// Find valid account by ID or get the first valid account /// </summary> /// <param name="session"></param> /// <returns>account</returns> private static O2GAccountRow GetAccount(O2GSession session, string sAccountID) { O2GAccountRow account = null; bool bHasAccount = false; O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory == null) { throw new Exception("Cannot create response reader factory"); } O2GLoginRules loginRules = session.getLoginRules(); O2GResponse response = loginRules.getTableRefreshResponse(O2GTableType.Accounts); O2GAccountsTableResponseReader accountsResponseReader = readerFactory.createAccountsTableReader(response); for (int i = 0; i < accountsResponseReader.Count; i++) { account = accountsResponseReader.getRow(i); string sAccountKind = account.AccountKind; if (string.IsNullOrEmpty(sAccountID) || sAccountID.Equals(account.AccountID)) { bHasAccount = true; break; } } if (!bHasAccount) { return(null); } else { return(account); } }
/// <summary> /// Create true market order request /// </summary> private static O2GRequest CreateTrueMarketOrderRequest(O2GSession session, string sOfferID, string sAccountID, int iAmount, string sBuySell) { 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.CreateOrder); valuemap.setString(O2GRequestParamsEnum.OrderType, Constants.Orders.TrueMarketOpen); valuemap.setString(O2GRequestParamsEnum.AccountID, sAccountID); valuemap.setString(O2GRequestParamsEnum.OfferID, sOfferID); valuemap.setString(O2GRequestParamsEnum.BuySell, sBuySell); valuemap.setInt(O2GRequestParamsEnum.Amount, iAmount); valuemap.setString(O2GRequestParamsEnum.CustomID, "TrueMarketOrder"); request = requestFactory.createOrderRequest(valuemap); if (request == null) { Console.WriteLine(requestFactory.getLastError()); } return(request); }
/// <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> /// Create entry order with attached stop and limit orders request /// </summary> private static O2GRequest CreateELSRequest(O2GSession session, string sOfferID, string sAccountID, int iAmount, double dRate, double dRateLimit, double dRateStop, string sBuySell, string sOrderType) { 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.CreateOrder); valuemap.setString(O2GRequestParamsEnum.OrderType, sOrderType); valuemap.setString(O2GRequestParamsEnum.AccountID, sAccountID); valuemap.setString(O2GRequestParamsEnum.OfferID, sOfferID); valuemap.setString(O2GRequestParamsEnum.BuySell, sBuySell); valuemap.setInt(O2GRequestParamsEnum.Amount, iAmount); valuemap.setDouble(O2GRequestParamsEnum.Rate, dRate); valuemap.setDouble(O2GRequestParamsEnum.RateLimit, dRateLimit); valuemap.setDouble(O2GRequestParamsEnum.RateStop, dRateStop); valuemap.setString(O2GRequestParamsEnum.CustomID, "EntryOrderWithStopLimit"); request = requestFactory.createOrderRequest(valuemap); if (request == null) { Console.WriteLine(requestFactory.getLastError()); } return request; }
/// <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; }
public GetHistoricalDataResponseListener(O2GSession session) { requestId = string.Empty; response = null; eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset); this.session = session; }
/// <summary> /// Create request for join two existing entry orders into a new contingency group /// </summary> private static O2GRequest JoinToNewGroupRequest(O2GSession session, string sAccountID, string sPrimaryID, string sSecondaryID, int iContingencyType) { O2GRequest request = null; O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GValueMap valuemapMain = requestFactory.createValueMap(); valuemapMain.setString(O2GRequestParamsEnum.Command, Constants.Commands.JoinToNewContingencyGroup); valuemapMain.setInt(O2GRequestParamsEnum.ContingencyGroupType, iContingencyType); O2GValueMap valuemapChild; valuemapChild = requestFactory.createValueMap(); valuemapChild.setString(O2GRequestParamsEnum.OrderID, sPrimaryID); valuemapChild.setString(O2GRequestParamsEnum.AccountID, sAccountID); valuemapMain.appendChild(valuemapChild); valuemapChild = requestFactory.createValueMap(); valuemapChild.setString(O2GRequestParamsEnum.OrderID, sSecondaryID); valuemapChild.setString(O2GRequestParamsEnum.AccountID, sAccountID); valuemapMain.appendChild(valuemapChild); request = requestFactory.createOrderRequest(valuemapMain); if (request == null) { Console.WriteLine(requestFactory.getLastError()); } return(request); }
static void Main(string[] args) { O2GSession session = null; SessionStatusListener statusListener = null; try { Console.WriteLine("TradingSettings sample\n"); ArgumentParser argParser = new ArgumentParser(args, "TradingSettings"); argParser.AddArguments(ParserArgument.Login, ParserArgument.Password, ParserArgument.Url, ParserArgument.Connection, ParserArgument.SessionID, ParserArgument.Pin); argParser.ParseArguments(); if (!argParser.AreArgumentsValid) { argParser.PrintUsage(); return; } argParser.PrintArguments(); LoginParams loginParams = argParser.LoginParams; 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) { PrintTradingSettings(session); Console.WriteLine("Done!"); } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { if (statusListener.Connected) { statusListener.Reset(); session.logout(); statusListener.WaitEvents(); } session.unsubscribeSessionStatus(statusListener); session.Dispose(); } } }
/// <summary> /// ctor /// </summary> /// <param name="session"></param> public ResponseListener(O2GSession session) { mRequestID = string.Empty; mResponse = null; mSyncResponseEvent = new EventWaitHandle(false, EventResetMode.AutoReset); mSession = session; }
public Connection(O2GSession session, LoginParams loginParams, SampleParams sampleParams, bool bIsFirstAccount) { mSession = session; mLoginParams = loginParams; mSampleParams = sampleParams; mIsFirstAccount = bIsFirstAccount; }
/// <summary> /// Create request for removing order from existing contingency group /// </summary> private static O2GRequest RemoveOrderFromGroupRequest(O2GSession session, string sAccountID, string sOrderID) { O2GRequest request = null; O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GValueMap valuemapMain = requestFactory.createValueMap(); valuemapMain.setString(O2GRequestParamsEnum.Command, Constants.Commands.RemoveFromContingencyGroup); O2GValueMap valuemapChild = requestFactory.createValueMap(); valuemapChild.setString(O2GRequestParamsEnum.Command, Constants.Commands.RemoveFromContingencyGroup); valuemapChild.setString(O2GRequestParamsEnum.OrderID, sOrderID); valuemapChild.setString(O2GRequestParamsEnum.AccountID, sAccountID); valuemapMain.appendChild(valuemapChild); request = requestFactory.createOrderRequest(valuemapMain); if (request == null) { Console.WriteLine(requestFactory.getLastError()); } return(request); }
/// <summary> /// ctor /// </summary> /// <param name="session"></param> public ResponseListener(O2GSession session) { mSession = session; mRequestID = string.Empty; mResponse = null; mSyncResponseEvent = new EventWaitHandle(false, EventResetMode.AutoReset); }
static void Main(string[] args) { O2GSession session = null; try { LoginParams loginParams = new LoginParams(ConfigurationManager.AppSettings); PrintSampleParams("PrintTable", loginParams); 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) { 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); if (account == null) { throw new Exception("No valid accounts"); } PrintOrders(tableManager, account.AccountID); Console.WriteLine("Done!"); } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { if (statusListener.Connected) { statusListener.Reset(); session.logout(); statusListener.WaitEvents(); } session.unsubscribeSessionStatus(statusListener); 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> /// Open Session to FXCM /// </summary> private void OpenSession() { try { // Create a new session object _session = O2GTransport.createSession(); _session.useTableManager(O2GTableManagerMode.Yes, null); // Initialize listener _statusListener = new SessionStatusListener(_session, _logger); // Register event _statusListener.ConnectionEvent += OnSessionStatusChanged; // Register local listener _session.subscribeSessionStatus(_statusListener); _statusListener.Reset(); // Send login request _session.login(_connectionParameters.LoginId, _connectionParameters.Password, _connectionParameters.Url, _connectionParameters.Connection); } catch (Exception exception) { _logger.Error(exception, _type.FullName, "OpenSession"); } }
/// <summary> /// Print accounts table /// </summary> /// <param name="session"></param> private static void PrintCommissionDetails(O2GSession session, SampleParams sampleParams) { //wait until commissions related information will be loaded O2GCommissionsProvider commissionProvider = session.getCommissionsProvider(); while (commissionProvider.getStatus() == O2GCommissionStatus.CommissionStatusLoading) { System.Threading.Thread.Sleep(1000); } if (commissionProvider.getStatus() != O2GCommissionStatus.CommissionStatusReady) { throw new Exception("Could not calculate the estimated commissions."); } //retrieve the required parameter values from the sampleParams O2GAccountRow account = GetAccount(session, sampleParams.AccountID); O2GOfferRow offer = GetOffer(session, sampleParams.Instrument); if (offer == null || account == null) { throw new Exception("Incorrect input parameters."); } O2GCommissionDescriptionsCollection commList = commissionProvider.getCommissionDescriptions(offer.OfferID, account.ATPID); foreach (O2GCommissionDescription descr in commList) { Console.WriteLine("Commission : {0}, {1}, {2}", descr.Stage, descr.UnitType, descr.CommissionValue); } }
public HistoricPricesForm(O2GSession CurrentSession) : this() { m_session = CurrentSession; // JS ADD TIMEFRAMES FROM timeframecollection TO DROPDOWN BOX this.ShowDialog(); }
private O2GRequest GetSetSubscriptionStatusRequest( O2GSession session, Dictionary <string, string> offerIds) { var factory = session.getRequestFactory(); var mainValueMap = factory.createValueMap(); mainValueMap.setString(O2GRequestParamsEnum.Command, "SetSubscriptionStatus"); foreach (var instrument in offerIds.Keys) { var childValueMap = factory.createValueMap(); childValueMap.setString(O2GRequestParamsEnum.Command, "SetSubscriptionStatus"); var status = instrument.IsSymbol() ? "T" : "D"; childValueMap.setString(O2GRequestParamsEnum.SubscriptionStatus, status); childValueMap.setString(O2GRequestParamsEnum.OfferID, offerIds[instrument]); mainValueMap.appendChild(childValueMap); } return(factory.createOrderRequest(mainValueMap)); }
/// <summary> /// Store offers data from response and print it /// </summary> /// <param name="session"></param> /// <param name="response"></param> /// <param name="sInstrument"></param> public void PrintOffers(O2GSession session, O2GResponse response, string sInstrument) { O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory == null) { throw new Exception("Cannot create response reader factory"); } O2GOffersTableResponseReader responseReader = readerFactory.createOffersTableReader(response); for (int i = 0; i < responseReader.Count; i++) { O2GOfferRow offerRow = responseReader.getRow(i); Offer offer; if (mOffers.FindOffer(offerRow.OfferID, out offer)) { if (offerRow.isTimeValid && offerRow.isBidValid && offerRow.isAskValid) { offer.Date = offerRow.Time; offer.Bid = offerRow.Bid; offer.Ask = offerRow.Ask; } } else { offer = new Offer(offerRow.OfferID, offerRow.Instrument, offerRow.Digits, offerRow.PointSize, offerRow.Time, offerRow.Bid, offerRow.Ask); mOffers.AddOffer(offer); } if (string.IsNullOrEmpty(sInstrument) || offerRow.Instrument.Equals(sInstrument)) { Console.WriteLine("{0}, {1}, Bid={2}, Ask={3}", offer.OfferID, offer.Instrument, offer.Bid, offer.Ask); } } }
public bool ConnectToDataFeed(string username, string password, Connection connection) { IsConnceted = false; try { _session = O2GTransport.createSession(); _session.LoginFailed += Session_LoginFailed; _session.SessionStatusChanged += Session_SessionStatusChanged; IsConnceted = Login(username, password, connection.ToString()); _session.RequestCompleted += Session_RequestCompleted; _session.RequestFailed += Session_RequestFailed; _session.TablesUpdates += Session_TablesUpdates; } catch (Exception ex) { Stop(); MessageBox.Show(ex.Message); IsConnceted = false; } return(IsConnceted); }
/// <summary> /// Attach L or S order to existing entry order /// </summary> private static O2GRequest AddOrderForEntryRequest(O2GSession session, O2GTradeRow trade, string sOrderType, double dRate) { if (!sOrderType.Equals("L") && !sOrderType.Equals("S")) { throw new Exception("Incorrect order type"); } 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.CreateOrder); valuemap.setString(O2GRequestParamsEnum.OrderType, sOrderType); // Must be L or S valuemap.setString(O2GRequestParamsEnum.AccountID, trade.AccountID); valuemap.setString(O2GRequestParamsEnum.OfferID, trade.OfferID); valuemap.setString(O2GRequestParamsEnum.TradeID, trade.TradeID); // TradeID from existing Entry order string sOppositeDirection = trade.BuySell == Constants.Buy ? Constants.Sell : Constants.Buy; valuemap.setString(O2GRequestParamsEnum.BuySell, sOppositeDirection); // The order direction must be opposite to the direction of the order which was used to create the position valuemap.setInt(O2GRequestParamsEnum.Amount, trade.Amount); valuemap.setDouble(O2GRequestParamsEnum.Rate, dRate); valuemap.setString(O2GRequestParamsEnum.CustomID, "AttachedEntryOrder"); request = requestFactory.createOrderRequest(valuemap); if (request == null) { Console.WriteLine(requestFactory.getLastError()); } return(request); }
/// <summary> /// Create entry order request /// </summary> private static O2GRequest CreateEntryOrderRequest(O2GSession session, string sOfferID, string sAccountID, int iAmount, double dRate, string sBuySell, string sOrderType, string sExpireDate) { 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.CreateOrder); valuemap.setString(O2GRequestParamsEnum.OrderType, sOrderType); valuemap.setString(O2GRequestParamsEnum.AccountID, sAccountID); valuemap.setString(O2GRequestParamsEnum.OfferID, sOfferID); valuemap.setString(O2GRequestParamsEnum.BuySell, sBuySell); valuemap.setInt(O2GRequestParamsEnum.Amount, iAmount); valuemap.setDouble(O2GRequestParamsEnum.Rate, dRate); valuemap.setString(O2GRequestParamsEnum.CustomID, "EntryOrder"); if (!string.IsNullOrEmpty(sExpireDate)) { valuemap.setString(O2GRequestParamsEnum.TimeInForce, Constants.TIF.GTD); valuemap.setString(O2GRequestParamsEnum.ExpireDayTime, sExpireDate); // UTCTimestamp format: "yyyyMMdd-HH:mm:ss.SSS" (milliseconds are optional) } request = requestFactory.createOrderRequest(valuemap); if (request == null) { Console.WriteLine(requestFactory.getLastError()); } return(request); }
/// <summary> /// ctor /// </summary> /// <param name="session"></param> public SessionStatusListener(O2GSession session, string sSessionID, string sPin) { mSession = session; mSessionID = sSessionID; mPin = sPin; Reset(); mSyncSessionEvent = new EventWaitHandle(false, EventResetMode.AutoReset); }
/// <summary> /// ctor /// </summary> /// <param name="session"></param> public ResponseListener(O2GSession session) { mSession = session; mRequestID = string.Empty; mInstrument = string.Empty; mResponse = null; mSyncResponseEvent = new EventWaitHandle(false, EventResetMode.AutoReset); mOffers = new OfferCollection(); }
/// <summary> /// ctor /// </summary> /// <param name="session"></param> public ResponseListener(O2GSession session) { mSession = session; mRequestID = string.Empty; mRequestIDs = new List<string>(); mResponse = null; mSyncResponseEvent = new EventWaitHandle(false, EventResetMode.AutoReset); mBatchOrderMonitor = null; }
/// <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> /// 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> /// Print accounts table /// </summary> /// <param name="session"></param> private static void PrintAccounts(O2GSession session) { O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory == null) { throw new Exception("Cannot create response reader factory"); } O2GLoginRules loginRules = session.getLoginRules(); O2GResponse response = loginRules.getTableRefreshResponse(O2GTableType.Accounts); O2GAccountsTableResponseReader accountsResponseReader = readerFactory.createAccountsTableReader(response); for (int i = 0; i < accountsResponseReader.Count; i++) { O2GAccountRow accountRow = accountsResponseReader.getRow(i); Console.WriteLine("AccountID: {0}, Balance: {1}, Used margin: {2}", accountRow.AccountID, accountRow.Balance, accountRow.UsedMargin); } }
/// <summary> /// Create true market order request /// </summary> private static O2GRequest CreateTrueMarketOrderRequest(O2GSession session, string sOfferID, string sAccountID, int iAmount, string sBuySell) { 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.CreateOrder); valuemap.setString(O2GRequestParamsEnum.OrderType, Constants.Orders.TrueMarketOpen); valuemap.setString(O2GRequestParamsEnum.AccountID, sAccountID); valuemap.setString(O2GRequestParamsEnum.OfferID, sOfferID); valuemap.setString(O2GRequestParamsEnum.BuySell, sBuySell); valuemap.setInt(O2GRequestParamsEnum.Amount, iAmount); valuemap.setString(O2GRequestParamsEnum.CustomID, "TrueMarketOrder"); request = requestFactory.createOrderRequest(valuemap); return request; }
/// <summary> /// Find valid account by ID or get the first valid account /// </summary> /// <param name="session"></param> /// <returns>account</returns> private static O2GAccountRow GetAccount(O2GSession session, string sAccountID) { O2GAccountRow account = null; bool bHasAccount = false; O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory == null) { throw new Exception("Cannot create response reader factory"); } O2GLoginRules loginRules = session.getLoginRules(); O2GResponse response = loginRules.getTableRefreshResponse(O2GTableType.Accounts); O2GAccountsTableResponseReader accountsResponseReader = readerFactory.createAccountsTableReader(response); for (int i = 0; i < accountsResponseReader.Count; i++) { account = accountsResponseReader.getRow(i); string sAccountKind = account.AccountKind; if (account.MaintenanceType.Equals("0")) // netting account { if (sAccountKind.Equals("32") || sAccountKind.Equals("36")) { if (account.MarginCallFlag.Equals("N")) { if (string.IsNullOrEmpty(sAccountID) || sAccountID.Equals(account.AccountID)) { bHasAccount = true; break; } } } } } if (!bHasAccount) { return null; } else { return account; } }
/// <summary> /// Create OCO request /// </summary> private static O2GRequest CreateOCORequest(O2GSession session, string sOfferID, string sAccountID, int iAmount, double dRateUp, double dRateDown) { O2GRequest request = null; O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GValueMap valuemapMain = requestFactory.createValueMap(); valuemapMain.setString(O2GRequestParamsEnum.Command, Constants.Commands.CreateOCO); // ValueMap for upswing O2GValueMap valuemapUp = requestFactory.createValueMap(); valuemapUp.setString(O2GRequestParamsEnum.Command, Constants.Commands.CreateOrder); valuemapUp.setString(O2GRequestParamsEnum.OrderType, Constants.Orders.StopEntry); valuemapUp.setString(O2GRequestParamsEnum.AccountID, sAccountID); valuemapUp.setString(O2GRequestParamsEnum.OfferID, sOfferID); valuemapUp.setString(O2GRequestParamsEnum.BuySell, Constants.Buy); valuemapUp.setInt(O2GRequestParamsEnum.Amount, iAmount); valuemapUp.setDouble(O2GRequestParamsEnum.Rate, dRateUp); valuemapMain.appendChild(valuemapUp); // ValueMap for downswing O2GValueMap valuemapDown = requestFactory.createValueMap(); valuemapDown.setString(O2GRequestParamsEnum.Command, Constants.Commands.CreateOrder); valuemapDown.setString(O2GRequestParamsEnum.OrderType, Constants.Orders.StopEntry); valuemapDown.setString(O2GRequestParamsEnum.AccountID, sAccountID); valuemapDown.setString(O2GRequestParamsEnum.OfferID, sOfferID); valuemapDown.setString(O2GRequestParamsEnum.BuySell, Constants.Sell); valuemapDown.setInt(O2GRequestParamsEnum.Amount, iAmount); valuemapDown.setDouble(O2GRequestParamsEnum.Rate, dRateDown); valuemapMain.appendChild(valuemapDown); request = requestFactory.createOrderRequest(valuemapMain); if (request == null) { Console.WriteLine(requestFactory.getLastError()); } return request; }
/// <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 history data from response /// </summary> /// <param name="session"></param> /// <param name="response"></param> public static void PrintPrices(O2GSession session, O2GResponse response) { Console.WriteLine("Request with RequestID={0} is completed:", response.RequestID); O2GResponseReaderFactory factory = session.getResponseReaderFactory(); if (factory != null) { O2GMarketDataSnapshotResponseReader reader = factory.createMarketDataSnapshotReader(response); for (int ii = reader.Count - 1; ii >= 0; ii--) { if (reader.isBar) { Console.WriteLine("DateTime={0}, BidOpen={1}, BidHigh={2}, BidLow={3}, BidClose={4}, AskOpen={5}, AskHigh={6}, AskLow={7}, AskClose={8}, Volume={9}", reader.getDate(ii), reader.getBidOpen(ii), reader.getBidHigh(ii), reader.getBidLow(ii), reader.getBidClose(ii), reader.getAskOpen(ii), reader.getAskHigh(ii), reader.getAskLow(ii), reader.getAskClose(ii), reader.getVolume(ii)); } else { Console.WriteLine("DateTime={0}, Bid={1}, Ask={2}", reader.getDate(ii), reader.getBidClose(ii), reader.getAskClose(ii)); } } } }
/// <summary> /// Show permissions for the particular instrument /// </summary> public static void CheckPermissions(O2GSession session, string sInstrument) { O2GLoginRules loginRules = session.getLoginRules(); O2GPermissionChecker permissionChecker = loginRules.getPermissionChecker(); Console.WriteLine("canCreateMarketOpenOrder = {0}", permissionChecker.canCreateMarketOpenOrder(sInstrument)); Console.WriteLine("canChangeMarketOpenOrder = {0}", permissionChecker.canChangeMarketOpenOrder(sInstrument)); Console.WriteLine("canDeleteMarketOpenOrder = {0}", permissionChecker.canDeleteMarketOpenOrder(sInstrument)); Console.WriteLine("canCreateMarketCloseOrder = {0}", permissionChecker.canCreateMarketCloseOrder(sInstrument)); Console.WriteLine("canChangeMarketCloseOrder = {0}", permissionChecker.canChangeMarketCloseOrder(sInstrument)); Console.WriteLine("canDeleteMarketCloseOrder = {0}", permissionChecker.canDeleteMarketCloseOrder(sInstrument)); Console.WriteLine("canCreateEntryOrder = {0}", permissionChecker.canCreateEntryOrder(sInstrument)); Console.WriteLine("canChangeEntryOrder = {0}", permissionChecker.canChangeEntryOrder(sInstrument)); Console.WriteLine("canDeleteEntryOrder = {0}", permissionChecker.canDeleteEntryOrder(sInstrument)); Console.WriteLine("canCreateStopLimitOrder = {0}", permissionChecker.canCreateStopLimitOrder(sInstrument)); Console.WriteLine("canChangeStopLimitOrder = {0}", permissionChecker.canChangeStopLimitOrder(sInstrument)); Console.WriteLine("canDeleteStopLimitOrder = {0}", permissionChecker.canDeleteStopLimitOrder(sInstrument)); Console.WriteLine("canRequestQuote = {0}", permissionChecker.canRequestQuote(sInstrument)); Console.WriteLine("canAcceptQuote = {0}", permissionChecker.canAcceptQuote(sInstrument)); Console.WriteLine("canDeleteQuote = {0}", permissionChecker.canDeleteQuote(sInstrument)); Console.WriteLine("canJoinToNewContingencyGroup = {0}", permissionChecker.canJoinToNewContingencyGroup(sInstrument)); Console.WriteLine("canJoinToExistingContingencyGroup = {0}", permissionChecker.canJoinToExistingContingencyGroup(sInstrument)); Console.WriteLine("canRemoveFromContingencyGroup = {0}", permissionChecker.canRemoveFromContingencyGroup(sInstrument)); Console.WriteLine("canChangeOfferSubscription = {0}", permissionChecker.canChangeOfferSubscription(sInstrument)); Console.WriteLine("canCreateNetCloseOrder = {0}", permissionChecker.canCreateNetCloseOrder(sInstrument)); Console.WriteLine("canChangeNetCloseOrder = {0}", permissionChecker.canChangeNetCloseOrder(sInstrument)); Console.WriteLine("canDeleteNetCloseOrder = {0}", permissionChecker.canDeleteNetCloseOrder(sInstrument)); Console.WriteLine("canCreateNetStopLimitOrder = {0}", permissionChecker.canCreateNetStopLimitOrder(sInstrument)); Console.WriteLine("canChangeNetStopLimitOrder = {0}", permissionChecker.canChangeNetStopLimitOrder(sInstrument)); Console.WriteLine("canDeleteNetStopLimitOrder = {0}", permissionChecker.canDeleteNetStopLimitOrder(sInstrument)); Console.WriteLine("canUseDynamicTrailingForStop = {0}", permissionChecker.canUseDynamicTrailingForStop()); Console.WriteLine("canUseDynamicTrailingForLimit = {0}", permissionChecker.canUseDynamicTrailingForLimit()); Console.WriteLine("canUseDynamicTrailingForEntryStop = {0}", permissionChecker.canUseDynamicTrailingForEntryStop()); Console.WriteLine("canUseDynamicTrailingForEntryLimit = {0}", permissionChecker.canUseDynamicTrailingForEntryLimit()); Console.WriteLine("canUseFluctuateTrailingForStop = {0}", permissionChecker.canUseFluctuateTrailingForStop()); Console.WriteLine("canUseFluctuateTrailingForLimit = {0}", permissionChecker.canUseFluctuateTrailingForLimit()); Console.WriteLine("canUseFluctuateTrailingForEntryStop = {0}", permissionChecker.canUseFluctuateTrailingForEntryStop()); Console.WriteLine("canUseFluctuateTrailingForEntryLimit = {0}", permissionChecker.canUseFluctuateTrailingForEntryLimit()); }
/// <summary> /// Create close market order request /// </summary> private static O2GRequest CreateCloseMarketOrderRequest(O2GSession session, string sInstrument, O2GTradeRow tradeRow) { O2GRequest request = null; O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GLoginRules loginRules = session.getLoginRules(); O2GPermissionChecker permissionChecker = loginRules.getPermissionChecker(); O2GValueMap valuemap = requestFactory.createValueMap(); valuemap.setString(O2GRequestParamsEnum.Command, Constants.Commands.CreateOrder); if (permissionChecker.canCreateMarketCloseOrder(sInstrument) != O2GPermissionStatus.PermissionEnabled) { valuemap.setString(O2GRequestParamsEnum.OrderType, Constants.Orders.TrueMarketOpen); // in USA you need to use "OM" to close a position. } else { valuemap.setString(O2GRequestParamsEnum.OrderType, Constants.Orders.TrueMarketClose); valuemap.setString(O2GRequestParamsEnum.TradeID, tradeRow.TradeID); } valuemap.setString(O2GRequestParamsEnum.AccountID, tradeRow.AccountID); valuemap.setString(O2GRequestParamsEnum.OfferID, tradeRow.OfferID); valuemap.setString(O2GRequestParamsEnum.BuySell, tradeRow.BuySell.Equals(Constants.Buy) ? Constants.Sell : Constants.Buy); valuemap.setInt(O2GRequestParamsEnum.Amount, tradeRow.Amount); valuemap.setString(O2GRequestParamsEnum.CustomID, "CloseMarketOrder"); request = requestFactory.createOrderRequest(valuemap); if (request == null) { Console.WriteLine(requestFactory.getLastError()); } return request; }
// Get current prices and calculate order price public void GetOfferRate(O2GSession session, string sInstrument, string mBuySell, string mOrderType, int entryPips,int stopPips) { double dBid = 0.0; double dAsk = 0.0; double dPointSize = 0.0; try { O2GLoginRules loginRules = session.getLoginRules(); if (loginRules != null && loginRules.isTableLoadedByDefault(O2GTableType.Offers)) { O2GResponse offersResponse = loginRules.getTableRefreshResponse(O2GTableType.Offers); O2GResponseReaderFactory responseFactory = session.getResponseReaderFactory(); O2GOffersTableResponseReader offersReader = responseFactory.createOffersTableReader(offersResponse); for (int i = 0; i < offersReader.Count; i++) { O2GOfferRow offer = offersReader.getRow(i); if (sInstrument == offer.Instrument) { mOfferID = offer.OfferID; dBid = offer.Bid; dAsk = offer.Ask; 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 (mOrderType == Constants.Orders.LimitEntry) { if (mBuySell == Constants.Buy) { mRate = dAsk - entryPips * dPointSize; // mRateLimit = mRate + 10 * dPointSize; mRateStop = mRate - stopPips * dPointSize; pegStopOffset = stopPips; } else { mRate = dBid + entryPips * dPointSize; // mRateLimit = mRate - 10 * dPointSize; mRateStop = mRate + stopPips * dPointSize; pegStopOffset = -stopPips; } } else // use StopEntry! { if (mBuySell == Constants.Buy) { mRate = dAsk + entryPips * dPointSize; //mRateLimit = mRate + 10 * dPointSize; mRateStop = mRate - stopPips * dPointSize; pegStopOffset = -stopPips; } else // Sell { mRate = dBid - entryPips * dPointSize; //mRateLimit = mRate - 10 * dPointSize; mRateStop = mRate + stopPips * dPointSize; pegStopOffset = stopPips; } } mHasOffer = true; break; } } if (!mHasOffer) log.debug("You specified invalid instrument. No action will be taken."); } } catch (Exception e) { log.debug("Exception in GetOfferRate().\n\t " + e.Message); } }
int trailStepStop = 1; // dynamic #endregion Fields #region Constructors public ELSTrade(O2GSession session,Display display) { this.mSession = session; this.display = display; }
// Get account for trade public void GetAccount(O2GSession session) { try { O2GLoginRules loginRules = session.getLoginRules(); if (loginRules != null && loginRules.isTableLoadedByDefault(O2GTableType.Accounts)) { string sAccountID = string.Empty; string sAccountKind = string.Empty; O2GResponse accountsResponse = loginRules.getTableRefreshResponse(O2GTableType.Accounts); O2GResponseReaderFactory responseFactory = session.getResponseReaderFactory(); O2GAccountsTableResponseReader accountsReader = responseFactory.createAccountsTableReader(accountsResponse); for (int i = 0; i < accountsReader.Count; i++) { O2GAccountRow account = accountsReader.getRow(i); sAccountID = account.AccountID; sAccountKind = account.AccountKind; if (sAccountKind == "32" || sAccountKind == "36") { mAccountID = sAccountID; mHasAccount = true; break; } } if (!mHasAccount) log.debug("You don't have any accounts available for trading. No action will be taken."); } } catch (Exception e) { log.debug("Exception in GetAccounts():\n\t " + e.Message); } }
public ELSResponseListener(O2GSession session, Display display) { this.mSession = session; this.display = display; manualEvent = new ManualResetEvent(false); }
public CreateOrder(O2GSession session, Display display) { this.session = session; this.display = display; session.subscribeResponse(this); }
/// <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"); } }
/// <summary> /// Create close all order request /// </summary> private static O2GRequest CreateCloseMarketNettingOrderRequest(O2GSession session, CloseOrdersData closeOrdersData) { O2GRequest request = null; O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GValueMap batchValuemap = requestFactory.createValueMap(); batchValuemap.setString(O2GRequestParamsEnum.Command, Constants.Commands.CreateOrder); string sOfferID = closeOrdersData.OfferID; string sAccountID = closeOrdersData.AccountID; OrderSide side = closeOrdersData.Side; O2GValueMap childValuemap; switch (side) { case OrderSide.Buy: childValuemap = requestFactory.createValueMap(); childValuemap.setString(O2GRequestParamsEnum.Command, Constants.Commands.CreateOrder); childValuemap.setString(O2GRequestParamsEnum.NetQuantity, "Y"); childValuemap.setString(O2GRequestParamsEnum.OrderType, Constants.Orders.TrueMarketClose); childValuemap.setString(O2GRequestParamsEnum.AccountID, sAccountID); childValuemap.setString(O2GRequestParamsEnum.OfferID, sOfferID); childValuemap.setString(O2GRequestParamsEnum.BuySell, Constants.Buy); batchValuemap.appendChild(childValuemap); break; case OrderSide.Sell: childValuemap = requestFactory.createValueMap(); childValuemap.setString(O2GRequestParamsEnum.Command, Constants.Commands.CreateOrder); childValuemap.setString(O2GRequestParamsEnum.NetQuantity, "Y"); childValuemap.setString(O2GRequestParamsEnum.OrderType, Constants.Orders.TrueMarketClose); childValuemap.setString(O2GRequestParamsEnum.AccountID, sAccountID); childValuemap.setString(O2GRequestParamsEnum.OfferID, sOfferID); childValuemap.setString(O2GRequestParamsEnum.BuySell, Constants.Sell); batchValuemap.appendChild(childValuemap); break; case OrderSide.Both: childValuemap = requestFactory.createValueMap(); childValuemap.setString(O2GRequestParamsEnum.Command, Constants.Commands.CreateOrder); childValuemap.setString(O2GRequestParamsEnum.NetQuantity, "Y"); childValuemap.setString(O2GRequestParamsEnum.OrderType, Constants.Orders.TrueMarketClose); childValuemap.setString(O2GRequestParamsEnum.AccountID, sAccountID); childValuemap.setString(O2GRequestParamsEnum.OfferID, sOfferID); childValuemap.setString(O2GRequestParamsEnum.BuySell, Constants.Buy); batchValuemap.appendChild(childValuemap); childValuemap = requestFactory.createValueMap(); childValuemap.setString(O2GRequestParamsEnum.Command, Constants.Commands.CreateOrder); childValuemap.setString(O2GRequestParamsEnum.NetQuantity, "Y"); childValuemap.setString(O2GRequestParamsEnum.OrderType, Constants.Orders.TrueMarketClose); childValuemap.setString(O2GRequestParamsEnum.AccountID, sAccountID); childValuemap.setString(O2GRequestParamsEnum.OfferID, sOfferID); childValuemap.setString(O2GRequestParamsEnum.BuySell, Constants.Sell); batchValuemap.appendChild(childValuemap); break; } request = requestFactory.createOrderRequest(batchValuemap); if (request == null) { Console.WriteLine(requestFactory.getLastError()); } return request; }
/// <summary> /// Find valid offer by instrument name /// </summary> /// <param name="session"></param> /// <param name="sInstrument"></param> /// <returns>offer</returns> private static O2GOfferRow GetOffer(O2GSession session, string sInstrument) { O2GOfferRow offer = null; bool bHasOffer = false; O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory == null) { throw new Exception("Cannot create response reader factory"); } O2GLoginRules loginRules = session.getLoginRules(); O2GResponse response = loginRules.getTableRefreshResponse(O2GTableType.Offers); O2GOffersTableResponseReader offersResponseReader = readerFactory.createOffersTableReader(response); for (int i = 0; i < offersResponseReader.Count; i++) { offer = offersResponseReader.getRow(i); if (offer.Instrument.Equals(sInstrument)) { if (offer.SubscriptionStatus.Equals("T")) { bHasOffer = true; break; } } } if (!bHasOffer) { return null; } else { return offer; } }
/// <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; }