Exemplo n.º 1
0
        /// <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"))  // not 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);
            }
        }
Exemplo n.º 2
0
        /// <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);

            using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient())
            {
                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}; BaseUnitSize={2}; Report URL={3}",
                                      account.AccountID, account.Balance, account.BaseUnitSize, url);

                    var response = httpClient.GetAsync(url).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        var responseContent = response.Content;
                        // by calling .Result you are synchronously reading the result
                        string content  = responseContent.ReadAsStringAsync().Result;
                        string filename = account.AccountID + ".html";
                        string prefix   = url.Scheme + "://" + url.Host + "/";
                        string report   = O2GHtmlContentUtils.ReplaceRelativePathWithAbsolute(content, prefix);
                        System.IO.File.WriteAllText(filename, report);
                        Console.WriteLine("Report is saved to {0}", filename);
                    }
                    else
                    {
                        throw new Exception("Report is not received.");
                    }
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Print offers and find 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;
            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++)
            {
                O2GOfferRow offerRow = offersResponseReader.getRow(i);
                if (offerRow.Instrument.Equals(sInstrument))
                {
                    offer = offerRow;
                }
                switch (offerRow.SubscriptionStatus)
                {
                case Constants.SubscriptionStatuses.ViewOnly:
                    Console.WriteLine("{0} : [V]iew only", offerRow.Instrument);
                    break;

                case Constants.SubscriptionStatuses.Disable:
                    Console.WriteLine("{0} : [D]isabled", offerRow.Instrument);
                    break;

                case Constants.SubscriptionStatuses.Tradable:
                    Console.WriteLine("{0} : Available for [T]rade", offerRow.Instrument);
                    break;

                default:
                    Console.WriteLine("{0} : {1}", offerRow.Instrument, offerRow.SubscriptionStatus);
                    break;
                }
            }
            return(offer);
        }
Exemplo n.º 4
0
        public static MarketDataEventArg ProcessMarketData(FXSession connection, O2GResponse response)
        {
            try
            {
                O2GResponseReaderFactory            rrfactory = connection.Session.getResponseReaderFactory();
                O2GMarketDataSnapshotResponseReader mReader   = rrfactory.createMarketDataSnapshotReader(response);

                var d = new SortedList <DateTime, Tick>(mReader.Count);

                for (int i = 0; i < mReader.Count; i++)
                {
                    // information like reader.getDate(i), reader.getBidOpen(i), reader.getBidHigh(i), reader.getBidLow(i), reader.getBidClose(i), reader.getVolume(i) is now available
                    //Console.WriteLine(i + ":" + mReader.getDate(i).ToString() + ":" + mReader.getBidOpen(i));
                    //create a quantum of ticks for the market data
                    var tick = new Tick(
                        mReader.getBid(i),
                        mReader.getBidOpen(i),
                        mReader.getBidHigh(i),
                        mReader.getBidLow(i),
                        mReader.getBidClose(i),
                        mReader.getAsk(i),
                        mReader.getAskOpen(i),
                        mReader.getAskHigh(i),
                        mReader.getAskLow(i),
                        mReader.getAskClose(i),
                        mReader.getVolume(i),
                        mReader.getDate(i));

                    d.Add(mReader.getDate(i), tick);
                }

                var q = new Quantum(d);
                return(new MarketDataEventArg(q));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(new MarketDataEventArg(new Quantum(new SortedList <DateTime, Tick>(300))));
            }
        }
Exemplo n.º 5
0
        /// <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");
            }
        }
Exemplo n.º 6
0
        /// <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))
                {
                    if (offer.Instrument.Equals("Copper"))
                    {
                        //Console.WriteLine("{0}, {1}, Bid={2}, Ask={3}", offer.OfferID, offer.Instrument, offer.Bid, offer.Ask);
                    }
                    Console.WriteLine("{0}, {1}, Bid={2}, Ask={3}", offer.OfferID, offer.Instrument, offer.Bid, offer.Ask);
                }
            }
        }
        public void onTablesUpdates(O2GResponse data)
        {
            O2GResponseReaderFactory factory = mSession.getResponseReaderFactory();

            if (factory != null)
            {
                O2GTablesUpdatesReader reader = factory.createTablesUpdatesReader(data);
                for (int ii = 0; ii < reader.Count; ii++)
                {
                    if (reader.getUpdateTable(ii) == O2GTableType.Orders)
                    {
                        O2GOrderRow orderRow = reader.getOrderRow(ii);
                        if (reader.getUpdateType(ii) == O2GTableUpdateType.Insert)
                        {
                            mOrderID = orderRow.OrderID;
                            mSyncResponseEvent.Set();
                            break;
                        }
                    }
                }
            }
        }
        public void onTablesUpdates(O2GResponse data)
        {
            O2GResponseReaderFactory factory = mSession.getResponseReaderFactory();

            if (factory != null)
            {
                O2GTablesUpdatesReader reader = factory.createTablesUpdatesReader(data);
                for (int ii = 0; ii < reader.Count; ii++)
                {
                    if (reader.getUpdateTable(ii) == O2GTableType.Orders)
                    {
                        O2GOrderRow orderRow = reader.getOrderRow(ii);
                        if (orderRow.RequestID.Equals(mRequestID))
                        {
                            switch (reader.getUpdateType(ii))
                            {
                            case O2GTableUpdateType.Insert:
                                if (IsLimitEntryOrder(orderRow) && string.IsNullOrEmpty(mOrderID))
                                {
                                    mOrderID = orderRow.OrderID;
                                    Console.WriteLine("The order has been added. Order ID: {0}, Rate: {1}, Time In Force: {2}",
                                                      orderRow.OrderID,
                                                      orderRow.Rate,
                                                      orderRow.TimeInForce);
                                    mSyncResponseEvent.Set();
                                }
                                break;

                            case O2GTableUpdateType.Delete:
                                Console.WriteLine("The order has been deleted. Order ID: {0}", orderRow.OrderID);
                                mSyncResponseEvent.Set();
                                break;
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 9
0
        /// <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);
        }
Exemplo n.º 10
0
        /// <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));
                    }
                }
            }
        }
        void ReadOffers(O2GResponse offers)
        {
            O2GResponseReaderFactory factory = mSession.getResponseReaderFactory();

            if (factory != null)
            {
                O2GOffersTableResponseReader reader = factory.createOffersTableReader(offers);

                mOffers.Clear();
                mOffersList.Clear();

                for (int i = 0; i < reader.Count; i++)
                {
                    O2GOfferRow row = reader.getRow(i);
                    //mTimeConverter.convert(row.Time, O2GTimeConverterTimeZone.UTC, mTimezone)
                    //DateTime dt = mTimeConverter.convert(row.Time, O2GTimeConverterTimeZone.Server, O2GTimeConverterTimeZone.UTC);
                    DateTime dt    = row.Time;
                    Offer    offer = new Offer(row.Instrument, dt, row.Bid, row.Ask, row.Volume, row.Digits, row.PointSize);
                    mOffers[row.OfferID] = offer;
                    mOffersList.Add(offer);
                    SendTick(offer);
                }
            }
        }
Exemplo n.º 12
0
        /// <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);
        }
