Пример #1
0
        public void EnsureRequestPreparation()
        {
            var entry = new Entry
            {
                Request = new Request
                {
                    Method = "POST",
                    Url = "http://posttestserver.com/post.php?dump&a={a}",
                    QueryString = new QueryString
                                {
                                    new NameValuePair
                                        {
                                            Name = "a",
                                            Value = "avalue"
                                        }
                                },
                    PostData = new PostData
                    {
                        Params = new Parameters
                                        {
                                            // naked
                                            new NameValuePair {Name = string.Empty, Value = "fooo"},
                                            //named
                                            new NameValuePair {Name = "param", Value = "paramValue"}
                                        }
                    }
                }
            };

            Helper.PrepareEntryRequest(entry);
            Assert.AreEqual("http://posttestserver.com/post.php?dump&a=avalue", entry.Request.Url);
            Assert.AreEqual("fooo&param=paramValue", entry.Request.PostData.Text);
        }
Пример #2
0
        public Task<AccountInformationResponseDTO> GetClientAndTradingAccountAsync()
        {
            var entry = new Entry
            {
                Request = new Request
                {
                    Method = "GET",
                    Url = ApiBaseUrl + "/useraccount/ClientAndTradingAccount"

                }
            };


            Task<Entry> getResponseTextTask = EnqueueRequestAsync(entry);

            Task<AccountInformationResponseDTO> deserializeTask =
                getResponseTextTask.ContinueWith(task =>
                {
                    var accountInformation =
                        JsonConvert.DeserializeObject<AccountInformationResponseDTO>(task.Result.Response.Content.Text);
                    AccountInformation = accountInformation;
                    return accountInformation;
                });

            return deserializeTask.ContinueWith(task => task.Result);
        }
Пример #3
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="entry"></param>
        /// <returns></returns>
        public override Task<Entry> EnqueueRequestAsync(Entry entry)
        {

            if (entry.Request.Headers == null)
            {
                entry.Request.Headers = new Headers();
            }

            if (!string.IsNullOrEmpty(Username))
            {

                entry.Request.Headers.Add(new NameValuePair("UserName", Username));
            }

            if (!string.IsNullOrEmpty(SessionId))
            {
                entry.Request.Headers.Add(new NameValuePair("Session", SessionId));
            }

            return base.EnqueueRequestAsync(entry);

             
        }
Пример #4
0
        // ***********************************
        // GetNewsDetail
        // ***********************************


        /// <summary>
        /// Get the detail of the specific news story matching the story ID in the parameter.
        /// </summary>
        /// <param name="source">The news feed source provider. Valid options are **dj**|**mni**|**ci**.</param>
        /// <param name="storyId">The news story ID.</param>
        public virtual Task<GetNewsDetailResponseDTO> GetNewsDetailAsync(string source, string storyId)
        {
            var entry = new Entry
            {
                Request = new Request
                {
                    Method = "GET",
                    Url = _client.ApiBaseUrl + "/news/{source}/{storyId}",
                    QueryString = new QueryString(new NameValuePair("source", source), new NameValuePair("storyId", storyId))
                }
            };


            Task<Entry> getResponseTextTask = _client.EnqueueRequestAsync(entry);

            Task<GetNewsDetailResponseDTO> deserializeTask =
                getResponseTextTask.ContinueWith(task =>
                {
                    var data =
                        JsonConvert.DeserializeObject<GetNewsDetailResponseDTO>(task.Result.Response.Content.Text);
                    return data;
                });

            return deserializeTask.ContinueWith(task => task.Result);
        }
Пример #5
0
        // ***********************************
        // ListSpreadMarkets
        // ***********************************


        /// <summary>
        /// Returns a list of Spread Betting markets filtered by market name and/or market code. Leave the market name and code parameters empty to return all markets available to the User.
        /// </summary>
        /// <param name="searchByMarketName">The characters that the Spread market name starts with. *(Optional)*.</param>
        /// <param name="searchByMarketCode">The characters that the Spread market code starts with, normally this is the RIC code for the market. *(Optional)*.</param>
        /// <param name="ClientAccountId">The logged on user's ClientAccountId. *(This only shows you markets that you can trade on.)*</param>
        /// <param name="maxResults">The maximum number of markets to return.</param>
        /// <param name="useMobileShortName">True if the market name should be in short form. Helpful when displaying data on a small screen.</param>
        public virtual Task<ListSpreadMarketsResponseDTO> ListSpreadMarketsAsync(string searchByMarketName, string searchByMarketCode, int ClientAccountId, int maxResults, bool useMobileShortName)
        {
            var entry = new Entry
            {
                Request = new Request
                {
                    Method = "GET",
                    Url = _client.ApiBaseUrl + "/spread/markets?MarketName={searchByMarketName}&MarketCode={searchByMarketCode}&ClientAccountId={ClientAccountId}&MaxResults={maxResults}&UseMobileShortName={useMobileShortName}",
                    QueryString = new QueryString(new NameValuePair("searchByMarketName", searchByMarketName), new NameValuePair("searchByMarketCode", searchByMarketCode), new NameValuePair("ClientAccountId", ClientAccountId), new NameValuePair("maxResults", maxResults), new NameValuePair("useMobileShortName", useMobileShortName))
                }
            };


            Task<Entry> getResponseTextTask = _client.EnqueueRequestAsync(entry);

            Task<ListSpreadMarketsResponseDTO> deserializeTask =
                getResponseTextTask.ContinueWith(task =>
                {
                    var data =
                        JsonConvert.DeserializeObject<ListSpreadMarketsResponseDTO>(task.Result.Response.Content.Text);
                    return data;
                });

            return deserializeTask.ContinueWith(task => task.Result);
        }
