protected void Application_Start(object sender, EventArgs e) { // set up a capturing logger so that we can output snapshots of activity upon page render LogManager.CreateInnerLogger = (logName, logLevel, showLevel, showDateTime, showLogName, dateTimeFormat) => { return(new CapturingAppender(logName, logLevel, showLevel, showDateTime, showLogName, dateTimeFormat)); }; try { GlobalRpcClient = new Client(new Uri("https://ciapipreprod.cityindextest9.co.uk/TradingApi"), AppKey); ApiLogOnResponseDTO response = GlobalRpcClient.LogIn("XX070608", "password"); if (response.PasswordChangeRequired) { _rpcStatus = "admin must change password for global account"; } else { _rpcStatus = "OK"; } } catch (ApiException ex) { _rpcStatus = ex.ToString(); } catch (Exception ex) { _rpcStatus = ex.ToString(); } }
static void Main(string[] args) { try { var listeners = new[] { new TextWriterTraceListener(Console.Out) }; Debug.Listeners.AddRange(listeners); var adapter = new MyLoggerFactoryAdapter(null) { OnMessage = AddLogMessage }; LogManager.Adapter = adapter; var client = new CIAPI.Rpc.Client(RPC_URI); client.LogIn(USERNAME, PASSWORD); var news = client.News.ListNewsHeadlinesWithSource("mni", "ALL", 10); client.LogOut(); } catch (Exception exc) { Console.WriteLine(exc); } }
public void SubscribeToNewsHeadlineStream() { //First we need a valid session, obtained from the Rpc client var ctx = new CIAPI.Rpc.Client(RPC_URI); ctx.LogIn(USERNAME, PASSWORD); //Next we create a connection to the streaming api, using the authenticated session //You application should only ever have one of these var streamingClient = StreamingClientFactory.CreateStreamingClient(STREAMING_URI, USERNAME, ctx.Session); //And instantiate a listener for news headlines on the appropriate topic //You can have multiple listeners on one connection var newsListener = streamingClient.BuildNewsHeadlinesListener("UK"); //The MessageReceived event will be triggered every time a new News headline is available, //so attach a handler for that event, and wait until something comes through var gate = new ManualResetEvent(false); NewsDTO receivedNewsHeadline = null; newsListener.MessageReceived += (s, e) => { receivedNewsHeadline = e.Data; //Do something with the new News headline data - perhaps update a news ticker? gate.Set(); }; gate.WaitOne(); //Shut down the connection streamingClient.Dispose(); //Destroy your session ctx.LogOut(); }
static void Main(string[] args) { try { var adapter = new MyLoggerFactoryAdapter(null) { OnMessage = AddLogMessage }; LogManager.Adapter = adapter; _client = new CIAPI.Rpc.Client(RPC_URI); _client.LogIn(USERNAME, PASSWORD); for (int i = 0; i < 100; i++) { ThreadPool.QueueUserWorkItem(s => EndlessTest()); } Console.ReadKey(); _client.LogOut(); _client.Dispose(); } catch (Exception exc) { Console.WriteLine(exc); } }
protected void Application_Start(object sender, EventArgs e) { // set up a capturing logger so that we can output snapshots of activity upon page render LogManager.CreateInnerLogger = (logName, logLevel, showLevel, showDateTime, showLogName, dateTimeFormat) => { return new CapturingAppender(logName, logLevel, showLevel, showDateTime, showLogName, dateTimeFormat); }; try { GlobalRpcClient = new Client(new Uri("https://ciapipreprod.cityindextest9.co.uk/TradingApi"), AppKey); ApiLogOnResponseDTO response = GlobalRpcClient.LogIn("XX070608", "password"); if (response.PasswordChangeRequired) { _rpcStatus = "admin must change password for global account"; } else { _rpcStatus = "OK"; } } catch (ApiException ex) { _rpcStatus = ex.ToString(); } catch (Exception ex) { _rpcStatus = ex.ToString(); } }
/// <summary> /// While the code is drastically simplified in comparison to the async pattern, you will typically /// want to do this on another thread and use BeingInvoke on the UI to marshal UI updates to the UI thread. /// This is probably the simplest pattern. /// </summary> private static void GetNewsSynchronously() { try { var ctx = new CIAPI.Rpc.Client(new Uri(StaticTestConfig.RpcUrl), new Uri(StaticTestConfig.StreamingUrl), AppKey); ctx.LogIn(StaticTestConfig.ApiUsername, StaticTestConfig.ApiPassword); var headlinesResponse = ctx.News.ListNewsHeadlinesWithSource("dj", "UK", 10); foreach (var item in headlinesResponse.Headlines) { // item contains id, date and headline. Console.WriteLine("{0} {1} {2}\r\n", item.StoryId, item.Headline, item.PublishDate); // fetch details to get all of the above and the body of the story var detailResponse = ctx.News.GetNewsDetail("dj", item.StoryId.ToString()); Console.WriteLine("{0}", detailResponse.NewsDetail.Story.Substring(0, 35) + "..."); Console.WriteLine("\r\n-----------------------------------------------------------------------------\r\n"); } ctx.LogOut(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); Console.WriteLine("\r\nPress enter to continue\r\n"); Console.ReadLine(); } #endregion }
public static void ConnectCIAPI() { CIAPI_Client = new CIAPI.Rpc.Client(RPC_URI); CIAPI_Client.LogIn(USERNAME, PASSWORD); StreamingClient = StreamingClientFactory.CreateStreamingClient(STREAMING_URI, USERNAME, CIAPI_Client.SessionId); StreamingClient.Connect(); IsConnected = true; }
public void FetchNews_sync() { var ctx = new CIAPI.Rpc.Client(RPC_URI); ctx.LogIn(USERNAME, PASSWORD); ListNewsHeadlinesResponseDTO news = ctx.News.ListNewsHeadlinesWithSource("dj", "UK", 10); //do something with the news ctx.LogOut(); }
public void FetchNews_sync() { var ctx = new CIAPI.Rpc.Client(RPC_URI, STREAMING_URI, AppKey); ctx.LogIn(USERNAME, PASSWORD); ListNewsHeadlinesResponseDTO news = ctx.News.ListNewsHeadlinesWithSource("dj", "UK", 10); //do something with the news ctx.LogOut(); }
public void FetchNews_sync() { var ctx = new CIAPI.Rpc.Client(RPC_URI); ctx.LogIn(USERNAME, PASSWORD); ListNewsHeadlinesResponseDTO news = ctx.ListNewsHeadlines("UK", 10); //do something with the news ctx.LogOut(); }
public static IStreamingClient BuildStreamingClient( string userName = "******", string password = "******") { const string apiUrl = "https://ciapipreprod.cityindextest9.co.uk/TradingApi/"; var authenticatedClient = new CIAPI.Rpc.Client(new Uri(apiUrl)); authenticatedClient.LogIn(userName, password); var streamingUri = new Uri("https://pushpreprod.cityindextest9.co.uk"); return StreamingClientFactory.CreateStreamingClient(streamingUri, userName, authenticatedClient.Session); }
public void SubscribeToNewsHeadlineStream() { //First we need a valid session, obtained from the Rpc client var ctx = new CIAPI.Rpc.Client(RPC_URI); ctx.LogIn(USERNAME, PASSWORD); //Next we create a connection to the streaming api, using the authenticated session //You application should only ever have one of these var streamingClient = StreamingClientFactory.CreateStreamingClient(STREAMING_URI, USERNAME, ctx.SessionId); streamingClient.Connect(); //And instantiate a listener for news headlines on the appropriate topic //You can have multiple listeners on one connection var newsListener = streamingClient.BuildNewsHeadlinesListener("NEWS.MOCKHEADLINES.UK"); newsListener.Start(); //The MessageReceived event will be triggered every time a new News headline is available, //so attach a handler for that event, and wait until something comes through var gate = new ManualResetEvent(false); NewsDTO receivedNewsHeadline = null; newsListener.MessageReceived += (s, e) => { receivedNewsHeadline = e.Data; //Do something with the new News headline data - perhaps update a news ticker? gate.Set(); }; gate.WaitOne(); //Clean up //Stop any listeners newsListener.Stop(); //Shut down the connection streamingClient.Disconnect(); //Destroy your session ctx.LogOut(); }
public void YouCanForceYourSessionToExpireByLoggingOut() { _rpcClient.LogIn(USERNAME, PASSWORD); KoanAssert.That(_rpcClient.Session, Is.Not.Null, "You should have a valid sessionId after logon"); var oldSessionId = _rpcClient.Session; //Logging out force expires your session token on the server _rpcClient.LogOut(); //So that future requests with your old token will fail. try { _rpcClient.Session = oldSessionId; var headlines2 = _rpcClient.News.ListNewsHeadlinesWithSource("dj", "AUS", 4); KoanAssert.Fail("the previous line should have thrown an (401) Unauthorized exception"); } catch (ReliableHttpException e) { KoanAssert.That(e.Message, Is.StringContaining("Session is not valid"), "The error message should contain something about 'Session is not valid'"); } }
public void Test2() { var authenticatedClient = new CIAPI.Rpc.Client(new Uri(apiUrl)); authenticatedClient.LogIn(userName, password); var client = new LightstreamerClient(streamingUrl, authenticatedClient.UserName, authenticatedClient.Session); client.StatusUpdate += AdapterStatusUpdate; var listener = client.BuildListener<PriceDTO>(dataAdapter, topic); listener.MessageReceived += ListenerMessageReceived; new ManualResetEvent(false).WaitOne(20000); client.TearDownListener(listener); client.Dispose(); }
public void CreatingASession() { //Interaction with the API is done via a top level "client" object //that holds details about your connection. //You need to initialise the client with a valid endpoint _rpcClient = new Rpc.Client(Settings.RpcUri, Settings.StreamingUri, AppKey); //And then create a session by creating a username & password //You can get test credentials by requesting them at https://ciapipreprod.cityindextest9.co.uk/CIAPI.docs/#content.test-credentials try { _rpcClient.LogIn(USERNAME, PASSWORD); } catch (ReliableHttpException apiException) { KoanAssert.Fail(string.Format("cannot login because {0}", apiException.Message)); } KoanAssert.That(_rpcClient.Session != "", "after logging in, you should have a valid session"); }
public void Test() { var authenticatedClient = new CIAPI.Rpc.Client(new Uri(apiUrl)); authenticatedClient.LogIn(userName, password); var adapter = new FaultTolerantLsClientAdapter(streamingUrl, authenticatedClient.UserName, authenticatedClient.Session, dataAdapter); adapter.StatusUpdate += AdapterStatusUpdate; adapter.Start(); var listener = adapter.BuildListener<PriceDTO>(topic); listener.MessageReceived += ListenerMessageReceived; new ManualResetEvent(false).WaitOne(10000); adapter.Stop(); adapter.Start(); new ManualResetEvent(false).WaitOne(10000); adapter.Stop(); }
public void NonRetryableExceptionFailsInsteadOfRetrying() { Console.WriteLine("NonRetryableExceptionFailsInsteadOfRetrying"); var requestFactory = new TestRequestFactory(); var ctx = new Client(new Uri(TestConfig.RpcUrl), new RequestCache(), requestFactory, _standardThrottleScopes, 3); requestFactory.CreateTestRequest("", TimeSpan.FromMilliseconds(300), null, null, new WebException("(401) Unauthorized")); Assert.Throws<ApiException>(() => ctx.LogIn("foo", "bar")); }
public void ShouldThrowExceptionIfRequestTimesOut() { var requestFactory = new TestRequestFactory { RequestTimeout = TimeSpan.FromSeconds(1) }; var ctx = new Client(new Uri(TestConfig.RpcUrl), new RequestCache(), requestFactory, _standardThrottleScopes, 3); requestFactory.CreateTestRequest(LoggedIn, TimeSpan.FromSeconds(300)); Assert.Throws<ApiException>(() => ctx.LogIn("foo", "bar")); }
public void SetupFixture() { var authenticatedClient = new CIAPI.Rpc.Client(Settings.RpcUri); authenticatedClient.LogIn(Settings.RpcUserName, Settings.RpcPassword); streamingClient = StreamingClientFactory.CreateStreamingClient(Settings.StreamingUri, Settings.RpcUserName, authenticatedClient.Session); }
/// <summary> /// While the code is drastically simplified in comparison to the async pattern, you will typically /// want to do this on another thread and use BeingInvoke on the UI to marshal UI updates to the UI thread. /// This is probably the simplest pattern. /// </summary> private static void GetNewsSynchronously() { try { var ctx = new CIAPI.Rpc.Client(new Uri(TestConfig.RpcUrl)); ctx.LogIn(TestConfig.ApiUsername, TestConfig.ApiPassword); var headlinesResponse = ctx.ListNewsHeadlines("UK", 10); foreach (var item in headlinesResponse.Headlines) { // item contains id, date and headline. Console.WriteLine("{0} {1} {2}\r\n", item.StoryId, item.Headline, item.PublishDate); // fetch details to get all of the above and the body of the story var detailResponse = ctx.GetNewsDetail(item.StoryId.ToString()); Console.WriteLine("{0}", detailResponse.NewsDetail.Story.Substring(0, 35) + "..."); Console.WriteLine("\r\n-----------------------------------------------------------------------------\r\n"); } ctx.LogOut(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); Console.WriteLine("\r\nPress enter to continue\r\n"); Console.ReadLine(); } #endregion }
public void FindRelatedOco() { // 1) Logon to the Flex ITP and configure your account (a CFD only account) so that you have only one open position with an attached stop and limit order // https://ciapi.cityindex.com/flexitp // 2) Grab the open positions for this account var client = new CIAPI.Rpc.Client(new Uri(serviceUrl)); client.LogIn(username, password); var accountInfo = client.AccountInformation.GetClientAndTradingAccount(); var openpositions = client.TradesAndOrders.ListOpenPositions(accountInfo.TradingAccounts[0].TradingAccountId); // 3) Grab the related stop and limit orders fot this open position var stopOrder = client.TradesAndOrders.GetActiveStopLimitOrder(openpositions.OpenPositions[0].StopOrder.OrderId.ToString()); /* Request URI : https://ciapi.cityindex.com/tradingapi/order/473037563/activestoplimitorder ResponseText : {"ActiveStopLimitOrder":{"Applicability":2,"Currency":"USD","Direction":"sell","ExpiryDateTimeUTC":null,"LastChangedDateTimeUTC":"\/Date(1327946960482)\/","LimitOrder":null,"MarketId":400481134,"MarketName":"EUR\/USD", * "OcoOrder":{"OrderId":473037507,"Quantity":5000,"TriggerPrice":1.5}, * "OrderId":473037563,"ParentOrderId":473037506,"Quantity":5000,"Status":2,"StopOrder":null,"TradingAccountId":400258216,"TriggerPrice":1.2,"Type":2}} */ var limitOrder = client.TradesAndOrders.GetActiveStopLimitOrder(openpositions.OpenPositions[0].LimitOrder.OrderId.ToString()); /* Request URI : https://ciapi.cityindex.com/tradingapi/order/473037507/activestoplimitorder ResponseText : {"ActiveStopLimitOrder":{"Applicability":2,"Currency":"USD","Direction":"sell","ExpiryDateTimeUTC":null,"LastChangedDateTimeUTC":"\/Date(1327946876905)\/","LimitOrder":null,"MarketId":400481134,"MarketName":"EUR\/USD", * "OcoOrder":null, * "OrderId":473037507,"ParentOrderId":473037506,"Quantity":5000,"Status":2,"StopOrder":null,"TradingAccountId":400258216,"TriggerPrice":1.5,"Type":3}} */ // 4) Now, check that stopOrder is related to the limitOrder via the OcoOrder Assert.IsNotNull(stopOrder.ActiveStopLimitOrder.OcoOrder, "stopOrder has no OcoOrder"); Assert.AreEqual(stopOrder.ActiveStopLimitOrder.OcoOrder.OrderId, limitOrder.ActiveStopLimitOrder.OrderId, "stopOrder's Oco is not the limitOrder as expected"); // 5) Now, check that reverse is also true - ie., the limitOrder is related to the stopOrder via the OcoOrder Assert.IsNotNull(limitOrder.ActiveStopLimitOrder.OcoOrder, "limitOrder has no OcoOrder"); Assert.AreEqual(limitOrder.ActiveStopLimitOrder.OcoOrder.OrderId, stopOrder.ActiveStopLimitOrder.OrderId, "limitOrder's Oco is not the stopOrder as expected"); /** * Replicate this behaviour using the JS test console at https://ciapi.cityindex.com/tradingapi * var userName = "******"; doPost('/session',{ "UserName": userName, "Password": "******"}, function (data, textCode) { setRequestHeader("UserName", userName); setRequestHeader("Session", data.Session); doGet('/UserAccount/ClientAndTradingAccount'); //TradingAccountId is 400258216 //grab all open positions doGet('/order/openpositions?TradingAccountId=400258216'); //Which gives us position 473037506, that has a stop (473037563) & limit order (473037507) // Get all orders - there should be 2. doGet('/order/activestoplimitorders?tradingaccountid=400258216'); // grab the stop - note that the attached OcoOrder is the limit doGet('/order/473037563/activestoplimitorder'); //grab the limit - note that the limit has no attached OcoOrder doGet('/order/473037507/activestoplimitorder'); }); */ }