Exemplo n.º 13
0
        // Print trading settings of the first account
        private static void PrintTradingSettings(O2GSession session)
        {
            O2GLoginRules loginRules = session.getLoginRules();

            if (loginRules == null)
            {
                throw new Exception("Cannot get login rules");
            }
            O2GResponse accountsResponse = loginRules.getTableRefreshResponse(O2GTableType.Accounts);

            if (accountsResponse == null)
            {
                throw new Exception("Cannot get response");
            }
            O2GResponse offersResponse = loginRules.getTableRefreshResponse(O2GTableType.Offers);

            if (offersResponse == null)
            {
                throw new Exception("Cannot get response");
            }
            O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider();
            O2GResponseReaderFactory   factory = session.getResponseReaderFactory();

            if (factory == null)
            {
                throw new Exception("Cannot create response reader factory");
            }
            O2GAccountsTableResponseReader accountsReader    = factory.createAccountsTableReader(accountsResponse);
            O2GOffersTableResponseReader   instrumentsReader = factory.createOffersTableReader(offersResponse);
            O2GAccountRow account = accountsReader.getRow(0);

            for (int i = 0; i < instrumentsReader.Count; i++)
            {
                O2GOfferRow     instrumentRow         = instrumentsReader.getRow(i);
                string          instrument            = instrumentRow.Instrument;
                int             condDistStopForTrade  = tradingSettingsProvider.getCondDistStopForTrade(instrument);
                int             condDistLimitForTrade = tradingSettingsProvider.getCondDistLimitForTrade(instrument);
                int             condDistEntryStop     = tradingSettingsProvider.getCondDistEntryStop(instrument);
                int             condDistEntryLimit    = tradingSettingsProvider.getCondDistEntryLimit(instrument);
                int             minQuantity           = tradingSettingsProvider.getMinQuantity(instrument, account);
                int             maxQuantity           = tradingSettingsProvider.getMaxQuantity(instrument, account);
                int             baseUnitSize          = tradingSettingsProvider.getBaseUnitSize(instrument, account);
                O2GMarketStatus marketStatus          = tradingSettingsProvider.getMarketStatus(instrument);
                int             minTrailingStep       = tradingSettingsProvider.getMinTrailingStep();
                int             maxTrailingStep       = tradingSettingsProvider.getMaxTrailingStep();
                double          mmr = tradingSettingsProvider.getMMR(instrument, account);
                double          mmr2 = 0, emr = 0, lmr = 0;
                bool            threeLevelMargin = tradingSettingsProvider.getMargins(instrument, account, ref mmr2, ref emr, ref lmr);
                string          sMarketStatus    = "unknown";
                switch (marketStatus)
                {
                case O2GMarketStatus.MarketStatusOpen:
                    sMarketStatus = "Market Open";
                    break;

                case O2GMarketStatus.MarketStatusClosed:
                    sMarketStatus = "Market Close";
                    break;
                }
                Console.WriteLine("Instrument: {0}, Status: {1}", instrument, sMarketStatus);
                Console.WriteLine("Cond.Dist: ST={0}; LT={1}", condDistStopForTrade, condDistLimitForTrade);
                Console.WriteLine("Cond.Dist entry stop={0}; entry limit={1}", condDistEntryStop,
                                  condDistEntryLimit);
                Console.WriteLine("Quantity: Min={0}; Max={1}. Base unit size={2}; MMR={3}", minQuantity,
                                  maxQuantity, baseUnitSize, mmr);
                if (threeLevelMargin)
                {
                    Console.WriteLine("Three level margin: MMR={0}; EMR={1}; LMR={2}", mmr2, emr, lmr);
                }
                else
                {
                    Console.WriteLine("Single level margin: MMR={0}; EMR={1}; LMR={2}", mmr2, emr, lmr);
                }
                Console.WriteLine("Trailing step: {0}-{1}", minTrailingStep, maxTrailingStep);
            }
        }
Exemplo n.º 14
0
        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>
        /// Fetches historical data from FXCM server
        /// </summary>
        /// <param name="historicDataRequest"></param>
        public void GetHistoricalData(HistoricDataRequest historicDataRequest)
        {
            // Create a new factory
            O2GRequestFactory factory = _session.getRequestFactory();

            // Get time frame
            O2GTimeframe timeframe = factory.Timeframes[GetFxcmTimeFrame(historicDataRequest)];

            if (timeframe == null)
            {
                _logger.Error("Invalid time format", _type.FullName, "GetHistoricalData");

                return;
            }

            // Clear any existing data
            _barCollection.Clear();

            // Request historical snapshot
            O2GRequest request = factory.createMarketDataSnapshotRequestInstrument(historicDataRequest.Security.Symbol, timeframe, 300);

            DateTime endTime = historicDataRequest.EndTime;

            do // cause there is limit for returned candles amount
            {
                factory.fillMarketDataSnapshotRequestTime(request, historicDataRequest.StartTime, endTime, false);

                SetRequestId(request.RequestID);

                _session.sendRequest(request);

                if (!WaitEvents())
                {
                    _logger.Error("Response waiting timeout expired", _type.FullName, "GetHistoricalData");

                    return;
                }

                // Shift "to" bound to oldest datetime of returned data
                O2GResponse response = 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(endTime, reader.getDate(0)) != 0)
                            {
                                endTime = reader.getDate(0); // earliest datetime of returned data
                            }
                            else
                            {
                                break;
                            }
                        }
                        else
                        {
                            if (_logger.IsInfoEnabled)
                            {
                                _logger.Info("Response waiting timeout expired", _type.FullName, "GetHistoricalData");
                            }
                            break;
                        }
                    }
                    ExtractPrices(_session, response, historicDataRequest);
                }
                else
                {
                    break;
                }
            } while (endTime > historicDataRequest.StartTime);

            if (_barCollection.Count > 0)
            {
                if (_historicalDataEvent != null)
                {
                    _barCollection.Reverse();

                    // Create historical data object
                    var historicalData = new HistoricBarData(historicDataRequest.Security, historicDataRequest.MarketDataProvider, DateTime.UtcNow);
                    historicalData.Bars  = _barCollection.ToArray();
                    historicalData.ReqId = historicDataRequest.Id;

                    // Raise Event
                    _historicalDataEvent(historicalData);
                }

                _barCollection.Clear();
            }
        }