Пример #6
0
        // ***********************************
        // ListStopLimitOrderHistory
        // ***********************************


        /// <summary>
        /// Queries for a specified trading account's stop / limit order history. The result set includes __only orders that were originally stop / limit orders__ that currently have one of the following statuses __(3 - Open, 4 - Cancelled, 5 - Rejected, 9 - Closed, 10 - Red Card)__.  There is currently no corresponding GetStopLimitOrderHistory *(as with [ListActiveStopLimitOrders](http://labs.cityindex.com/docs/Content/HTTP%20Services/ListActiveStopLimitOrders.htm))*. **Notes on Parameters** >**ClientAccountId** - this can be passed in order to retrieve all information on all trading accounts for which it is the parent. >**TradingAccountId** - this can be passed to retrieve information specific to a certain trading account *(the child of ClientAccount)*.  If *neither* ClientAccountId nor TradingAccountId is passed, then the information returned by default from the API is ClientAccount.
        /// </summary>
        /// <param name="TradingAccountId">The ID of the trading account to get orders for.</param>
        /// <param name="maxResults">The maximum number of results to return.</param>
        public virtual Task<ListStopLimitOrderHistoryResponseDTO> ListStopLimitOrderHistoryAsync(int TradingAccountId, int maxResults)
        {
            var entry = new Entry
            {
                Request = new Request
                {
                    Method = "GET",
                    Url = _client.ApiBaseUrl + "/order/stoplimitorderhistory?TradingAccountId={TradingAccountId}&MaxResults={maxResults}",
                    QueryString = new QueryString(new NameValuePair("TradingAccountId", TradingAccountId), new NameValuePair("maxResults", maxResults))
                }
            };


            Task<Entry> getResponseTextTask = _client.EnqueueRequestAsync(entry);

            Task<ListStopLimitOrderHistoryResponseDTO> deserializeTask =
                getResponseTextTask.ContinueWith(task =>
                {
                    var data =
                        JsonConvert.DeserializeObject<ListStopLimitOrderHistoryResponseDTO>(task.Result.Response.Content.Text);
                    return data;
                });

            return deserializeTask.ContinueWith(task => task.Result);
        }
Пример #7
0
        // ***********************************
        // ListNewsHeadlines
        // ***********************************


        /// <summary>
        /// Get a list of current news headlines.
        /// </summary>
        /// <param name="request">Object specifying the various request parameters.</param>
        public virtual Task<ListNewsHeadlinesResponseDTO> ListNewsHeadlinesAsync(ListNewsHeadlinesRequestDTO request)
        {
            var entry = new Entry
            {
                Request = new Request
                {
                    Method = "POST",
                    Url = _client.ApiBaseUrl + "/news/headlines",
                    PostData = new PostData{
                       MimeType = "application/json",
                       Params = new Parameters(new NameValuePair("", request))
                    }
                }
            };


            Task<Entry> getResponseTextTask = _client.EnqueueRequestAsync(entry);

            Task<ListNewsHeadlinesResponseDTO> deserializeTask =
                getResponseTextTask.ContinueWith(task =>
                {
                    var data =
                        JsonConvert.DeserializeObject<ListNewsHeadlinesResponseDTO>(task.Result.Response.Content.Text);
                    return data;
                });

            return deserializeTask.ContinueWith(task => task.Result);
        }
Пример #8
0
        // ***********************************
        // Get
        // ***********************************


        /// <summary>
        /// Get client preferences.
        /// </summary>
        /// <param name="clientPreferenceRequestDto">The client preference key to get.</param>
        public virtual Task<GetClientPreferenceResponseDTO> GetAsync(ClientPreferenceRequestDTO clientPreferenceRequestDto)
        {
            var entry = new Entry
            {
                Request = new Request
                {
                    Method = "POST",
                    Url = _client.ApiBaseUrl + "/clientpreference/get",
                    PostData = new PostData{
                       MimeType = "application/json",
                       Params = new Parameters(new NameValuePair("", clientPreferenceRequestDto))
                    }
                }
            };


            Task<Entry> getResponseTextTask = _client.EnqueueRequestAsync(entry);

            Task<GetClientPreferenceResponseDTO> deserializeTask =
                getResponseTextTask.ContinueWith(task =>
                {
                    var data =
                        JsonConvert.DeserializeObject<GetClientPreferenceResponseDTO>(task.Result.Response.Content.Text);
                    return data;
                });

            return deserializeTask.ContinueWith(task => task.Result);
        }
