/// <summary> /// /// </summary> /// <param name="side"></param> /// <param name="retracement"></param> /// <returns></returns> protected virtual Tuple <double, double, double> GetOrderPrices(double spread, string side, Thrust thrust) { double entryPrice, stopLossPrice; FibonacciRetracement retracement = (FibonacciRetracement)thrust.Study; if (side == MACC.Constants.SignalSide.Buy) { entryPrice = retracement.LevelPrice(FibonacciLevel.R382) + (0.75 * spread); stopLossPrice = retracement.LevelPrice(FibonacciLevel.R618) - (0.75 * spread); if (thrust.FillZoneReached() && thrust.TakeProfitZoneReached()) { stopLossPrice = retracement.LevelPrice(FibonacciLevel.R500) - (0.75 * spread); } } else { entryPrice = retracement.LevelPrice(FibonacciLevel.R382) - (0.75 * spread); stopLossPrice = retracement.LevelPrice(FibonacciLevel.R618) + (0.75 * spread); if (thrust.FillZoneReached() && thrust.TakeProfitZoneReached()) { stopLossPrice = retracement.LevelPrice(FibonacciLevel.R500) + (0.75 * spread); } } int multiplier = side == MACC.Constants.SignalSide.Buy ? 1 : -1; double r382Price = retracement.LevelPrice(FibonacciLevel.R382); double takeProfitPrice = r382Price + (0.618 * Math.Abs(retracement.FocusPrice - r382Price) * multiplier); var orderPrices = Tuple.Create <double, double, double>(entryPrice, stopLossPrice, takeProfitPrice); return(orderPrices); }
protected virtual Thrust SetThrustFillZoneReached(Chart chart, Thrust thrust) { // if already set, exit. if (thrust.FillZoneReached()) { return(thrust); } #region did price reach the fill zone? List <Frame> afterFocusFrames = chart.Frames.Skip(GetFocusIndex(chart, thrust) + 1).ToList(); Frame fillZoneReachedFrame = afterFocusFrames.FirstOrDefault(frame => { double focusToFillZoneDelta = _fillZoneReachedCoefficient * Math.Abs(thrust.FocusPrice - thrust.EntryPrice.Value); if (thrust.Direction == EPatternDirection.Up) { if (frame.Bar.lowMid <= thrust.FocusPrice - focusToFillZoneDelta) { thrust.FillZoneReachedIndex = chart.Frames.IndexOf(frame); return(true); } } else { if (frame.Bar.highMid >= focusToFillZoneDelta + thrust.FocusPrice) { thrust.FillZoneReachedIndex = chart.Frames.IndexOf(frame); return(true); } } return(false); }); #endregion return(thrust); }
/// <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); } }
protected virtual Thrust SetThrustTakeProfitZoneReached(Chart chart, Thrust thrust) { FibonacciRetracement retracement = thrust.Study as FibonacciRetracement; #region did price reach the takeProfit zone? if (thrust.FillZoneReached()) { double? searchTakeProfitPrice = null; List <Frame> searchFrames = null; if (!thrust.TakeProfitZoneReached()) { searchTakeProfitPrice = thrust.TakeProfitPrice.Value; searchFrames = chart.Frames.Skip(thrust.FillZoneReachedIndex.Value + 1).ToList(); } else { if (retracement.ExtremaChanged()) { int multiplier = thrust.Side == MACC.Constants.SignalSide.Buy ? 1 : -1; double r382Price = retracement.LevelPrice(FibonacciLevel.R382); searchTakeProfitPrice = r382Price + (0.618 * Math.Abs(retracement.FocusPrice - r382Price) * multiplier); searchFrames = chart.Frames.Skip(retracement.ExtremaIndex.Value + 1).ToList(); } } Frame takeProfitZoneReachedFrame = searchFrames.FirstOrDefault(frame => { double extremaToTakeProfitZoneDelta = _takeProfitZoneReachedCoefficient * Math.Abs(searchTakeProfitPrice.Value - retracement.ExtremaPrice.Value); bool takeProfitZoneReached = false; if (thrust.Direction == EPatternDirection.Up) { takeProfitZoneReached = (frame.Bar.highMid >= retracement.ExtremaPrice.Value + extremaToTakeProfitZoneDelta); } else { takeProfitZoneReached = (frame.Bar.lowMid <= retracement.ExtremaPrice.Value - extremaToTakeProfitZoneDelta); } if (takeProfitZoneReached) { thrust.TakeProfitZoneReachedIndex = chart.Frames.IndexOf(frame); thrust.TakeProfitZoneReachedFocusPrice = thrust.FocusPrice; return(true); } return(false); }); } #endregion // is it a breakout? if (thrust.TakeProfitZoneReached()) { double breakoutDelta = thrust.SignalPrice * _focusBreakoutCoefficient * _minThrustPercentRange; if (thrust.Direction == EPatternDirection.Up) { thrust.Breakout = thrust.FocusPrice >= thrust.TakeProfitZoneReachedFocusPrice.Value + breakoutDelta; } else { thrust.Breakout = thrust.FocusPrice <= thrust.TakeProfitZoneReachedFocusPrice.Value - breakoutDelta; } if (thrust.Breakout) { thrust.FillZoneReachedIndex = null; thrust.TakeProfitZoneReachedIndex = null; thrust.TakeProfitZoneReachedFocusPrice = null; } } return(thrust); }