Exemplo n.º 16
0
        public void processData(O2GResponse response, HddMainFormBasic hdd, DataSetup dataSetup)
        {
            bool     outOfRangeDateFound = false;
            DateTime tempEndDate         = new DateTime();

            try
            {
                //Exit thread if the value is false
                if (!keepThreadRunning)
                {
                    return;
                }

                var query1 = HddMainFormBasic.threadDictionary.Keys.FirstOrDefault(t => t == response.RequestID);
                if (query1 != null)
                {
                    HddMainFormBasic.threadDictionary[query1].CallBack = true;
                }


                O2GResponseReaderFactory readerfactory = tss.Session.getResponseReaderFactory();

                O2GMarketDataSnapshotResponseReader reader = readerfactory.createMarketDataSnapshotReader(response);

                DateTime from = new DateTime();
                DateTime to   = new DateTime();
                if (reader.Count > 0)
                {
                    from = reader.getDate(0);
                    to   = reader.getDate(reader.Count - 1);
                }
                Console.WriteLine("Market data received from " + from.ToString("MM/dd/yyyy HH:mm:ss") + " to " + to.ToString("MM/dd/yyyy HH:mm:ss"));

                //insert data into price list
                for (int j = reader.Count - 1; j > -1; j--)
                {
                    prices.Add(new Data(reader.getAskOpen(j), reader.getAskHigh(j), reader.getAskLow(j), reader.getAskClose(j), reader.getBidOpen(j), reader.getBidHigh(j), reader.getBidLow(j), reader.getBidClose(j), reader.getDate(j), reader.getVolume(j)));
                }
                //if less rates are obtained then it means we reached the end.
                //Nothing came back for the timeframe specified means, nothing exist in the remaining timeframe.
                if (reader.Count < 300 || reader.Count == 0)
                {
                    outOfRangeDateFound = true;
                    tempEndDate         = endDate;
                }

                if (!outOfRangeDateFound)
                {
                    removeLastDate(prices[prices.Count - 1].StartTime, prices);

                    tempEndDate = prices[prices.Count - 1].StartTime;
                }
                if (prices.Count > 3000)
                {
                    DataBaseHandler.getInstance().addEntries(prices);
                    prices.Clear();
                    if (timeInterval.Equals("t1"))
                    {
                        Thread.Sleep(2000);
                    }
                }

                //Get total ticks between end date and start date
                long totalTicks = tempEndDate.Ticks - dataSetup.StartDate.Ticks;

                currentStep           = 0;
                currentStep           = ((double)(totalTicks * maxIterations)) / initialTotalTicks;
                dataSetup.currentStep = currentStep;
                tick = reader.Count;
                Time = sw.Elapsed;

                #region repeat process OR quit
                if (outOfRangeDateFound == false)
                {
                    try
                    {
                        //Call HDD function to calculate more data
                        DataSetup ds = new DataSetup();
                        ds = dataSetup;

                        ds.EndDate = tempEndDate;
                        hdd.sendRequest(startDate, tempEndDate, ds);
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("Error: " + e.Message);
                    }
                }
                else
                {
                    Console.WriteLine("Done");

                    #region Final flushing to database
                    try
                    {
                        if (prices.Count > 0)
                        {
                            //Finally write to database
                            DataBaseHandler.getInstance().addEntries(prices);
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message, "Error in writing data", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        logger.Debug(e.Message);
                        logger.Debug(e.StackTrace);
                    }
                    finally
                    {
                        prices.Clear();
                    }
                    #endregion

                    #region Writing to a File
                    long rows = 0;
                    rows = DataBaseHandler.getInstance().getNumberOfRows();

                    //Calculate the levels first before requesting data.
                    long        templevel = 0;
                    List <long> levels    = new List <long>();
                    levels.Add(0);
                    while (true)
                    {
                        if (templevel + 5000 < rows)
                        {
                            templevel += 5000;
                            levels.Add(templevel);
                        }
                        else
                        {
                            levels.Add(rows);
                            break;
                        }
                    }
                    logger.Debug("Levels of data to be requested from database: " + levels.ToString());
                    dataSetup.isAlive = false;
                    #endregion
                }
                #endregion
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + "\n" + e.Source, "Error");
            }
        }
Exemplo n.º 17
0
        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();
                }
            }
        }
        private static bool ProcessOrderRequest(FxcmBroker fxcm, O2GRequest request, out string orderId)
        {
            var ret       = string.Empty;
            var waitOrder = new ManualResetEvent(false);

            var responseListener = new ResponseListener(
                fxcm.Session,
                data =>
            {
                O2GResponseReaderFactory factory = fxcm.Session.getResponseReaderFactory();
                if (factory != null)
                {
                    O2GTablesUpdatesReader reader = factory.createTablesUpdatesReader(data);
                    for (int ii = 0; ii < reader.Count; ii++)
                    {
                        if (reader.getUpdateTable(ii) == O2GTableType.Orders)
                        {
                            O2GOrderRow orderRow = reader.getOrderRow(ii);
                            if (reader.getUpdateType(ii) == O2GTableUpdateType.Insert)
                            {
                                ret = orderRow.OrderID;
                                waitOrder.Set();
                                break;
                            }
                        }
                    }
                }
            });

            fxcm.Session.subscribeResponse(responseListener);

            try
            {
                responseListener.SetRequestID(request.RequestID);
                fxcm.Session.sendRequest(request);
                if (responseListener.WaitEvents())
                {
                    if (!string.IsNullOrEmpty(responseListener.Error))
                    {
                        Log.Error($"Unable to process request - {responseListener.Error}");
                        orderId = ret;
                        return(false);
                    }

                    // Get order ID
                    waitOrder.WaitOne();

                    orderId = ret;
                    return(true);
                }
                else
                {
                    Log.Error($"Unable to process request");
                    orderId = ret;
                    return(false);
                }
            }
            finally
            {
                fxcm.Session.unsubscribeResponse(responseListener);
            }
        }