Пример #9
0
        public void CanEnqueueRequestAsync()
        {
            var entry = new Entry
                {
                    Request = new Request
                        {
                            Method = "POST",
                            Url = "http://posttestserver.com/post.php?dump&a={a}",
                            QueryString = new QueryString
                                {
                                    new NameValuePair
                                        {
                                            Name = "a",
                                            Value = "avalue"
                                        }
                                },
                            PostData = new PostData
                                {
                                    MimeType = "text/plain",
                                    Params = new Parameters
                                        {
                                            // naked
                                            new NameValuePair {Name = string.Empty, Value = "fooo"},
                                            //named
                                            new NameValuePair {Name = "param", Value = "paramValue"}
                                        }
                                },
                            Headers = new Headers
                                {
                                    new NameValuePair
                                        {
                                            Name = "arbitrary-header",
                                            Value = "header value"
                                        }
                                }
                        }
                };


            var client = new Client("https://ciapi.cityindex.com/tradingapi", "ciapi.portable");

            Task<Entry> t = client.EnqueueRequestAsync(entry);

            // this will throw if exceptions occur in task
            t.Wait();



            Entry result = t.Result;

            Response response = result.Response;


            string responseText = response.Content.Text;

            Assert.AreEqual(response.Content.Size, responseText.Length);

            Assert.IsTrue(responseText.Contains("HTTP_ARBITRARY_HEADER = header value\n"));
            Assert.IsTrue(responseText.Contains("CONTENT_TYPE = text/plain\n"));
            Assert.IsTrue(responseText.Contains("QUERY_STRING = dump&a=avalue\n"));
            Assert.IsTrue(responseText.Contains("== Begin post body ==\nfooo&param=paramValue\n== End post body ==\n"));
            // 
        }
Пример #10
0
        // ***********************************
        // DeleteSession
        // ***********************************


        /// <summary>
        /// Delete a session. This is how you "log off" from the CIAPI.
        /// </summary>
        /// <param name="UserName">Username is case sensitive. May be set as a service parameter or as a request header.</param>
        /// <param name="Session">The session token. May be set as a service parameter or as a request header.</param>
        internal virtual Task<ApiLogOffResponseDTO> DeleteSessionAsync(string UserName, string Session)
        {
            var entry = new Entry
            {
                Request = new Request
                {
                    Method = "POST",
                    Url = _client.ApiBaseUrl + "/session/deleteSession?UserName={UserName}&session={session}",
                    PostData = new PostData{
                       MimeType = "application/json",
                       Params = new Parameters()
                    },
                    QueryString = new QueryString(new NameValuePair("UserName", UserName), new NameValuePair("Session", Session))
                }
            };


            Task<Entry> getResponseTextTask = _client.EnqueueRequestAsync(entry);

            Task<ApiLogOffResponseDTO> deserializeTask =
                getResponseTextTask.ContinueWith(task =>
                {
                    var data =
                        JsonConvert.DeserializeObject<ApiLogOffResponseDTO>(task.Result.Response.Content.Text);
                    return data;
                });

            return deserializeTask.ContinueWith(task => task.Result);
        }
Пример #11
0
        // ***********************************
        // TagLookup
        // ***********************************


        /// <summary>
        /// Gets all of the tags that the requesting user is allowed to see. Tags are returned in a primary / secondary hierarchy. There are no parameters in this call.
        /// </summary>
        public virtual Task<MarketInformationTagLookupResponseDTO> TagLookupAsync()
        {
            var entry = new Entry
            {
                Request = new Request
                {
                    Method = "GET",
                    Url = _client.ApiBaseUrl + "/market/taglookup"
                }
            };


            Task<Entry> getResponseTextTask = _client.EnqueueRequestAsync(entry);

            Task<MarketInformationTagLookupResponseDTO> deserializeTask =
                getResponseTextTask.ContinueWith(task =>
                {
                    var data =
                        JsonConvert.DeserializeObject<MarketInformationTagLookupResponseDTO>(task.Result.Response.Content.Text);
                    return data;
                });

            return deserializeTask.ContinueWith(task => task.Result);
        }
Пример #12
0
        // ***********************************
        // GetClientApplicationMessageTranslationWithInterestingItems
        // ***********************************


        /// <summary>
        /// Use the message translation service to get client specific translated textual strings for specific keys.
        /// </summary>
        /// <param name="apiClientApplicationMessageTranslationRequestDto">DTO of the required data for translation lookup.</param>
        public virtual Task<ApiClientApplicationMessageTranslationResponseDTO> GetClientApplicationMessageTranslationWithInterestingItemsAsync(ApiClientApplicationMessageTranslationRequestDTO apiClientApplicationMessageTranslationRequestDto)
        {
            var entry = new Entry
            {
                Request = new Request
                {
                    Method = "POST",
                    Url = _client.ApiBaseUrl + "/message/translationWithInterestingItems",
                    PostData = new PostData{
                       MimeType = "application/json",
                       Params = new Parameters(new NameValuePair("", apiClientApplicationMessageTranslationRequestDto))
                    }
                }
            };


            Task<Entry> getResponseTextTask = _client.EnqueueRequestAsync(entry);

            Task<ApiClientApplicationMessageTranslationResponseDTO> deserializeTask =
                getResponseTextTask.ContinueWith(task =>
                {
                    var data =
                        JsonConvert.DeserializeObject<ApiClientApplicationMessageTranslationResponseDTO>(task.Result.Response.Content.Text);
                    return data;
                });

            return deserializeTask.ContinueWith(task => task.Result);
        }
