/// <summary> /// /// </summary> /// <param name="chart"></param> /// <param name="side"></param> /// <param name="state"></param> /// <returns></returns> public virtual double?GetAdjustedStopLossPrice(Chart chart, IParameters parameters, IDictionary <string, object> state) { string side; Thrust thrust; bool hasProfit; #region state validation string stateItem = ""; try { stateItem = "side"; side = (string)state[stateItem]; stateItem = "thrust"; thrust = (Thrust)state[stateItem]; stateItem = "hasProfit"; hasProfit = Convert.ToBoolean(state[stateItem]); } catch (Exception ex) { throw new ArgumentException(string.Format("State argument is missing or invalid: {0}.", stateItem), ex); } #endregion #region logic // if a buy ... // move the stop to the lower of the .500 fib price or [patern lowBid price set by the post-fill price action] // if a sell ... // move the stop to the higher of the .500 fib price or [patern highBid price set by the post-fill price action] #endregion FibonacciRetracement retracement = (FibonacciRetracement)thrust.Study; if (!retracement.ExtremaPrice.HasValue) { return(null); } double?stopLossPrice = null; double r500Price = retracement.LevelPrice(FibonacciLevel.R500); double lastPrice = chart.Frames.Last().Bar.closeMid; double extrema500Delta = 0; double extremaPrice = retracement.ExtremaPrice.Value; double extremaTakeProfitDelta = Math.Abs(thrust.TakeProfitPrice.Value - extremaPrice); double takeProfitZoneReachedExtremaCoefficient = parameters.GetDouble("takeProfitZoneReachedExtremaCoefficient") ?? 0.5; if (side == MACC.Constants.SignalSide.Buy) { extrema500Delta = extremaPrice - r500Price; if (hasProfit) { if (thrust.TakeProfitZoneReached()) { stopLossPrice = extremaPrice + (takeProfitZoneReachedExtremaCoefficient * extremaTakeProfitDelta); } else if (extrema500Delta >= 0 && !thrust.ProfitWindowClosed) { stopLossPrice = null; } else if (extrema500Delta >= 0 && thrust.ProfitWindowClosed) // set to extrema or 500? { stopLossPrice = r500Price; } else if (extrema500Delta < 0 && !thrust.ProfitWindowClosed) { stopLossPrice = extremaPrice; } else // extrema500Delta < 0 && profitWindowClosed .. set to r500 { stopLossPrice = r500Price; } } else { if (thrust.TakeProfitZoneReached()) { stopLossPrice = -1; } if (thrust.ProfitWindowClosed && lastPrice > r500Price) { stopLossPrice = r500Price; } else if (thrust.ProfitWindowClosed && lastPrice <= r500Price) { stopLossPrice = -1; // kill trade } else { stopLossPrice = null; } } if (stopLossPrice.HasValue) { // stopLoss should never move down if (stopLossPrice <= thrust.StopLossPrice) { stopLossPrice = null; } else { stopLossPrice -= chart.HistoricBidAskSpread; } } } else { extrema500Delta = r500Price - extremaPrice; if (hasProfit) { if (thrust.TakeProfitZoneReached()) { stopLossPrice = extremaPrice - (takeProfitZoneReachedExtremaCoefficient * extremaTakeProfitDelta); } else if (extrema500Delta >= 0 && !thrust.ProfitWindowClosed) { stopLossPrice = null; } else if (extrema500Delta >= 0 && thrust.ProfitWindowClosed) { stopLossPrice = extremaPrice; } else if (extrema500Delta < 0 && !thrust.ProfitWindowClosed) { stopLossPrice = extremaPrice; } else // extrema500Delta < 0 && profitWindowClosed { stopLossPrice = r500Price; } } else { if (thrust.TakeProfitZoneReached()) { stopLossPrice = -1; } else if (lastPrice < r500Price && thrust.ProfitWindowClosed) { stopLossPrice = r500Price; } else if (lastPrice >= r500Price && thrust.ProfitWindowClosed) { stopLossPrice = -1; // kill trade .. if not already stopped out } else { stopLossPrice = null; } } if (stopLossPrice.HasValue) { // stopLoss should never move up if (stopLossPrice >= thrust.StopLossPrice) { stopLossPrice = null; } else { stopLossPrice += chart.HistoricBidAskSpread; } } } if (stopLossPrice.HasValue) { stopLossPrice = Math.Round(stopLossPrice.Value, retracement.LevelPlaces()); } return(stopLossPrice); }
/// <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); } }