Exemplo n.º 19
0
        private void GetHistoryPrices(O2GSession O2GSession, string Instrument, string Interval, DateTime DtFrom, DateTime DtTo)
        {
            m_responseListener = new ResponseListener(O2GSession);
            O2GSession.subscribeResponse(m_responseListener);

            O2GRequestFactory factory = O2GSession.getRequestFactory();

            O2GTimeframeCollection timeframecollection = factory.Timeframes;
            O2GTimeframe           Timeframe           = timeframecollection[Interval];

            if (Timeframe == null)
            {
                throw new Exception(string.Format("Timeframe '{0}' is incorrect!", Timeframe));
            }

            O2GRequest request  = factory.createMarketDataSnapshotRequestInstrument(Instrument, Timeframe, 300);
            DateTime   DtFirst  = DtTo;
            DateTime   DatePrec = System.DateTime.MinValue;

            //TimeSpan PricesTimeSpan = System.TimeSpan.MinValue;

            //if (Interval == "m5")
            //{
            //    PricesTimeSpan = new TimeSpan(0, 0, 5, 0, 0);
            //}

            do // cause there is limit for returned candles amount
            {
                factory.fillMarketDataSnapshotRequestTime(request, DtFrom, DtFirst, false);
                m_responseListener.SetRequestID(request.RequestID);
                O2GSession.sendRequest(request);

                if (!m_responseListener.WaitEvents())
                {
                    throw new Exception("Response waiting timeout expired");
                }
                // shift "to" bound to oldest datetime of returned data
                O2GResponse response = m_responseListener.GetResponse();
                if (response != null && response.Type == O2GResponseType.MarketDataSnapshot)
                {
                    O2GResponseReaderFactory readerFactory = O2GSession.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--)
                                {
                                    if (reader.getDate(nData) != DatePrec)
                                    {
                                        m_datetime.Add(reader.getDate(nData));

                                        m_ask.Add(reader.getAsk(nData));
                                        m_askopen.Add(reader.getAskOpen(nData));
                                        m_askclose.Add(reader.getAskClose(nData));
                                        m_askhigh.Add(reader.getAskHigh(nData));
                                        m_asklow.Add(reader.getAskLow(nData));

                                        m_bid.Add(reader.getBid(nData));
                                        m_bidopen.Add(reader.getBidOpen(nData));
                                        m_bidclose.Add(reader.getBidClose(nData));
                                        m_bidhigh.Add(reader.getBidHigh(nData));
                                        m_bidlow.Add(reader.getBidLow(nData));
                                    }
                                    //else
                                    //{
                                    //    break;
                                    //}

                                    DatePrec = reader.getDate(nData);
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                        else
                        {
                            Console.WriteLine("0 rows received");
                            break;
                        }
                    }
                    // PrintPrices(session, response);
                }
                else
                {
                    break;
                }
            } while (DtFirst > DtFrom);

            m_datetime.Reverse();

            m_ask.Reverse();
            m_askopen.Reverse();
            m_askclose.Reverse();
            m_askhigh.Reverse();
            m_asklow.Reverse();

            m_bid.Reverse();
            m_bidopen.Reverse();
            m_bidclose.Reverse();
            m_bidhigh.Reverse();
            m_bidlow.Reverse();
        }