Пример #13
0
        // ***********************************
        // GetVersionInformation
        // ***********************************


        /// <summary>
        /// Gets version information for a specific client application and *(optionally)* account operator.
        /// </summary>
        /// <param name="AppKey">A string to uniquely identify the application.</param>
        /// <param name="AccountOperatorId">An optional parameter to identify the account operator string to uniquely identify the application.</param>
        public virtual Task<GetVersionInformationResponseDTO> GetVersionInformationAsync(string AppKey, int AccountOperatorId)
        {
            var entry = new Entry
            {
                Request = new Request
                {
                    Method = "GET",
                    Url = _client.ApiBaseUrl + "/clientapplication/versioninformation?AppKey={AppKey}&AccountOperatorId={AccountOperatorId}",
                    QueryString = new QueryString(new NameValuePair("AppKey", AppKey), new NameValuePair("AccountOperatorId", AccountOperatorId))
                }
            };


            Task<Entry> getResponseTextTask = _client.EnqueueRequestAsync(entry);

            Task<GetVersionInformationResponseDTO> deserializeTask =
                getResponseTextTask.ContinueWith(task =>
                {
                    var data =
                        JsonConvert.DeserializeObject<GetVersionInformationResponseDTO>(task.Result.Response.Content.Text);
                    return data;
                });

            return deserializeTask.ContinueWith(task => task.Result);
        }
Пример #14
0
        // ***********************************
        // GetClientApplicationMessageTranslation
        // ***********************************


        /// <summary>
        /// Use the message translation service to get client specific translated text strings.
        /// </summary>
        /// <param name="ClientApplicationId">Client application identifier. *(Optional)*</param>
        /// <param name="CultureId">Culture ID which corresponds to a culture code. *(Optional)*</param>
        /// <param name="AccountOperatorId">Account operator identifier. *(Optional)*</param>
        public virtual Task<ApiClientApplicationMessageTranslationResponseDTO> GetClientApplicationMessageTranslationAsync(int ClientApplicationId, int CultureId, int AccountOperatorId)
        {
            var entry = new Entry
            {
                Request = new Request
                {
                    Method = "GET",
                    Url = _client.ApiBaseUrl + "/message/translation?ClientApplicationId={ClientApplicationId}&CultureId={CultureId}&AccountOperatorId={AccountOperatorId}",
                    QueryString = new QueryString(new NameValuePair("ClientApplicationId", ClientApplicationId), new NameValuePair("CultureId", CultureId), new NameValuePair("AccountOperatorId", AccountOperatorId))
                }
            };


            Task<Entry> getResponseTextTask = _client.EnqueueRequestAsync(entry);

            Task<ApiClientApplicationMessageTranslationResponseDTO> deserializeTask =
                getResponseTextTask.ContinueWith(task =>
                {
                    var data =
                        JsonConvert.DeserializeObject<ApiClientApplicationMessageTranslationResponseDTO>(task.Result.Response.Content.Text);
                    return data;
                });

            return deserializeTask.ContinueWith(task => task.Result);
        }
Пример #15
0
        // ***********************************
        // GetSystemLookup
        // ***********************************


        /// <summary>
        /// Use the message lookup service to get localised text names for the various status codes &amp;amp; IDs returned by the API. For example, a query for **OrderStatusReason** will contain text names for all the possible values of **OrderStatusReason** in the [ApiOrderResponseDTO](http://labs.cityindex.com/docs/Content/Data%20Types/ApiOrderResponseDTO.htm). You should only request the list once per session *(for each entity you're interested in)*.
        /// </summary>
        /// <param name="LookupEntityName">The entity to lookup. For example: **OrderStatusReason**, **InstructionStatusReason**, **OrderApplicability**, **Currency**, **QuoteStatus**, **QuoteStatusReason** or **Culture**.</param>
        /// <param name="CultureId">The Culture ID used to override the translated text description. *(Optional)*.</param>
        public virtual Task<ApiLookupResponseDTO> GetSystemLookupAsync(string LookupEntityName, int CultureId)
        {
            var entry = new Entry
            {
                Request = new Request
                {
                    Method = "GET",
                    Url = _client.ApiBaseUrl + "/message/lookup?LookupEntityName={LookupEntityName}&CultureId={CultureId}",
                    QueryString = new QueryString(new NameValuePair("LookupEntityName", LookupEntityName), new NameValuePair("CultureId", CultureId))
                }
            };


            Task<Entry> getResponseTextTask = _client.EnqueueRequestAsync(entry);

            Task<ApiLookupResponseDTO> deserializeTask =
                getResponseTextTask.ContinueWith(task =>
                {
                    var data =
                        JsonConvert.DeserializeObject<ApiLookupResponseDTO>(task.Result.Response.Content.Text);
                    return data;
                });

            return deserializeTask.ContinueWith(task => task.Result);
        }
