public void CanSimulateTrade() { var marketInfo = GetMarketInfo(_CFDmarketId); //BUY var trade = new NewTradeOrderRequestDTO() { AuditId = marketInfo.AuditId, AutoRollover = false, BidPrice = marketInfo.Bid, Close = null, Currency = null, Direction = "buy", IfDone = null, MarketId = marketInfo.MarketId, OfferPrice = marketInfo.Offer, Quantity = 1, QuoteId = null, TradingAccountId = _accounts.CFDAccount.TradingAccountId }; var response = _rpcClient.TradesAndOrders.SimulateTrade(trade); _rpcClient.MagicNumberResolver.ResolveMagicNumbers(response); Assert.AreEqual("Accepted", response.Status_Resolved); }
public void CanRecieveOrderNotification() { var MARKET_ID = 154297; //GBP/USD var gate = new ManualResetEvent(false); var rpcClient = BuildRpcClient(); var streamingClient = rpcClient.CreateStreamingClient(); var priceListener = streamingClient.BuildPricesListener(MARKET_ID); var ordersListener = streamingClient.BuildOrdersListener(); try { OrderDTO newOrder = null; var marketInfo = rpcClient.Market.GetMarketInformation(MARKET_ID.ToString()); var account = rpcClient.AccountInformation.GetClientAndTradingAccount(); ordersListener.MessageReceived += (s, e) => { newOrder = e.Data; Console.WriteLine( string.Format( "New order has been recieved on Orders stream\r\n {0}", e.Data.ToStringWithValues())); gate.Set(); }; priceListener.MessageReceived += (s, e) => { var order = new NewTradeOrderRequestDTO { MarketId = e.Data.MarketId, BidPrice = e.Data.Bid, OfferPrice = e.Data.Offer, AuditId = e.Data.AuditId, Quantity = marketInfo.MarketInformation.WebMinSize.GetValueOrDefault() + 1, TradingAccountId = account.TradingAccounts[0].TradingAccountId, Direction = "buy" }; var response = rpcClient.TradesAndOrders.Trade(order); rpcClient.MagicNumberResolver.ResolveMagicNumbers(response); Console.WriteLine(string.Format("Trade/order placed: \r\n{0}", response.ToStringWithValues())); Assert.AreEqual("Accepted", response.Status_Resolved, string.Format("Error placing order: \r\n{0}", response.ToStringWithValues())); }; gate.WaitOne(TimeSpan.FromSeconds(15)); Assert.IsNotNull(newOrder); } finally { streamingClient.TearDownListener(priceListener); streamingClient.TearDownListener(ordersListener); streamingClient.Dispose(); } }
public ApiTradeOrderResponseDTO Trade(PriceDTO price, Direction direction) { AccountInformationResponseDTO accountInfo = _client.AccountInformation.GetClientAndTradingAccount(); int tradingAccountId = GetTradingAccountId(_client, price.MarketId, accountInfo); var request = new NewTradeOrderRequestDTO { MarketId = price.MarketId, Direction = direction.ToString().ToLower(), Quantity = Quantity, BidPrice = price.Bid, OfferPrice = price.Offer, AuditId = price.AuditId, TradingAccountId = tradingAccountId, AutoRollover = false }; ApiTradeOrderResponseDTO response = _client.TradesAndOrders.Trade(request); return response; }
public void CanConsumeTradeMarginStream() { var tradeMarginListener = _streamingClient.BuildTradeMarginListener(); // set up a handler to respond to stream events var gate = new AutoResetEvent(false); TradeMarginDTO actual = null; Stopwatch sw = new Stopwatch(); sw.Start(); tradeMarginListener.MessageReceived += (s, e) => { Console.WriteLine( "-----------------------------------------------"); sw.Stop(); actual = e.Data; Console.WriteLine("event received in {0} seconds", TimeSpan.FromMilliseconds(sw.ElapsedMilliseconds)); Console.WriteLine(actual.ToStringWithValues()); Console.WriteLine( "-----------------------------------------------"); gate.Set(); }; // place a trade to give the margin listener something to listen to AccountInformationResponseDTO accounts = _authenticatedClient.AccountInformation.GetClientAndTradingAccount(); PriceDTO marketInfo = GetMarketInfo(80905); NewTradeOrderRequestDTO trade = new NewTradeOrderRequestDTO() { AuditId = marketInfo.AuditId, AutoRollover = false, BidPrice = marketInfo.Bid, Close = null, Currency = null, Direction = "buy", IfDone = null, MarketId = marketInfo.MarketId, OfferPrice = marketInfo.Offer, Quantity = 1, QuoteId = null, TradingAccountId = accounts.SpreadBettingAccount.TradingAccountId }; var response = _authenticatedClient.TradesAndOrders.Trade(trade); gate.WaitOne(50000); _streamingClient.TearDownListener(tradeMarginListener); // close the tradeMarginListener //marketInfo = GetMarketInfo(80905); //int orderId = response.OrderId; //trade = new NewTradeOrderRequestDTO() //{ // AuditId = marketInfo.AuditId, // AutoRollover = false, // BidPrice = marketInfo.Bid, // Close = new int[] { orderId }, // Currency = null, // Direction = "sell", // IfDone = null, // MarketId = marketInfo.MarketId, // OfferPrice = marketInfo.Offer, // Quantity = 1, // QuoteId = null, // TradingAccountId = accounts.SpreadBettingAccount.TradingAccountId //}; //_authenticatedClient.TradesAndOrders.Trade(trade); Assert.IsNotNull(actual,"did not get a streaming event"); }
/// <summary> /// API call that allows a simulated new trade to be placed. /// </summary> /// <param name="Trade">The simulated trade request.</param> /// <param name="callback"></param> /// <param name="state"></param> public virtual void BeginSimulateTrade(NewTradeOrderRequestDTO Trade, ReliableAsyncCallback callback, object state) { string uriTemplate = "/simulate/newtradeorder"; _client.BeginRequest(RequestMethod.POST, "order", uriTemplate , new Dictionary<string, object> { { "Trade", Trade} },ContentType.JSON,ContentType.JSON, TimeSpan.FromMilliseconds(0), 30000,0 ,callback, state); }
// *********************************** // SimulateTrade // *********************************** /// <summary> /// API call that allows a simulated new trade to be placed. /// </summary> /// <param name="Trade">The simulated trade request.</param> public virtual ApiSimulateTradeOrderResponseDTO SimulateTrade(NewTradeOrderRequestDTO Trade) { string uriTemplate = "/simulate/newtradeorder"; return _client.Request<ApiSimulateTradeOrderResponseDTO>(RequestMethod.POST,"order", uriTemplate , new Dictionary<string, object> { { "Trade", Trade} },ContentType.JSON,ContentType.JSON, TimeSpan.FromMilliseconds(0),30000,0 ); }
// *********************************** // Trade // *********************************** /// <summary> /// <p>Place a trade on a particular market. Post a <a onclick="dojo.hash('#type.NewTradeOrderRequestDTO'); return false;" class="json-link" href="#">NewTradeOrderRequestDTO</a> to the uri specified below.</p> <p>Do not set any order id fields when requesting a new trade, the platform will generate them.</p> /// </summary> /// <param name="trade">The trade request</param> public ApiTradeOrderResponseDTO Trade(NewTradeOrderRequestDTO trade) { return Request<ApiTradeOrderResponseDTO>("order", "/newtradeorder", "POST", new Dictionary<string, object> { { "trade", trade} }, TimeSpan.FromMilliseconds(0), "trading"); }
/// <summary> /// <p>Place a trade on a particular market. Post a <a onclick="dojo.hash('#type.NewTradeOrderRequestDTO'); return false;" class="json-link" href="#">NewTradeOrderRequestDTO</a> to the uri specified below.</p> <p>Do not set any order id fields when requesting a new trade, the platform will generate them.</p> /// </summary> /// <param name="trade">The trade request</param> /// <param name="callback"></param> /// <param name="state"></param> public void BeginTrade(NewTradeOrderRequestDTO trade, ApiAsyncCallback<ApiTradeOrderResponseDTO> callback, object state) { BeginRequest(callback, state, "order", "/newtradeorder", "POST", new Dictionary<string, object> { { "trade", trade} }, TimeSpan.FromMilliseconds(0), "trading"); }
public void CanUpdateTrade() { var rpcClient = BuildRpcClient(); AccountInformationResponseDTO accounts = rpcClient.AccountInformation.GetClientAndTradingAccount(); PriceDTO marketInfo = GetMarketInfo(_CFDmarketId); var trade = new NewTradeOrderRequestDTO() { AuditId = marketInfo.AuditId, AutoRollover = false, BidPrice = marketInfo.Bid, Close = null, Currency = null, Direction = "buy", IfDone = null, MarketId = marketInfo.MarketId, OfferPrice = marketInfo.Offer, Quantity = 1, QuoteId = null, TradingAccountId = accounts.CFDAccount.TradingAccountId }; var order = rpcClient.TradesAndOrders.Trade(trade); rpcClient.MagicNumberResolver.ResolveMagicNumbers(order); Assert.AreEqual("Accepted", order.Status_Resolved); var update = new UpdateTradeOrderRequestDTO { OrderId = order.OrderId, MarketId = trade.MarketId, Currency = trade.Currency, IfDone = new[] { new ApiIfDoneDTO { Stop = new ApiStopLimitOrderDTO { TriggerPrice = marketInfo.Offer+10, Direction = "sell", IfDone = null, MarketId = marketInfo.MarketId, Quantity = 1, TradingAccountId = accounts.CFDAccount.TradingAccountId } } }, AuditId = trade.AuditId, AutoRollover = trade.AutoRollover, BidPrice = trade.BidPrice, Close = trade.Close, Direction = trade.Direction, OfferPrice = trade.OfferPrice, Quantity = trade.Quantity, QuoteId = trade.QuoteId, TradingAccountId = trade.TradingAccountId }; var response = rpcClient.TradesAndOrders.UpdateTrade(update); }
private void OnMarketPricesStreamMessageReceived(object sender, MessageEventArgs<PriceDTO> e) { if (!_listening || _ordered || Market == null) return; _ordered = true; var order = new NewTradeOrderRequestDTO { MarketId = e.Data.MarketId, BidPrice = e.Data.Bid, OfferPrice = e.Data.Offer, AuditId = e.Data.AuditId, Quantity = Market.WebMinSize.GetValueOrDefault() + 1, TradingAccountId = Account.TradingAccounts[0].TradingAccountId, Direction = "buy" }; Dispatcher.BeginInvoke(() => listBox1.Items.Add("price update arrived, making a new trade")); RpcClient.TradesAndOrders.BeginTrade(order, ar => { var result = RpcClient.TradesAndOrders.EndTrade(ar); var newOrder = result.Orders.Length > 0 && result.Orders[0].OrderId == result.OrderId ? result.Orders[0] : null; if (newOrder != null && newOrder.Status == 8 && newOrder.StatusReason == 140) { Dispatcher.BeginInvoke(() => { listBox1.Items.Add("the account is on a dealer watchlist!"); listBox1.Items.Add("waiting for the order approval..."); }); } }, null); }
/// <summary> /// An example of one strategy for placing a trade. /// </summary> /// <param name="request"></param> /// <param name="callback"></param> public void PlaceTradeAsync(NewTradeOrderRequestDTO request, TradeOrderResponseDelegate callback) { RpcClient.TradesAndOrders.BeginTrade(request, (ar) => { var result = new ApiResult<ApiTradeOrderResponseDTO>(); try { result.Data = RpcClient.TradesAndOrders.EndTrade(ar); // resolve the magic numbers so that we have readable values for status codes RpcClient.MagicNumberResolver.ResolveMagicNumbers(result.Data); } catch (Exception ex) { result.Exception = ex; } // to avoid deadlocks that can occur when an async call is made within the callback of another async callback // we will fire the callback on a new thread. new Thread(() => callback(result)).Start(); // NOTE: the deadlock is a result of locking on the request queue and cache in JsonClient and is the price paid // for that functionality. // TODO: (in JsonClient) find out how to determine if an object is being locked on and throw exception if this is so. }, null); }
public void PlaceTradeAsync(int tradingAccountId, int marketId, TradeDirection direction, decimal quantity, decimal bidPrice, decimal offerPrice, int[] close, TradeOrderResponseDelegate callback) { NewTradeOrderRequestDTO orderRequest; lock (_syncObj) { PriceDTO price; _prices.TryGetValue(marketId, out price); if (price == null) { throw new Exception("you must have a price subscription in order to place a trade"); } orderRequest = new NewTradeOrderRequestDTO { AuditId = price.AuditId, MarketId = marketId, Direction = direction.ToString(), BidPrice = bidPrice, OfferPrice = offerPrice, Quantity = quantity, Close = close, TradingAccountId = tradingAccountId }; } PlaceTradeAsync(orderRequest, callback); }
public void CanTrade() { //MarketId: 80905 //Name: "GBP/USD (per 0.0001) Rolling Spread" //MarketId: 400516274 //Name: "GBP/USD (per 0.0001) Dec 11 Spread" var rpcClient = BuildRpcClient(); AccountInformationResponseDTO accounts = rpcClient.AccountInformation.GetClientAndTradingAccount(); PriceDTO marketInfo = GetMarketInfo(80905); NewTradeOrderRequestDTO trade = new NewTradeOrderRequestDTO() { AuditId = marketInfo.AuditId, AutoRollover = false, BidPrice = marketInfo.Bid, Close = null, Currency = null, Direction = "buy", IfDone = null, MarketId = marketInfo.MarketId, OfferPrice = marketInfo.Offer, Quantity = 1, QuoteId = null, TradingAccountId = accounts.SpreadBettingAccount.TradingAccountId }; var response = rpcClient.TradesAndOrders.Trade(trade); rpcClient.MagicNumberResolver.ResolveMagicNumbers(response); Assert.AreEqual(response.Status_Resolved, "Accepted"); marketInfo = GetMarketInfo(80905); int orderId = response.OrderId; trade = new NewTradeOrderRequestDTO() { AuditId = marketInfo.AuditId, AutoRollover = false, BidPrice = marketInfo.Bid, Close = new int[] { orderId }, Currency = null, Direction = "sell", IfDone = null, MarketId = marketInfo.MarketId, OfferPrice = marketInfo.Offer, Quantity = 1, QuoteId = null, TradingAccountId = accounts.SpreadBettingAccount.TradingAccountId }; response = rpcClient.TradesAndOrders.Trade(trade); rpcClient.MagicNumberResolver.ResolveMagicNumbers(response); Assert.AreEqual(response.Status_Resolved, "Accepted"); }
private int Trade(Client client, AccountInformationResponseDTO accountInfo, int marketId, PriceDTO price, decimal quantity, string direction, IEnumerable<int> closeOrderIds) { var tradeRequest = new NewTradeOrderRequestDTO { MarketId = marketId, Quantity = quantity, Direction = direction, TradingAccountId = accountInfo.SpreadBettingAccount.TradingAccountId, AuditId = price.AuditId, BidPrice = price.Bid, OfferPrice = price.Offer, Close = closeOrderIds.ToArray(), }; var resp = client.TradesAndOrders.Trade(tradeRequest); if (resp.OrderId == 0) { client.MagicNumberResolver.ResolveMagicNumbers(resp); var message = GetResponseDescription(resp); throw new ApplicationException(message); } return resp.OrderId; }