Exemplo n.º 20
0
        // **AFTER LOG IN**
        // Background worker for table listeners
        private void priceBW_DoWork(object sender, DoWorkEventArgs e)
        {
            Console.WriteLine("Entered BW");

            mSession.useTableManager(O2GTableManagerMode.Yes, null);

            tableManager  = mSession.getTableManager();
            managerStatus = tableManager.getStatus();

            while (managerStatus == O2GTableManagerStatus.TablesLoading)
            {
                Thread.Sleep(50);
                managerStatus = tableManager.getStatus();
            }
            if (managerStatus == O2GTableManagerStatus.TablesLoadFailed)
            {
                this.Invoke(new MethodInvoker(delegate { actiBox.AppendText("WARNING: LOADING TABLES FAILED!" + Environment.NewLine); }));
                return;
            }
            // Check Accounts Table and Grab Information
            try
            {
                O2GLoginRules loginRules = mSession.getLoginRules();
                Console.WriteLine("Tables are loaded!");
                // Check if Accounts table is loaded automatically
                if (loginRules != null && loginRules.isTableLoadedByDefault(O2GTableType.Accounts))
                {
                    // If table is loaded, use getTableRefreshResponse method
                    O2GResponse accountsResponse             = loginRules.getTableRefreshResponse(O2GTableType.Accounts);
                    O2GResponseReaderFactory responseFactory = mSession.getResponseReaderFactory();
                    if (responseFactory != null)
                    {
                        O2GAccountsTableResponseReader accountsReader = responseFactory.createAccountsTableReader(accountsResponse);

                        for (int i = 0; i < accountsReader.Count; i++)
                        {
                            account      = accountsReader.getRow(i);
                            accountValue = account.Balance;
                            this.Invoke(new MethodInvoker(delegate { accountValueBox.Text = "$" + Convert.ToString(accountValue); }));
                            acctEq = account.Balance;
                            this.Invoke(new MethodInvoker(delegate { accountLevBox.Text = "$" + Convert.ToString(acctEq); }));
                            this.Invoke(new MethodInvoker(delegate { accountEquityBox.Text = "$" + Convert.ToString(acctEq); }));
                            sAccountID  = account.AccountID.ToString();
                            amountLimit = account.AmountLimit;
                            baseSize    = account.BaseUnitSize;
                            if (account.MaintenanceType == "Y")
                            {
                                this.Invoke(new MethodInvoker(delegate { hedgingBox.Text = "Yes"; }));
                                hedgingLong = true;
                                Settings.Default.hedgeLong = true;
                                hedgingShort = true;
                                Settings.Default.hedgeShort = true;
                                this.Invoke(new MethodInvoker(delegate { longCheckBox.Checked = true; }));
                                this.Invoke(new MethodInvoker(delegate { shortCheckBox.Checked = true; }));
                            }
                            else
                            {
                                this.Invoke(new MethodInvoker(delegate { hedgingBox.Text = "No"; }));
                                if (hedgingShort == false)
                                {
                                    hedgingLong = true;
                                    this.Invoke(new MethodInvoker(delegate { longCheckBox.Checked = true; }));
                                    this.Invoke(new MethodInvoker(delegate { shortCheckBox.Checked = false; }));
                                }
                                else
                                {
                                    hedgingShort = true;
                                    this.Invoke(new MethodInvoker(delegate { longCheckBox.Checked = false; }));
                                    this.Invoke(new MethodInvoker(delegate { shortCheckBox.Checked = true; }));
                                }
                            }
                        }
                    }
                }
                else
                {
                    // If table is not loaded, use createRefreshTableRequest method
                    O2GRequestFactory requestFactory = mSession.getRequestFactory();
                    if (requestFactory != null)
                    {
                        O2GRequest request = requestFactory.createRefreshTableRequest(O2GTableType.Accounts);
                        mSession.sendRequest(request);
                        Thread.Sleep(1000);
                    }
                }
            }
            catch (Exception acctErr)
            {
                Console.WriteLine(acctErr);
            }

            // Check if all 20 pairs needed are subscribed to on the account.
            try
            {
                O2GLoginRules loginRules = mSession.getLoginRules();

                if (loginRules != null && loginRules.isTableLoadedByDefault(O2GTableType.Offers))
                {
                    O2GResponse offersResponse = loginRules.getTableRefreshResponse(O2GTableType.Offers);
                    O2GResponseReaderFactory responseFactory = mSession.getResponseReaderFactory();
                    if (responseFactory != null)
                    {
                        O2GOffersTableResponseReader offersReader = responseFactory.createOffersTableReader(offersResponse);

                        for (int i = 0; i < offersReader.Count; i++)
                        {
                            O2GOfferRow offers = offersReader.getRow(i);

                            string checkOffer = offers.OfferID;
                        }
                    }
                }
            }
            catch (Exception mmrErr)
            {
                Console.WriteLine(mmrErr);
            }

            Console.WriteLine("Initializing needed table events.");
            // Initiate Table Getters
            O2GOffersTable offersTable = (O2GOffersTable)tableManager.getTable(O2GTableType.Offers);

            accountsTable = (O2GAccountsTable)tableManager.getTable(O2GTableType.Accounts);
            O2GSummaryTable      summaryTable = (O2GSummaryTable)tableManager.getTable(O2GTableType.Summary);
            O2GClosedTradesTable closedTable  = (O2GClosedTradesTable)tableManager.getTable(O2GTableType.ClosedTrades);

            // Trigger Table Events for Subscription
            offersTable.RowChanged   += new EventHandler <RowEventArgs>(offersTable_RowChanged);
            accountsTable.RowChanged += new EventHandler <RowEventArgs>(accountsTable_RowChanged);
            summaryTable.RowChanged  += new EventHandler <RowEventArgs>(summaryTable_RowChanged);
            closedTable.RowChanged   += new EventHandler <RowEventArgs>(closedTable_RowChanged);

            // Check pair subscription status, and add if needed.

            this.Invoke(new MethodInvoker(delegate { actiBox.AppendText("Connection Established.... Monitoring Pairs..." + Environment.NewLine); }));
            pastTimer.Start();
        }