Пример #16
0
        // ***********************************
        // SimulateTrade
        // ***********************************


        /// <summary>
        /// API call that allows a simulated new trade to be placed.
        /// </summary>
        /// <param name="Trade">The simulated trade request.</param>
        public virtual Task<ApiSimulateTradeOrderResponseDTO> SimulateTradeAsync(NewTradeOrderRequestDTO Trade)
        {
            var entry = new Entry
            {
                Request = new Request
                {
                    Method = "POST",
                    Url = _client.ApiBaseUrl + "/order/simulate/newtradeorder",
                    PostData = new PostData{
                       MimeType = "application/json",
                       Params = new Parameters(new NameValuePair("", Trade))
                    }
                }
            };


            Task<Entry> getResponseTextTask = _client.EnqueueRequestAsync(entry);

            Task<ApiSimulateTradeOrderResponseDTO> deserializeTask =
                getResponseTextTask.ContinueWith(task =>
                {
                    var data =
                        JsonConvert.DeserializeObject<ApiSimulateTradeOrderResponseDTO>(task.Result.Response.Content.Text);
                    return data;
                });

            return deserializeTask.ContinueWith(task => task.Result);
        }
Пример #17
0
        // ***********************************
        // GetMarketInformation
        // ***********************************


        /// <summary>
        /// Get Market Information for the single specified market supplied in the parameter.
        /// </summary>
        /// <param name="MarketId">The market ID.</param>
        public virtual Task<GetMarketInformationResponseDTO> GetMarketInformationAsync(string MarketId)
        {
            var entry = new Entry
            {
                Request = new Request
                {
                    Method = "GET",
                    Url = _client.ApiBaseUrl + "/market/{MarketId}/information",
                    QueryString = new QueryString(new NameValuePair("MarketId", MarketId))
                }
            };


            Task<Entry> getResponseTextTask = _client.EnqueueRequestAsync(entry);

            Task<GetMarketInformationResponseDTO> deserializeTask =
                getResponseTextTask.ContinueWith(task =>
                {
                    var data =
                        JsonConvert.DeserializeObject<GetMarketInformationResponseDTO>(task.Result.Response.Content.Text);
                    return data;
                });

            return deserializeTask.ContinueWith(task => task.Result);
        }
Пример #18
0
        // ***********************************
        // ChangePassword
        // ***********************************


        /// <summary>
        /// Change a user's password.
        /// </summary>
        /// <param name="apiChangePasswordRequest">The change password request details.</param>
        public virtual Task<ApiChangePasswordResponseDTO> ChangePasswordAsync(ApiChangePasswordRequestDTO apiChangePasswordRequest)
        {
            var entry = new Entry
            {
                Request = new Request
                {
                    Method = "POST",
                    Url = _client.ApiBaseUrl + "/session/changePassword",
                    PostData = new PostData{
                       MimeType = "application/json",
                       Params = new Parameters(new NameValuePair("", apiChangePasswordRequest))
                    }
                }
            };


            Task<Entry> getResponseTextTask = _client.EnqueueRequestAsync(entry);

            Task<ApiChangePasswordResponseDTO> deserializeTask =
                getResponseTextTask.ContinueWith(task =>
                {
                    var data =
                        JsonConvert.DeserializeObject<ApiChangePasswordResponseDTO>(task.Result.Response.Content.Text);
                    return data;
                });

            return deserializeTask.ContinueWith(task => task.Result);
        }
Пример #19
0
        // ***********************************
        // SearchWithTags
        // ***********************************


        /// <summary>
        /// Get market information and tags for the markets that meet the search criteria. Leave the query string empty to return all markets and tags available to the user.
        /// </summary>
        /// <param name="query">The text to search for. Matches part of market name / code from the start. *(Optional)*.</param>
        /// <param name="tagId">The ID for the tag to be searched. *(Optional)*.</param>
        /// <param name="searchByMarketCode">Sets the search to use market code.</param>
        /// <param name="searchByMarketName">Sets the search to use market Name.</param>
        /// <param name="spreadProductType">Sets the search to include spread bet markets.</param>
        /// <param name="cfdProductType">Sets the search to include CFD markets.</param>
        /// <param name="binaryProductType">Sets the search to include binary markets.</param>
        /// <param name="includeOptions">When set to true, the search captures and returns options markets. When set to false, options markets are excluded from the search results.</param>
        /// <param name="maxResults">The maximum number of results to return. Default is 20.</param>
        /// <param name="useMobileShortName">True if the market name should be in short form. Helpful when displaying data on a small screen.</param>
        public virtual Task<MarketInformationSearchWithTagsResponseDTO> SearchWithTagsAsync(string query, int tagId, bool searchByMarketCode, bool searchByMarketName, bool spreadProductType, bool cfdProductType, bool binaryProductType, bool includeOptions, int maxResults, bool useMobileShortName)
        {
            var entry = new Entry
            {
                Request = new Request
                {
                    Method = "GET",
                    Url = _client.ApiBaseUrl + "/market/searchwithtags?Query={query}&TagId={tagId}&SearchByMarketCode={searchByMarketCode}&SearchByMarketName={searchByMarketName}&SpreadProductType={spreadProductType}&CfdProductType={cfdProductType}&BinaryProductType={binaryProductType}&IncludeOptions={includeOptions}&MaxResults={maxResults}&UseMobileShortName={useMobileShortName}",
                    QueryString = new QueryString(new NameValuePair("query", query), new NameValuePair("tagId", tagId), new NameValuePair("searchByMarketCode", searchByMarketCode), new NameValuePair("searchByMarketName", searchByMarketName), new NameValuePair("spreadProductType", spreadProductType), new NameValuePair("cfdProductType", cfdProductType), new NameValuePair("binaryProductType", binaryProductType), new NameValuePair("includeOptions", includeOptions), new NameValuePair("maxResults", maxResults), new NameValuePair("useMobileShortName", useMobileShortName))
                }
            };


            Task<Entry> getResponseTextTask = _client.EnqueueRequestAsync(entry);

            Task<MarketInformationSearchWithTagsResponseDTO> deserializeTask =
                getResponseTextTask.ContinueWith(task =>
                {
                    var data =
                        JsonConvert.DeserializeObject<MarketInformationSearchWithTagsResponseDTO>(task.Result.Response.Content.Text);
                    return data;
                });

            return deserializeTask.ContinueWith(task => task.Result);
        }
