private async Task RunTradesTest() { // trade tests await PlaceMarketOrder(); // get list of open trades var openTrades = await Rest.GetTradeListAsync(_accountId); _results.Verify(openTrades.Count > 0 && openTrades[0].id > 0, "Trades list retrieved"); if (openTrades.Count > 0) { // get details for a trade var tradeDetails = await Rest.GetTradeDetailsAsync(_accountId, openTrades[0].id); _results.Verify(tradeDetails.id > 0 && tradeDetails.price > 0 && tradeDetails.units != 0, "Trade details retrieved"); // Modify an open trade var request = new Dictionary <string, string> { { "stopLoss", "0.4" } }; var modifiedDetails = await Rest.PatchTradeAsync(_accountId, openTrades[0].id, request); _results.Verify(modifiedDetails.id > 0 && Math.Abs(modifiedDetails.stopLoss - 0.4) < float.Epsilon, "Trade modified"); if (!_marketHalted) { // close an open trade var closedDetails = await Rest.DeleteTradeAsync(_accountId, openTrades[0].id); _results.Verify(closedDetails.id > 0, "Trade closed"); _results.Verify(!string.IsNullOrEmpty(closedDetails.time), "Trade close details time"); _results.Verify(!string.IsNullOrEmpty(closedDetails.side), "Trade close details side"); _results.Verify(!string.IsNullOrEmpty(closedDetails.instrument), "Trade close details instrument"); _results.Verify(closedDetails.price > 0, "Trade close details price"); _results.Verify(closedDetails.profit != 0, "Trade close details profit"); } else { _results.Add("Skipping: Trade delete test because market is halted"); } } else { _results.Add("Skipping: Trade details test because no trades were found"); _results.Add("Skipping: Trade modify test because no trades were found"); _results.Add("Skipping: Trade delete test because no trades were found"); } }
protected async Task RunTradesTestAsync() { if (!_tradeTestCompleted) { // trade tests await PlaceTestMarketOrder(); // get list of open trades var openTrades = await Rest.GetTradeListAsync(Security.Account.PracticeAccount); if (openTrades.Count > 0) { // get details for a trade var tradeDetails = await Rest.GetTradeDetailsAsync(Security.Account.PracticeAccount, openTrades[0].id); bool detailsRetrieved = tradeDetails.id > 0 && tradeDetails.price > 0 && tradeDetails.units != 0; // Modify an open trade var request = new Dictionary <string, string> { { "stopLoss", "0.4" } }; var modifiedDetails = await Rest.PatchTradeAsync(Security.Account.PracticeAccount, openTrades[0].id, request); bool tradeModified = modifiedDetails.id > 0 && Math.Abs(modifiedDetails.stopLoss - 0.4) < float.Epsilon; if (!await Helpers.IsMarketHalted()) { // close an open trade var closedDetails = await Rest.DeleteTradeAsync(Security.Account.PracticeAccount, openTrades[0].id); bool tradeClosed = closedDetails.id > 0; } else { // } } else { // } } _tradeTestCompleted = true; }
public override async Task MakeRequest() { await InternalMakeRequest(() => Rest.DeleteTradeAsync(AccountDataSource.DefaultDataSource.Id, RequestHelpers.lastTradeId)); }
/// <summary> /// /// </summary> /// <param name="chart"></param> /// <param name="thrust"></param> /// <param name="retracement"></param> protected virtual async void ManageOrder(Chart chart, Thrust thrust) { StrategyTransaction[] transactions = null; StrategyTransaction orderTransaction, fillTransaction, cancelTransaction, exitTransaction; // get transaction collection from db int orderTransactionID = thrust.StrategyTransactionID.GetValueOrDefault(); transactions = await StrategyCaller.Instance().GetStrategyTransactionsCollectionAsync(orderTransactionID); orderTransaction = transactions.FirstOrDefault(t => t.StrategyTransactionID == orderTransactionID); fillTransaction = transactions.FirstOrDefault(t => t.BrokerOrderID != null && t.Type == MACC.Constants.TransactionTypes.OrderFilled); cancelTransaction = transactions.FirstOrDefault(t => t.BrokerOrderID != null && t.Type == MACC.Constants.TransactionTypes.OrderCancel); exitTransaction = transactions.FirstOrDefault(t => t.BrokerTradeID != null && t.Type != MACC.Constants.TransactionTypes.TradeUpdate); bool purgeInActiveThrust = true; if (fillTransaction == null) { if (cancelTransaction != null) { // order cancelled thrust.Active = false; } else { // order open if (!thrust.Active) { // cancel the order // the cancel transaction will be written to the db by the event stream handler await Rest.DeleteOrderAsync(_accountId, Convert.ToInt64(orderTransaction.BrokerTransactionID)); } else { if (thrust.FocusChanged() || (thrust.FillZoneReached() && thrust.TakeProfitZoneReached())) { AddAlgorithmMessage(string.Format("UPDATE ORDER: {0}: FCH-{1}: FZR-{2}: TPR-{3}", orderTransaction.Instrument, thrust.FocusChanged(), thrust.FillZoneReached(), thrust.TakeProfitZoneReached())); UpdateEntryOrder(orderTransaction, chart, thrust); } } } } else { if (exitTransaction == null) { // order filled purgeInActiveThrust = false; FibonacciRetracement retracement = (FibonacciRetracement)thrust.Study; #region get open trade info long tradeId = Convert.ToInt64(fillTransaction.BrokerTransactionID); Frame fillFrame = chart.Frames.LastOrDefault(f => Convert.ToDateTime(f.Bar.time).ToUniversalTime() <= fillTransaction.Time); int fillIndex = chart.Frames.IndexOf(fillFrame); #endregion #region get takeProfitPrice and stopLossPrice int profitWaitPeriods = Parameters.GetInteger("thrustProfitWaitPeriods") ?? 6; thrust.ProfitWindowClosed = (fillIndex + profitWaitPeriods) < chart.Frames.Count; IPriceBar lastBar = chart.Frames.Last().Bar; bool hasProfit = orderTransaction.Side == MACC.Constants.SignalSide.Buy ? lastBar.closeMid > fillTransaction.Price : lastBar.closeMid < fillTransaction.Price; #region stopLossPrice & takeProfitPrice logic // adjust stopLossPrice and takeProfitPrice // if a buy ... // move the stop to the lower of the .500 fib price or [patern lowMid price set by the post-fill price action] // move the profit target to 1 or 2 pips under .618 * (thrust.FocusPrice - [pattern lowMid price set by the post-fill price action]) // if a sell ... // move the stop to the higher of the .500 fib price or [patern highMid price set by the post-fill price action] // move the profit target to 1 or 2 pips above .618 * ([pattern lowMid price set by the post-fill price action] - thrust.FocusPrice) #endregion double?takeProfitPrice = GetAdjustedTakeProfitPrice(chart, thrust.Side, retracement); AddAlgorithmMessage(string.Format("GET SLP: {0}: TPZ-{1}: PWC-{2}: XTP-{3}: CLP-{4}: PFT-{5}", fillTransaction.Instrument, thrust.TakeProfitZoneReached(), thrust.ProfitWindowClosed, retracement.ExtremaPrice, lastBar.closeMid, hasProfit)); double?stopLossPrice = GetAdjustedStopLossPrice(chart, thrust.Side, thrust, hasProfit); #endregion #region kill or update the trade // not profitable && beyond r500 .. kill it if (stopLossPrice.GetValueOrDefault() == -1) { thrust.Active = false; purgeInActiveThrust = true; try { await Rest.DeleteTradeAsync(_accountId, tradeId); } catch (Exception e) { AddAlgorithmMessage(string.Format("CLOSE TRADE {0} Failed: {1}", tradeId, e.Message), true, TraceEventType.Error); } } else { if ((takeProfitPrice ?? thrust.TakeProfitPrice) != thrust.TakeProfitPrice || (stopLossPrice ?? thrust.StopLossPrice) != thrust.StopLossPrice) { AddAlgorithmMessage(string.Format("UPDATE TRADE: {0}: TPZ-{1}: PWC-{2}: XTP-{3}: CLP-{4}: TP-{5}: TTP-{6}: SL-{7}: TSL-{8}", fillTransaction.Instrument, thrust.TakeProfitZoneReached(), thrust.ProfitWindowClosed, retracement.ExtremaPrice, lastBar.closeMid, takeProfitPrice, thrust.TakeProfitPrice, stopLossPrice, thrust.StopLossPrice)); UpdateOpenTrade(thrust, tradeId, takeProfitPrice, stopLossPrice, retracement.LevelPlaces()); } } #endregion } else { // trade closed #region about closed trades // if coll includes a stopLossFilled or takeProfitFilled .. // set thrust.Active = false // this be done server side when the strategyTransaction from the stream is saved // the signal should be found on the server and signal.Active should be set to false // do it here also #endregion thrust.Active = false; } } if (!thrust.Active && purgeInActiveThrust) { await PurgeThrust(chart, thrust); } }