Exemplo n.º 21
0
        // **AFTER LOG IN**
        // Background worker for table listeners
        private void priceBW_DoWork(object sender, DoWorkEventArgs e)
        {
            Console.WriteLine("Entered BW");
            // Enable timers.
            pastTimer.Enabled = true;
            pastTimer.Start();
            oneSecTimer.Enabled = true;
            oneSecTimer.Start();

            mSession.useTableManager(O2GTableManagerMode.Yes, null);

            tableManager  = mSession.getTableManager();
            managerStatus = tableManager.getStatus();

            while (managerStatus == O2GTableManagerStatus.TablesLoading)
            {
                Console.WriteLine("Tables are loading...");
                Thread.Sleep(50);
                managerStatus = tableManager.getStatus();
            }
            if (managerStatus == O2GTableManagerStatus.TablesLoadFailed)
            {
                Console.WriteLine("Tabled loading failed");
                this.Invoke(new MethodInvoker(delegate { actiBox.AppendText("WARNING: LOADING TABLES FAILED!" + Environment.NewLine); }));
                return;
            }
            // Check Accounts Table and Grab Information
            try
            {
                O2GLoginRules loginRules = mSession.getLoginRules();
                Console.WriteLine("Tables are loaded!");
                // Check if Accounts table is loaded automatically
                if (loginRules != null && loginRules.isTableLoadedByDefault(O2GTableType.Accounts))
                {
                    Console.WriteLine("Login rules != null");
                    // If table is loaded, use getTableRefreshResponse method
                    O2GResponse accountsResponse             = loginRules.getTableRefreshResponse(O2GTableType.Accounts);
                    O2GResponseReaderFactory responseFactory = mSession.getResponseReaderFactory();
                    if (responseFactory != null)
                    {
                        Console.WriteLine("Grabbing account data....");
                        O2GAccountsTableResponseReader accountsReader = responseFactory.createAccountsTableReader(accountsResponse);

                        for (int i = 0; i < accountsReader.Count; i++)
                        {
                            account      = accountsReader.getRow(i);
                            accountValue = account.Balance;
                            this.Invoke(new MethodInvoker(delegate { accountValueBox.Text = "$" + Convert.ToString(accountValue); }));
                            availLev = account.Balance;
                            this.Invoke(new MethodInvoker(delegate { accountLevBox.Text = "$" + Convert.ToString(availLev); }));
                            sAccountID  = account.AccountID.ToString();
                            amountLimit = account.AmountLimit;
                            baseSize    = account.BaseUnitSize;
                        }
                    }
                }
                else
                {
                    // If table is not loaded, use createRefreshTableRequest method
                    O2GRequestFactory requestFactory = mSession.getRequestFactory();
                    if (requestFactory != null)
                    {
                        O2GRequest request = requestFactory.createRefreshTableRequest(O2GTableType.Accounts);
                        mSession.sendRequest(request);
                        Thread.Sleep(1000);
                    }
                }
            }
            catch (Exception acctErr)
            {
                Console.WriteLine(acctErr);
            }

            // Check if all 20 pairs needed are subscribed to on the account.
            try
            {
                O2GLoginRules loginRules = mSession.getLoginRules();

                if (loginRules != null && loginRules.isTableLoadedByDefault(O2GTableType.Offers))
                {
                    O2GResponse offersResponse = loginRules.getTableRefreshResponse(O2GTableType.Offers);
                    O2GResponseReaderFactory responseFactory = mSession.getResponseReaderFactory();
                    if (responseFactory != null)
                    {
                        Console.WriteLine("Triggering offers row");
                        O2GOffersTableResponseReader offersReader = responseFactory.createOffersTableReader(offersResponse);

                        for (int i = 0; i < offersReader.Count; i++)
                        {
                            O2GOfferRow offers = offersReader.getRow(i);

                            string checkOffer = offers.OfferID;
                        }
                    }
                }
                // Get MMR prices and set position initial cost
                Console.WriteLine("Grabbing MMR");
                this.Invoke(new MethodInvoker(delegate { actiBox.AppendText("Retrieving Pair MMR..." + Environment.NewLine); }));
                O2GTradingSettingsProvider settingResponse = loginRules.getTradingSettingsProvider();
                audcadMMR     = settingResponse.getMMR("AUD/CAD", account);
                audcadInitial = shortLot * audcadMMR;
                audjpyMMR     = settingResponse.getMMR("AUD/JPY", account);
                audjpyInitial = shortLot * audjpyMMR;
                audusdMMR     = settingResponse.getMMR("AUD/USD", account);
                audusdInitial = shortLot * audusdMMR;
                cadjpyMMR     = settingResponse.getMMR("CAD/JPY", account);
                cadjpyInitial = shortLot * cadjpyMMR;
                chfjpyMMR     = settingResponse.getMMR("CHF/JPY", account);
                chfjpyInitial = shortLot * chfjpyMMR;
                euraudMMR     = settingResponse.getMMR("EUR/AUD", account);
                euraudInitial = shortLot * euraudMMR;
                eurcadMMR     = settingResponse.getMMR("EUR/CAD", account);
                eurcadInitial = shortLot * eurcadMMR;
                eurchfMMR     = settingResponse.getMMR("EUR/CHF", account);
                eurchfInitial = shortLot * eurchfMMR;
                eurjpyMMR     = settingResponse.getMMR("EUR/JPY", account);
                eurjpyInitial = shortLot * eurjpyMMR;
                eurusdMMR     = settingResponse.getMMR("EUR/USD", account);
                eurusdInitial = shortLot * eurusdMMR;
                gbpaudMMR     = settingResponse.getMMR("GBP/AUD", account);
                gbpaudInitial = shortLot * gbpaudMMR;
                gbpchfMMR     = settingResponse.getMMR("GBP/CHF", account);
                gbpchfInitial = shortLot * gbpchfMMR;
                gbpjpyMMR     = settingResponse.getMMR("GBP/JPY", account);
                gbpjpyInitial = shortLot * gbpjpyMMR;
                gbpnzdMMR     = settingResponse.getMMR("GBP/NZD", account);
                gbpnzdInitial = shortLot * gbpnzdMMR;
                gbpusdMMR     = settingResponse.getMMR("GBP/USD", account);
                gbpusdInitial = shortLot * gbpusdMMR;
                nzdjpyMMR     = settingResponse.getMMR("NZD/JPY", account);
                nzdjpyInitial = shortLot * nzdjpyMMR;
                nzdusdMMR     = settingResponse.getMMR("NZD/USD", account);
                nzdusdInitial = shortLot * nzdusdMMR;
                usdcadMMR     = settingResponse.getMMR("USD/CAD", account);
                usdcadInitial = shortLot * usdcadMMR;
                usdchfMMR     = settingResponse.getMMR("USD/CHF", account);
                usdchfInitial = shortLot * usdchfMMR;
                usdjpyMMR     = settingResponse.getMMR("USD/JPY", account);
                usdjpyInitial = shortLot * usdjpyMMR;

                // Set highest move to 0
                highestMove = 0;

                // Set all move values to 0;
            }
            catch (Exception mmrErr)
            {
                Console.WriteLine(mmrErr);
            }

            Console.WriteLine("Initializing needed table events.");
            // Initiate Table Getters
            O2GOffersTable offersTable = (O2GOffersTable)tableManager.getTable(O2GTableType.Offers);

            accountsTable = (O2GAccountsTable)tableManager.getTable(O2GTableType.Accounts);
            O2GTradesTable tradesTable = (O2GTradesTable)tableManager.getTable(O2GTableType.Trades);

            //O2GOrdersTable ordersTable = (O2GOrdersTable)tableManager.getTable(O2GTableType.Orders);
            //O2GClosedTradesTable closedTradesTable = (O2GClosedTradesTable)tableManager.getTable(O2GTableType.ClosedTrades);
            //O2GMessagesTable messagesTable = (O2GMessagesTable)tableManager.getTable(O2GTableType.Messages);
            //O2GSummaryTable summaryTable = (O2GSummaryTable)tableManager.getTable(O2GTableType.Summary);


            // Trigger Table Events for Subscription
            offersTable.RowChanged   += new EventHandler <RowEventArgs>(offersTable_RowChanged);
            accountsTable.RowChanged += new EventHandler <RowEventArgs>(accountsTable_RowChanged);
            tradesTable.RowChanged   += new EventHandler <RowEventArgs>(tradesTable_RowChanged);
            //ordersTable.RowChanged += new EventHandler<RowEventArgs>(ordersTable_RowChanged);
            //closedTradesTable.RowChanged += new EventHandler<RowEventArgs>(closedTradesTable_RowChanged);
            //messagesTable.RowChanged += new EventHandler<RowEventArgs>(messagesTable_RowChanged);
            //summaryTable.RowChanged += new EventHandler<RowEventArgs>(summaryTable_RowChanged);

            // Check pair subscription status, and add if needed.

            this.Invoke(new MethodInvoker(delegate { actiBox.AppendText("Connection Established.... Monitoring Pairs..." + Environment.NewLine); }));
            // Start Past Price Timer
            pastTimer.Start();
        }
        public void onTablesUpdates(O2GResponse data)
        {
            O2GResponseReaderFactory factory = mSession.getResponseReaderFactory();

            if (factory != null)
            {
                O2GTablesUpdatesReader reader = factory.createTablesUpdatesReader(data);
                for (int ii = 0; ii < reader.Count; ii++)
                {
                    switch (reader.getUpdateTable(ii))
                    {
                    case O2GTableType.Accounts:
                        O2GAccountRow account = reader.getAccountRow(ii);
                        //Show balance updates
                        Console.WriteLine("Balance: {0}", account.Balance);
                        break;

                    case O2GTableType.Orders:
                        O2GOrderRow order = reader.getOrderRow(ii);
                        switch (reader.getUpdateType(ii))
                        {
                        case O2GTableUpdateType.Insert:
                            if (mBatchOrderMonitor != null)
                            {
                                Console.WriteLine("The order has been added. Order ID: {0}, Rate: {1}, Time In Force: {2}",
                                                  order.OrderID,
                                                  order.Rate,
                                                  order.TimeInForce);
                                mBatchOrderMonitor.OnOrderAdded(order);
                            }
                            break;

                        case O2GTableUpdateType.Delete:
                            if (mBatchOrderMonitor != null)
                            {
                                Console.WriteLine("The order has been deleted. Order ID: {0}", order.OrderID);
                                mBatchOrderMonitor.OnOrderDeleted(order);
                                if (mBatchOrderMonitor.IsBatchExecuted())
                                {
                                    PrintResult();
                                    mSyncResponseEvent.Set();
                                }
                            }
                            break;
                        }
                        break;

                    case O2GTableType.Trades:
                        O2GTradeRow trade = reader.getTradeRow(ii);
                        if (reader.getUpdateType(ii) == O2GTableUpdateType.Insert)
                        {
                            if (mBatchOrderMonitor != null)
                            {
                                mBatchOrderMonitor.OnTradeAdded(trade);
                                if (mBatchOrderMonitor.IsBatchExecuted())
                                {
                                    PrintResult();
                                    mSyncResponseEvent.Set();
                                }
                            }
                        }
                        break;

                    case O2GTableType.ClosedTrades:
                        O2GClosedTradeRow closedTrade = reader.getClosedTradeRow(ii);
                        if (reader.getUpdateType(ii) == O2GTableUpdateType.Insert)
                        {
                            if (mBatchOrderMonitor != null)
                            {
                                mBatchOrderMonitor.OnClosedTradeAdded(closedTrade);
                                if (mBatchOrderMonitor.IsBatchExecuted())
                                {
                                    PrintResult();
                                    mSyncResponseEvent.Set();
                                }
                            }
                        }
                        break;

                    case O2GTableType.Messages:
                        O2GMessageRow message = reader.getMessageRow(ii);
                        if (reader.getUpdateType(ii) == O2GTableUpdateType.Insert)
                        {
                            if (mBatchOrderMonitor != null)
                            {
                                mBatchOrderMonitor.OnMessageAdded(message);
                                if (mBatchOrderMonitor.IsBatchExecuted())
                                {
                                    PrintResult();
                                    mSyncResponseEvent.Set();
                                }
                            }
                        }
                        break;
                    }
                }
            }
        }