Пример #20
0
        // ***********************************
        // GetPriceBars
        // ***********************************


        /// <summary>
        /// Get historic price bars for the specified market in OHLC *(open, high, low, close)* format, suitable for plotting in candlestick charts. Returns price bars in ascending order up to the current time. When there are no prices for a particular time period, no price bar is returned. Thus, it can appear that the array of price bars has "gaps", i.e. the gap between the date &amp;amp; time of each price bar might not be equal to interval x span.  Sample Urls: * /market/1234/history?interval=MINUTE&amp;amp;span=15&amp;amp;PriceBars=180 * /market/735/history?interval=HOUR&amp;amp;span=1&amp;amp;PriceBars=240 * /market/1577/history?interval=DAY&amp;amp;span=1&amp;amp;PriceBars=10
        /// </summary>
        /// <param name="MarketId">The ID of the market.</param>
        /// <param name="interval">The pricebar interval.</param>
        /// <param name="span">The number of each interval per pricebar.</param>
        /// <param name="PriceBars">The total number of price bars to return.</param>
        public virtual Task<GetPriceBarResponseDTO> GetPriceBarsAsync(string MarketId, string interval, int span, string PriceBars)
        {
            var entry = new Entry
            {
                Request = new Request
                {
                    Method = "GET",
                    Url = _client.ApiBaseUrl + "/market/{MarketId}/barhistory?interval={interval}&span={span}&PriceBars={PriceBars}",
                    QueryString = new QueryString(new NameValuePair("MarketId", MarketId), new NameValuePair("interval", interval), new NameValuePair("span", span), new NameValuePair("PriceBars", PriceBars))
                }
            };


            Task<Entry> getResponseTextTask = _client.EnqueueRequestAsync(entry);

            Task<GetPriceBarResponseDTO> deserializeTask =
                getResponseTextTask.ContinueWith(task =>
                {
                    var data =
                        JsonConvert.DeserializeObject<GetPriceBarResponseDTO>(task.Result.Response.Content.Text);
                    return data;
                });

            return deserializeTask.ContinueWith(task => task.Result);
        }
Пример #21
0
        // ***********************************
        // SaveMarketInformation
        // ***********************************


        /// <summary>
        /// Save Market Information for the specified list of markets.
        /// </summary>
        /// <param name="listMarketInformationRequestSaveDTO">Save Market Information for the specified list of markets.</param>
        public virtual Task<ApiSaveMarketInformationResponseDTO> SaveMarketInformationAsync(SaveMarketInformationRequestDTO listMarketInformationRequestSaveDTO)
        {
            var entry = new Entry
            {
                Request = new Request
                {
                    Method = "POST",
                    Url = _client.ApiBaseUrl + "/market/information/save",
                    PostData = new PostData{
                       MimeType = "application/json",
                       Params = new Parameters(new NameValuePair("", listMarketInformationRequestSaveDTO))
                    }
                }
            };


            Task<Entry> getResponseTextTask = _client.EnqueueRequestAsync(entry);

            Task<ApiSaveMarketInformationResponseDTO> deserializeTask =
                getResponseTextTask.ContinueWith(task =>
                {
                    var data =
                        JsonConvert.DeserializeObject<ApiSaveMarketInformationResponseDTO>(task.Result.Response.Content.Text);
                    return data;
                });

            return deserializeTask.ContinueWith(task => task.Result);
        }
Пример #22
0
        // ***********************************
        // ListOpenPositions
        // ***********************************


        /// <summary>
        /// Queries for a specified trading account's trades / open positions. This URI is intended to support a grid in a UI. One usage pattern is to subscribe to streaming orders, call this for the initial data to display in the grid, and call the HTTP service [GetOpenPosition](http://labs.cityindex.com/docs/Content/HTTP%20Services/GetOpenPosition.htm) when you get updates on the order stream to get the updated data in this format. **Notes on Parameters** >**ClientAccountId** - this can be passed in order to retrieve all information on all trading accounts for which it is the parent. >**TradingAccountId** - this can be passed to retrieve information specific to a certain trading account *(the child of ClientAccount)*.  If *neither* ClientAccountId nor TradingAccountId is passed, then the information returned by default from the API is ClientAccount.
        /// </summary>
        /// <param name="TradingAccountId">The ID of the trading account to get orders for.</param>
        public virtual Task<ListOpenPositionsResponseDTO> ListOpenPositionsAsync(int TradingAccountId)
        {
            var entry = new Entry
            {
                Request = new Request
                {
                    Method = "GET",
                    Url = _client.ApiBaseUrl + "/order/openpositions?TradingAccountId={TradingAccountId}",
                    QueryString = new QueryString(new NameValuePair("TradingAccountId", TradingAccountId))
                }
            };


            Task<Entry> getResponseTextTask = _client.EnqueueRequestAsync(entry);

            Task<ListOpenPositionsResponseDTO> deserializeTask =
                getResponseTextTask.ContinueWith(task =>
                {
                    var data =
                        JsonConvert.DeserializeObject<ListOpenPositionsResponseDTO>(task.Result.Response.Content.Text);
                    return data;
                });

            return deserializeTask.ContinueWith(task => task.Result);
        }
Пример #23
0
        // ***********************************
        // GetKeyList
        // ***********************************


        /// <summary>
        /// Get list of client preferences keys. There are no parameters in this call.
        /// </summary>
        public virtual Task<GetKeyListClientPreferenceResponseDTO> GetKeyListAsync()
        {
            var entry = new Entry
            {
                Request = new Request
                {
                    Method = "GET",
                    Url = _client.ApiBaseUrl + "/clientpreference/getkeylist"
                }
            };


            Task<Entry> getResponseTextTask = _client.EnqueueRequestAsync(entry);

            Task<GetKeyListClientPreferenceResponseDTO> deserializeTask =
                getResponseTextTask.ContinueWith(task =>
                {
                    var data =
                        JsonConvert.DeserializeObject<GetKeyListClientPreferenceResponseDTO>(task.Result.Response.Content.Text);
                    return data;
                });

            return deserializeTask.ContinueWith(task => task.Result);
        }
Пример #24
0
        private void IssueRequest(WebRequest r, Entry entry, TaskCompletionSource<Entry> taskCompletionSource)
        {
            r.BeginGetResponse(a =>
                {
                    try
                    {
                        WebResponse webResponse = r.EndGetResponse(a);

                        byte[] rtb;
                        using (Stream rs = webResponse.GetResponseStream())
                        {
                            rtb = Helper.ReadStreamFully(rs);
                        }
                        string rt = Encoding.UTF8.GetString(rtb, 0, rtb.Length);
                        var entryResponse = new Response
                            {
                                Content = new Content
                                    {
                                        MimeType = webResponse.ContentType,
                                        Size = (int)webResponse.ContentLength,
                                        Text = rt
                                    }
                            };

                        entry.Response = entryResponse;
                        taskCompletionSource.SetResult(entry);
                    }
                    catch (WebException exc)
                    {
                        // we could get an exception here
                        try
                        {
                            Stream rs = exc.Response.GetResponseStream();
                            byte[] rtb = Helper.ReadStreamFully(rs);
                            string rt = Encoding.UTF8.GetString(rtb, 0, rtb.Length);
                            var ape = new HttpWebException { ResponseText = rt };
                            taskCompletionSource.SetException(ape);
                        }
                        catch
                        {
                            // problem extracting web exception response. just send original exception
                            taskCompletionSource.SetException(exc);
                        }
                    }
                    catch (Exception exc)
                    {
                        taskCompletionSource.SetException(exc);
                    }
                }, null);
        }
Пример #25
0
        // ***********************************
        // GetPriceTicks
        // ***********************************


        /// <summary>
        /// Get historic price ticks for the specified market. Returns price ticks in ascending order up to the current time. The length of time that elapses between each tick is usually different.
        /// </summary>
        /// <param name="MarketId">The market ID.</param>
        /// <param name="PriceTicks">The total number of price ticks to return.</param>
        public virtual Task<GetPriceTickResponseDTO> GetPriceTicksAsync(string MarketId, string PriceTicks)
        {
            var entry = new Entry
            {
                Request = new Request
                {
                    Method = "GET",
                    Url = _client.ApiBaseUrl + "/market/{MarketId}/tickhistory?PriceTicks={PriceTicks}",
                    QueryString = new QueryString(new NameValuePair("MarketId", MarketId), new NameValuePair("PriceTicks", PriceTicks))
                }
            };


            Task<Entry> getResponseTextTask = _client.EnqueueRequestAsync(entry);

            Task<GetPriceTickResponseDTO> deserializeTask =
                getResponseTextTask.ContinueWith(task =>
                {
                    var data =
                        JsonConvert.DeserializeObject<GetPriceTickResponseDTO>(task.Result.Response.Content.Text);
                    return data;
                });

            return deserializeTask.ContinueWith(task => task.Result);
        }