Exemplo n.º 23
0
        public void onTablesUpdates(O2GResponse data)
        {
            O2GResponseReaderFactory factory = mSession.getResponseReaderFactory();

            if (factory != null)
            {
                O2GTablesUpdatesReader reader = factory.createTablesUpdatesReader(data);
                for (int ii = 0; ii < reader.Count; ii++)
                {
                    switch (reader.getUpdateTable(ii))
                    {
                    case O2GTableType.Accounts:
                        O2GAccountRow account = reader.getAccountRow(ii);
                        //Show balance updates
                        Console.WriteLine("Balance: {0}", account.Balance);
                        break;

                    case O2GTableType.Orders:
                        O2GOrderRow order = reader.getOrderRow(ii);
                        switch (reader.getUpdateType(ii))
                        {
                        case O2GTableUpdateType.Insert:
                            if ((OrderMonitorNetting.IsClosingOrder(order) || OrderMonitorNetting.IsOpeningOrder(order)) &&
                                mOrderMonitor == null)
                            {
                                Console.WriteLine("The order has been added. Order ID: {0}, Rate: {1}, Time In Force: {2}",
                                                  order.OrderID,
                                                  order.Rate,
                                                  order.TimeInForce);
                                O2GTradeRow tradeRow = null;
                                string      sTradeID = order.TradeID;
                                if (mTradesTable != null)
                                {
                                    for (int j = 0; j < mTradesTable.Count; j++)
                                    {
                                        if (sTradeID.Equals(mTradesTable.getRow(j).TradeID))
                                        {
                                            tradeRow = mTradesTable.getRow(j);
                                            break;
                                        }
                                    }
                                }
                                if (tradeRow == null)
                                {
                                    mOrderMonitor = new OrderMonitorNetting(order);
                                }
                                else
                                {
                                    mOrderMonitor = new OrderMonitorNetting(order, tradeRow.Amount);
                                }
                            }
                            break;

                        case O2GTableUpdateType.Delete:
                            if (mOrderMonitor != null)
                            {
                                Console.WriteLine("The order has been deleted. Order ID: {0}", order.OrderID);
                                mOrderMonitor.OnOrderDeleted(order);
                                if (mOrderMonitor.IsOrderCompleted)
                                {
                                    PrintResult();
                                    mSyncResponseEvent.Set();
                                }
                            }
                            break;
                        }
                        break;

                    case O2GTableType.Trades:
                        O2GTradeRow trade = reader.getTradeRow(ii);
                        switch (reader.getUpdateType(ii))
                        {
                        case O2GTableUpdateType.Insert:
                            if (mOrderMonitor != null)
                            {
                                mOrderMonitor.OnTradeAdded(trade);
                                if (mOrderMonitor.IsOrderCompleted)
                                {
                                    PrintResult();
                                    mSyncResponseEvent.Set();
                                }
                            }
                            break;

                        case O2GTableUpdateType.Update:
                            if (mOrderMonitor != null)
                            {
                                mOrderMonitor.OnTradeUpdated(trade);
                                if (mOrderMonitor.IsOrderCompleted)
                                {
                                    PrintResult();
                                    mSyncResponseEvent.Set();
                                }
                            }
                            break;
                        }
                        break;

                    case O2GTableType.ClosedTrades:
                        O2GClosedTradeRow closedTrade = reader.getClosedTradeRow(ii);
                        if (reader.getUpdateType(ii) == O2GTableUpdateType.Insert)
                        {
                            if (mOrderMonitor != null)
                            {
                                mOrderMonitor.OnClosedTradeAdded(closedTrade);
                                if (mOrderMonitor.IsOrderCompleted)
                                {
                                    PrintResult();
                                    mSyncResponseEvent.Set();
                                }
                            }
                        }
                        break;

                    case O2GTableType.Messages:
                        O2GMessageRow message = reader.getMessageRow(ii);
                        if (reader.getUpdateType(ii) == O2GTableUpdateType.Insert)
                        {
                            if (mOrderMonitor != null)
                            {
                                mOrderMonitor.OnMessageAdded(message);
                                if (mOrderMonitor.IsOrderCompleted)
                                {
                                    PrintResult();
                                    mSyncResponseEvent.Set();
                                }
                            }
                        }
                        break;
                    }
                }
            }
        }
        public void onTablesUpdates(O2GResponse response)
        {
            O2GResponseReaderFactory factory = mSession.getResponseReaderFactory();

            if (factory != null)
            {
                O2GTablesUpdatesReader reader = factory.createTablesUpdatesReader(response);
                for (int ii = 0; ii < reader.Count; ii++)
                {
                    switch (reader.getUpdateTable(ii))
                    {
                    case O2GTableType.Accounts:
                        O2GAccountRow account = reader.getAccountRow(ii);
                        // Show balance updates
                        Console.WriteLine("Balance: {0}", account.Balance);
                        break;

                    case O2GTableType.Orders:
                        O2GOrderRow order = reader.getOrderRow(ii);
                        switch (reader.getUpdateType(ii))
                        {
                        case O2GTableUpdateType.Insert:
                            if (mRequestID.Equals(order.RequestID))
                            {
                                mOrderID = order.OrderID;
                                printOrder("New order is added", order);
                            }
                            break;

                        case O2GTableUpdateType.Update:
                            printOrder("An order is changed", order);
                            break;

                        case O2GTableUpdateType.Delete:
                            if (mRequestID.Equals(order.RequestID))
                            {
                                string sStatus = order.Status;
                                if (sStatus.Equals("R"))
                                {
                                    printOrder("An order has been rejected", order);
                                }
                                else
                                {
                                    printOrder("An order is going to be removed", order);
                                }
                                mSyncResponseEvent.Set();
                            }
                            break;
                        }
                        break;

                    case O2GTableType.Trades:
                        O2GTradeRow trade = reader.getTradeRow(ii);
                        if (reader.getUpdateType(ii) == O2GTableUpdateType.Insert)
                        {
                            Console.WriteLine("Position is opened: TradeID='{0}', TradeIDOrigin='{1}'",
                                              trade.TradeID, trade.TradeIDOrigin);
                        }
                        break;

                    case O2GTableType.ClosedTrades:
                        O2GClosedTradeRow closedTrade = reader.getClosedTradeRow(ii);
                        if (reader.getUpdateType(ii) == O2GTableUpdateType.Insert)
                        {
                            Console.WriteLine("Position is closed: TradeID='{0}'",
                                              closedTrade.TradeID);
                        }
                        break;

                    case O2GTableType.Messages:
                        O2GMessageRow message = reader.getMessageRow(ii);
                        if (reader.getUpdateType(ii) == O2GTableUpdateType.Insert)
                        {
                            string text    = message.Text;
                            int    findPos = text.IndexOf(mOrderID);
                            if (findPos >= 0)
                            {
                                Console.WriteLine("Feature='{0}', Message='{1}'",
                                                  message.Feature, text);
                            }
                        }
                        break;
                    }
                }
            }
        }
 void IO2GResponseListener.onTablesUpdates(O2GResponse response)
 {
     if (response.Type == O2GResponseType.GetOffers || response.Type == O2GResponseType.TablesUpdates)
     {
         O2GResponseReaderFactory factory = mSession.getResponseReaderFactory();
         if (factory != null)
         {
             O2GOffersTableResponseReader reader = factory.createOffersTableReader(response);
             for (int i = 0; i < reader.Count; i++)
             {
                 O2GOfferRow row   = reader.getRow(i);
                 Offer       offer = null;
                 mOffers.TryGetValue(row.OfferID, out offer);
                 if (offer == null)
                 {
                     if (row.isInstrumentValid && row.isTimeValid && row.isBidValid && row.isAskValid &&
                         row.isVolumeValid && row.isDigitsValid && row.isPointSizeValid)
                     {
                         //mTimeConverter.convert(row.Time, O2GTimeConverterTimeZone.UTC, mTimezone)
                         //DateTime dt = mTimeConverter.convert(row.Time, O2GTimeConverterTimeZone.Server, O2GTimeConverterTimeZone.UTC);
                         DateTime dt = row.Time;
                         offer = new Offer(row.Instrument, dt, row.Bid, row.Ask, row.Volume, row.Digits, row.PointSize);
                         mOffers[row.OfferID] = offer;
                         mOffersList.Add(offer);
                         SendTick(offer);
                     }
                 }
                 else
                 {
                     if (row.isTimeValid)
                     {
                         //mTimeConverter.convert(row.Time, O2GTimeConverterTimeZone.UTC, mTimezone)
                         //DateTime dt = mTimeConverter.convert(row.Time, O2GTimeConverterTimeZone.Server, O2GTimeConverterTimeZone.UTC);
                         DateTime dt = row.Time;
                         offer.Time = dt;
                     }
                     if (row.isBidValid)
                     {
                         offer.Bid = row.Bid;
                     }
                     if (row.isAskValid)
                     {
                         offer.Ask = row.Ask;
                     }
                     if (row.isVolumeValid)
                     {
                         offer.Volume = row.Volume;
                     }
                     if (row.isPointSizeValid)
                     {
                         offer.PointSize = row.PointSize;
                     }
                     if (row.isDigitsValid)
                     {
                         offer.Precision = row.Digits;
                     }
                     SendTick(offer);
                 }
             }
         }
     }
 }