Пример #26
0
        // ***********************************
        // GetActiveStopLimitOrder
        // ***********************************


        /// <summary>
        /// Queries for an active stop limit order with a specified order ID. It returns a null value if the order doesn't exist, or is not an active stop limit order. This URI is intended to support a grid in a UI. One usage pattern is to subscribe to streaming orders, call the HTTP service [ListActiveStopLimitOrders](http://labs.cityindex.com/docs/Content/HTTP%20Services/ListActiveStopLimitOrders.htm) for the initial data to display in the grid, and call this URI when you get updates on the order stream to get the updated data in this format. For a more comprehensive order response, see the HTTP service [GetOrder](http://labs.cityindex.com/docs/Content/HTTP%20Services/GetOrder.htm).
        /// </summary>
        /// <param name="OrderId">The requested order ID.</param>
        public virtual Task<GetActiveStopLimitOrderResponseDTO> GetActiveStopLimitOrderAsync(string OrderId)
        {
            var entry = new Entry
            {
                Request = new Request
                {
                    Method = "GET",
                    Url = _client.ApiBaseUrl + "/order/{OrderId}/activestoplimitorder",
                    QueryString = new QueryString(new NameValuePair("OrderId", OrderId))
                }
            };


            Task<Entry> getResponseTextTask = _client.EnqueueRequestAsync(entry);

            Task<GetActiveStopLimitOrderResponseDTO> deserializeTask =
                getResponseTextTask.ContinueWith(task =>
                {
                    var data =
                        JsonConvert.DeserializeObject<GetActiveStopLimitOrderResponseDTO>(task.Result.Response.Content.Text);
                    return data;
                });

            return deserializeTask.ContinueWith(task => task.Result);
        }
Пример #27
0
        // ***********************************
        // ListNewsHeadlinesWithSource
        // ***********************************


        /// <summary>
        /// Get a list of current news headlines.
        /// </summary>
        /// <param name="source">The news feed source provider. Valid options are: **dj**|**mni**|**ci**.</param>
        /// <param name="category">Filter headlines by category. Valid categories depend on the source used:  for **dj**: *uk*|*aus*, for **ci**: *SEMINARSCHINA*, for **mni**: *ALL*.</param>
        /// <param name="maxResults">Specify the maximum number of headlines returned.</param>
        public virtual Task<ListNewsHeadlinesResponseDTO> ListNewsHeadlinesWithSourceAsync(string source, string category, int maxResults)
        {
            var entry = new Entry
            {
                Request = new Request
                {
                    Method = "GET",
                    Url = _client.ApiBaseUrl + "/news/{source}/{category}?MaxResults={maxResults}",
                    QueryString = new QueryString(new NameValuePair("source", source), new NameValuePair("category", category), new NameValuePair("maxResults", maxResults))
                }
            };


            Task<Entry> getResponseTextTask = _client.EnqueueRequestAsync(entry);

            Task<ListNewsHeadlinesResponseDTO> deserializeTask =
                getResponseTextTask.ContinueWith(task =>
                {
                    var data =
                        JsonConvert.DeserializeObject<ListNewsHeadlinesResponseDTO>(task.Result.Response.Content.Text);
                    return data;
                });

            return deserializeTask.ContinueWith(task => task.Result);
        }
Пример #28
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public virtual Task<Entry> EnqueueRequestAsync(Entry e)
        {
            // TODO: implement throttled queue using Task/Parallel classes
            // TODO: use reactive extensions observable to implement missing request timeout functionality
            // http://stackoverflow.com/questions/6411850/implement-an-async-timeout-in-silverlight

            // clone the entry as we are going to modify it.


            var entry = Helper.CloneObject<Entry>(e);

            Helper.PrepareEntryRequest(entry);

            var taskCompletionSource = new TaskCompletionSource<Entry>();

            HttpWebRequest r = WebRequest.CreateHttp(entry.Request.Url);

            r.Method = entry.Request.Method;

            if (entry.Request.Headers != null)
            {
                foreach (NameValuePair header in entry.Request.Headers)
                {
                    r.Headers[header.Name] = header.Value.ToString();
                }
            }

            byte[] bytes = null;

            if (entry.Request.PostData != null)
            {
                if (!string.IsNullOrEmpty(entry.Request.PostData.MimeType))
                {
                    r.ContentType = entry.Request.PostData.MimeType;
                }

                if (!string.IsNullOrEmpty(entry.Request.PostData.Text))
                {
                    bytes = Encoding.UTF8.GetBytes(entry.Request.PostData.Text);
                }

                r.BeginGetRequestStream(b =>
                    {
                        try
                        {
                            using (Stream rqs = r.EndGetRequestStream(b))
                            {
                                if (bytes != null && bytes.Length > 0)
                                {
                                    rqs.Write(bytes, 0, bytes.Length);
                                }
                            }
                            IssueRequest(r, entry, taskCompletionSource);
                        }
                        catch (Exception ex)
                        {
                            taskCompletionSource.SetException(ex);
                        }
                    }, r);
            }
            else
            {
                IssueRequest(r, entry, taskCompletionSource);
            }


            return taskCompletionSource.Task;
        }