Skip to content

Instantly share code, notes, and snippets.

@gbajaj
Created June 15, 2021 23:20
Show Gist options
  • Save gbajaj/a2eb5ce9e566a821f540702fa1c2859e to your computer and use it in GitHub Desktop.
Save gbajaj/a2eb5ce9e566a821f540702fa1c2859e to your computer and use it in GitHub Desktop.
Strart
#region Using declarations
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Gui;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Gui.SuperDom;
using NinjaTrader.Gui.Tools;
using NinjaTrader.Data;
using NinjaTrader.NinjaScript;
using NinjaTrader.Core.FloatingPoint;
using NinjaTrader.NinjaScript.Indicators;
using NinjaTrader.NinjaScript.DrawingTools;
#endregion
//This namespace holds Strategies in this folder and is required. Do not change it.
namespace NinjaTrader.NinjaScript.Strategies
{
public class YogesthStrat : Strategy
{
private EMA EMAFast;
private EMA EMASlow;
private DateTime currentDate = Core.Globals.MinDate;
private DateTime lastDate = Core.Globals.MinDate;
private Data.SessionIterator sessionIterator;
private bool takeTrades = false;
private double longEntryFillPrice = 0;
private double currentMonthHigh = 0;
private double currentMonthLow = 0;
private double previousMonthHigh = 0;
private double previousMonthLow = 0;
private double currentWeekHigh = 0;
private double currentWeekLow = 0;
private double previousWeekHigh = 0;
private double previousWeekLow = 0;
private double currentDayHigh = 0;
private double currentDayLow = 0;
private double previousDayHigh = 0;
private double previousDayLow = 0;
private int dayDataSeriesIndex = 0;
private int weekDataSeriesIndex = 0;
private int monthDataSeriesIndex = 0;
private int hourDataSeriesIndex = 0;
private bool newMonth = false;
private int firstWeekIdxOfTheMonth = -1;
private int firstDayIdxOfTheWeek = -1;
private int currentMonthBarIndex = 0;
private int currentWeekBarIndex = 0;
private int currentDayBarIndex = 0;
private int previousMonthBarIndex = 0;
private int previousWeekBarIndex = 0;
private int previousDayBarIndex = 0;
private int redBarCounter = 0;
private int unConditionalRedBarCounter = 0;
private int oncePerDay = 0;
private int startBar = 0;
private int endBar = 0;
//private double stopPricePercentage = 0;
private int noTradeTime = 170100;
private Order _entryOrder = null;
private Order stopLongOrder = null;
#region Properties
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name="ContSize", Order=1, GroupName="Parameters")]
public int ContSize
{ get; set; }
[NinjaScriptProperty]
[Range(0, 10)]
[Display(Name="stopPricePercentage", Order=1, GroupName="Parameters")]
public double stopPricePercentage
{ get; set; }
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name="maxredBarCounter", Order=12, GroupName="Parameters")]
public int maxredBarCounter
{ get; set; }
[NinjaScriptProperty]
[Display(Name="isRealTime", Order=1, GroupName="Parameters")]
public bool isRealTime
{ get; set; }
[NinjaScriptProperty]
[Display(Name="enableDebugLog", Order=1, GroupName="Parameters")]
public bool enableDebugLog
{ get; set; }
#endregion
enum StratsBarType{
InsideBarOne,
TwoDown,
TwoUp,
OutsideBarThree
}
protected override void OnStateChange()
{
MyPrint("Current State is: "+ State + "for the strategy: " + Name);
if (State == State.SetDefaults)
{
Description = @"StratsLongTerm";
Name = "StratsLongTerm;";
Calculate = Calculate.OnBarClose;
EntriesPerDirection = 1;
EntryHandling = EntryHandling.AllEntries;
IsExitOnSessionCloseStrategy = false;
ExitOnSessionCloseSeconds = 30;
IsFillLimitOnTouch = false;
MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
OrderFillResolution = OrderFillResolution.Standard;
Slippage = 0;
StartBehavior = StartBehavior.WaitUntilFlatSynchronizeAccount;
TimeInForce = TimeInForce.Gtc;
TraceOrders = false;
RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
StopTargetHandling = StopTargetHandling.PerEntryExecution;
BarsRequiredToTrade = 2; // This is for monthly Bar as long as there is one previous month bar we can trade.
// Disable this property for performance gains in Strategy Analyzer optimizations
// See the Help Guide for additional information
IsInstantiatedOnEachOptimizationIteration = true;
ContSize = 1;
noTradeTime = 170100;
stopPricePercentage = 1;
isRealTime = false;
enableDebugLog = false;
maxredBarCounter = 3;
PrintTo = PrintTo.OutputTab2;
}
else if (State == State.Configure)
{
ClearOutputWindow();
AddDataSeries(BarsPeriodType.Day, 1);
AddDataSeries(BarsPeriodType.Week, 1);
AddDataSeries(BarsPeriodType.Month, 1);
hourDataSeriesIndex = 0;
dayDataSeriesIndex = 1;
weekDataSeriesIndex = 2;
monthDataSeriesIndex = 3;
RealtimeErrorHandling = RealtimeErrorHandling.IgnoreAllErrors;
}
else if (State == State.Historical) {
// AddCustomControls();
}
else if (State == State.DataLoaded) {
MyPrint("Start date and time for the chart is: " + Time[0].Date.ToLongDateString() + " " + ToTime(Time[0]));
MyPrint ("Bar Type" + BarsPeriod.BarsPeriodType);
MyPrint ("Bar Period Type " + BarsPeriod.Value + " " + BarsPeriod.Value2);
MyPrint ("Base bars period Type " + BarsPeriod.BaseBarsPeriodType);
MyPrint ("Base bars period Value " + BarsPeriod.BaseBarsPeriodValue);
} else if (State == State.Terminated) {
stopPricePercentage = 0;
}
}
protected override void OnBarUpdate()
{
if (isRealTime == true){
if (State != State.Realtime)
return;
}
if (BarsInProgress != 0)
return;
if (IsResetOnNewTradingDays[BarsInProgress] == false){
Print(DateTime.Now + ": Break At EOD is set to FALSE, set it to TRUE and restart the strategy: " + Name);
return;
}
// 1st Bar for given time period is -1, 2nd bar is 0 and so on so forth
// Check for month bar and all we need one month bar to trade
if ((CurrentBars[monthDataSeriesIndex] < BarsRequiredToTrade )){
//MyPrint("Don't have sufficient bar to trade now on data series Month: " + + CurrentBars[monthDataSeriesIndex] + " " + CurrentBars[weekDataSeriesIndex] + " " + CurrentBars[dayDataSeriesIndex]);
return;
}
else{
//MyPrint("have sufficient bar to trade now on data series Month: " + CurrentBars[monthDataSeriesIndex] + " " + CurrentBars[weekDataSeriesIndex] + " " + CurrentBars[dayDataSeriesIndex] );
//MyPrint ("Time of the bar: " + Time[0]);
//MyPrint("Previous Month: " + Times[monthDataSeriesIndex][1].Month + " Close: " + Closes[monthDataSeriesIndex][1] + " Previous Month Open " + Opens[monthDataSeriesIndex][1]);
//MyPrint("Current Month: " + Times[monthDataSeriesIndex][0].Month + " High: " + Highs[monthDataSeriesIndex][0] + " Current Close: " + Close[0]);
//MyPrint ("Current Week Index: " + CurrentBars[weekDataSeriesIndex]);
previousMonthHigh = Highs[monthDataSeriesIndex][0];
previousMonthLow = Lows[monthDataSeriesIndex][0];
previousWeekHigh = Highs[weekDataSeriesIndex][0];
previousWeekLow = Lows[weekDataSeriesIndex][0];
//currentWeekHigh = Highs[weekDataSeriesIndex][0];
//currentWeekLow = Lows[weekDataSeriesIndex][0];
previousDayHigh = Highs[dayDataSeriesIndex][0];
previousDayLow = Lows[dayDataSeriesIndex][0];
//currentDayHigh = Highs[dayDataSeriesIndex][0];
//currentDayLow = Lows[dayDataSeriesIndex][0];
if(Time[0].Month != Time[1].Month){
MyPrint ("NEW MONTH STARTED");
firstWeekIdxOfTheMonth = CurrentBars[weekDataSeriesIndex];
newMonth = true;
currentMonthHigh = 0; //Highs[weekDataSeriesIndex][0];
currentMonthLow = Lows[weekDataSeriesIndex][0];
}
if(currentWeekBarIndex != CurrentBars[weekDataSeriesIndex]){
firstDayIdxOfTheWeek = CurrentBars[dayDataSeriesIndex];
previousWeekBarIndex = currentWeekBarIndex;
currentWeekBarIndex = CurrentBars[weekDataSeriesIndex];
currentWeekHigh = 0;
currentWeekLow = Lows[dayDataSeriesIndex][0];
}
}
// if the last month was red
//MyPrint ("Current Close: " + Closes[hourDataSeriesIndex][0] + "Current High: " + Highs[hourDataSeriesIndex][0] + " CurrentMonthHighBefore this bar close: " + currentMonthHigh);
//MyPrint ("Current Low: " + Lows[hourDataSeriesIndex][0] + " CurrentMonthLowBefore this bar close: " + currentMonthLow);
//MyPrint ("Previous Month open: " + Opens[monthDataSeriesIndex][0] + "Previous Month Close: " + Closes[monthDataSeriesIndex][0]);
ContSize = (int) (50000/GetCurrentBid(0));
// ENTER LONG
if(_entryOrder == null){
if(Opens[monthDataSeriesIndex][0] > Closes[monthDataSeriesIndex][0]) { // last month was red
if (CurrentBars[weekDataSeriesIndex] > firstWeekIdxOfTheMonth){
if(Closes[hourDataSeriesIndex][0] > currentMonthHigh){
EnterLong(ContSize, "Long");
}else{
MyPrint ("Entered Long Limit");
//EnterLongLimit(0,false,ContSize,currentMonthHigh + 0.25, "Long");
}
}
}
/*else if (Opens[weekDataSeriesIndex][0] > Closes[weekDataSeriesIndex][0]){ // last week was red
if(Closes[hourDataSeriesIndex][0] > currentWeekHigh && CurrentBars[dayDataSeriesIndex] > firstDayIdxOfTheWeek){
EnterLong(ContSize, "Long");
}
}
else if (Opens[dayDataSeriesIndex][0] > Closes[dayDataSeriesIndex][0]){ // last week was red
if(Closes[hourDataSeriesIndex][0] > previousDayHigh){
EnterLong(ContSize, "Long");
}
}*/
else if (Closes[hourDataSeriesIndex][0] > previousMonthHigh ){
EnterLong(ContSize, "Long");
}
}
// EXIT LONG
else if (_entryOrder != null){
if(Opens[dayDataSeriesIndex][0] > Closes[dayDataSeriesIndex][0]
&& stratsBarType(dayDataSeriesIndex) == StratsBarType.TwoDown
&& Opens[weekDataSeriesIndex][0] > Closes[weekDataSeriesIndex][0]
&& stratsBarType(weekDataSeriesIndex) == StratsBarType.TwoUp )
redBarCounter = redBarCounter + 1;
else
redBarCounter = 0;
if(Opens[weekDataSeriesIndex][0] > Closes[weekDataSeriesIndex][0]
//&& stratsBarType(dayDataSeriesIndex) == StratsBarType.TwoDown
&& Opens[weekDataSeriesIndex][1] > Closes[weekDataSeriesIndex][1] )
//&& stratsBarType(weekDataSeriesIndex) == StratsBarType.TwoDown )
unConditionalRedBarCounter = unConditionalRedBarCounter + 1;
else
unConditionalRedBarCounter = 0;
if((Lows[hourDataSeriesIndex][0] < currentMonthLow &&
CurrentBars[weekDataSeriesIndex] > firstWeekIdxOfTheMonth)) {
//|| (Opens[monthDataSeriesIndex][0] > Closes[monthDataSeriesIndex][0] && Lows[hourDataSeriesIndex][0] < previousMonthLow)// && CurrentBars[weekDataSeriesIndex] == firstWeekIdxOfTheMonth)
//|| (Opens[weekDataSeriesIndex][0] > Closes[weekDataSeriesIndex][0] && Lows[hourDataSeriesIndex][0] < previousWeekLow)
//|| (Lows[hourDataSeriesIndex][0] < previousMonthLow && CurrentBars[weekDataSeriesIndex] == firstWeekIdxOfTheMonth && Lows[hourDataSeriesIndex][0] < currentMonthLow)
//MyPrint ("Lows[hourDataSeriesIndex][0]: " + Lows[hourDataSeriesIndex][0] + " currentMonthLow: " + currentMonthLow);
ExitLong("ExitLong", "Long");
}
else if (redBarCounter >= 5){
MyPrint ("Exiting because of maxredBarCounter");
ExitLong("ExitLong", "Long");
}
else if (Opens[weekDataSeriesIndex][0] > Closes[weekDataSeriesIndex][0] &&
Lows[hourDataSeriesIndex][0] < previousWeekLow - 10 && stratsBarType(weekDataSeriesIndex) == StratsBarType.OutsideBarThree
){
//ExitLong("ExitLong", "Long");
}
// this logic reduces the drawdown from 99K to 90 K but also reduces the profit from 1.6M to 1.3M from 2009 - 2021
/*else if (Opens[weekDataSeriesIndex][0] > Closes[weekDataSeriesIndex][0] &&
Lows[hourDataSeriesIndex][0] < currentWeekLow &&
CurrentBars[dayDataSeriesIndex] > firstDayIdxOfTheWeek){
ExitLong("ExitLong", "Long");
}*/
//else if (Closes[dayDataSeriesIndex][0] < EMA(Closes[dayDataSeriesIndex], emaPeriod)[0] && Opens[monthDataSeriesIndex][0] > Closes[monthDataSeriesIndex][0]) {
//ExitLong("ExitLong", "Long");
//}
}
if(Highs[hourDataSeriesIndex][0] > currentMonthHigh){
currentMonthHigh = Highs[hourDataSeriesIndex][0];
}
if(Lows[hourDataSeriesIndex][0] < currentMonthLow){
currentMonthLow = Lows[hourDataSeriesIndex][0];
}
if(Highs[hourDataSeriesIndex][0] > currentWeekHigh){
currentWeekHigh = Highs[hourDataSeriesIndex][0];
}
if(Lows[hourDataSeriesIndex][0] < currentWeekLow){
currentWeekLow = Lows[hourDataSeriesIndex][0];
}
//MyPrint("Current month high after bar close: " + currentMonthHigh + " month low: " + currentMonthLow);
/*if(PriorDayOHLC().PriorHigh[0] == 0){
MyPrint("Prior Day High not avaialble yet " + Time[0].Date.ToLongDateString() + " " + ToTime(Time[0]));
return;
}
setAllTheVariablesRequireForTrading();
takeActionIfMarketPositionIsNotFlat();
setLongAndShortOrderCondition();
enterLong();
enterShort();*/
}
//def insidebar1 = (H[1] < H[2] and L[1] > L[2]) or (H[1] == H[2] and L[1] > L[2]) or (H[1] < H[2] and L[1] == L[2]) or (H[1] == H[2] and L[1] == L[2]);
//def outsidebar1 = H[1] > H[2] and L[1] < L[2];
//def twoup1 = H[1] > H[2] and L[1] >= L[2];
//def twodown1 = H[1] <= H[2] and L[1] < L[2];
private StratsBarType stratsBarType(int dataSeriesIndex){
if(Highs[dataSeriesIndex][0] <= Highs[dataSeriesIndex][1] && Lows[dataSeriesIndex][0] >= Lows[dataSeriesIndex][1]){
return StratsBarType.InsideBarOne;
}
else if(Highs[dataSeriesIndex][0] > Highs[dataSeriesIndex][1] && Lows[dataSeriesIndex][0] < Lows[dataSeriesIndex][1]){
return StratsBarType.OutsideBarThree;
}
else if (Highs[dataSeriesIndex][0] > Highs[dataSeriesIndex][1] && Lows[dataSeriesIndex][0] >= Lows[dataSeriesIndex][1]){
return StratsBarType.TwoUp;
}
else if (Highs[dataSeriesIndex][0] <= Highs[dataSeriesIndex][1] && Lows[dataSeriesIndex][0] < Lows[dataSeriesIndex][1]){
return StratsBarType.TwoDown;
}
else{ // this will never executed
return StratsBarType.InsideBarOne;
}
}
private void MyPrint(String str){
if(enableDebugLog == true){
Print(DateTime.Now + ": " + str);
}
}
/*private void takeActionIfMarketPositionIsNotFlat (){
if (Position.MarketPosition == MarketPosition.Long) {
if (stopLongOrder == null) {
// Stop is rejected. Handle here
MyPrint ("stopPricePercentage in OBU, Rejected earlier, Retryring with market order ");
ExitLong("ExitLong", "Long");
}else{
if ((GetCurrentBid(0) >= breakEvenPrice) && (breakEvenPrice !=0)) {
ChangeOrder(stopLongOrder, Position.Quantity, 0, stopMovePrice);
}
}
}
else if (Position.MarketPosition == MarketPosition.Short) {
if (stopShortOrder == null) {
// Stop is rejected. Handle here
MyPrint ("stopPricePercentage in OBU, Rejected earlier, Retryring with market order ");
ExitShort("ExitShort", "Short");
} else{
if ((GetCurrentBid(0) <= breakEvenPrice) && (breakEvenPrice !=0)) {
ChangeOrder(stopShortOrder, Position.Quantity, 0, stopMovePrice);
}
}
}
}
private void setAllTheVariablesRequireForTrading(){
// No trades are taken between 1:15 PM and 3 PM
if ((ToTime(Time[0]) > 131500) && (ToTime(Time[0]) < 150000)) {
oncePerDay = 0;
}
if (Bars.BarsSinceNewTradingDay == 0) {
MyPrint ("NEW DAY ============================================== " + Time[0].Date.ToLongDateString() + " " + Time[0].Hour + "Hr");
takeTrades = false;
} else
takeTrades = true;
if ((Time[0].DayOfWeek == DayOfWeek.Sunday) && (ToTime(Time[0]) < noTradeTime))
//takeTrades = false;
if(priorDayHi == 0){
MyPrint(" Previous Hi: " + priorDayHi + " Previous Lo: " + priorDayLow );
}
if (overNightHi == 0) {
if((ToTime(Time[0]) > 063000) && (ToTime(Time[0]) <= 145900)) {
MyPrint ("Time between 6:30AM and 3:00 PM");
MyPrint(" Previous Hi: " + priorDayHi + " Previous Lo: " + priorDayLow );
MyPrint("OverNightHI : " + overNightHi + " OverNightLow : " + overNightLow );
startBar = Bars.GetBar(new DateTime(Time[0].Year, Time[0].Month, Time[0].Day, 0, 0, 0));
endBar = Bars.GetBar(new DateTime(Time[0].Year, Time[0].Month, Time[0].Day, 06, 30, 0));
overNightHi = MAX(High, endBar - startBar + 1)[CurrentBar - endBar];
overNightLow = MIN(Low, endBar - startBar + 1)[CurrentBar - endBar];
startBar = Bars.GetBar(new DateTime(Time[0].Year, Time[0].Month, Time[0].Day-1, 15, 0, 0));
endBar = Bars.GetBar(new DateTime(Time[0].Year, Time[0].Month, Time[0].Day-1, 23, 59, 59));
overNightHi = Math.Max(overNightHi, MAX(High, endBar - startBar + 1)[CurrentBar - endBar]);
overNightLow = Math.Min(overNightLow, MIN(Low, endBar - startBar + 1)[CurrentBar - endBar]);
RemoveDrawObject("OverNightHI");
RemoveDrawObject("OverNightLow");
Draw.HorizontalLine(this, ("OverNightHI"), overNightHi, Brushes.DarkBlue, DashStyleHelper.Dash, 2, true);
Draw.HorizontalLine(this, ("OverNightLow"), overNightLow, Brushes.DarkGray, DashStyleHelper.Dash, 2, true);
}
else {
MyPrint ("Time between 3:00 PM and 6:30 AM");
MyPrint(" Previous Hi: " + priorDayHi + " Previous Lo: " + priorDayLow );
MyPrint("OverNightHI : " + overNightHi + " OverNightLow : " + overNightLow );
startBar = Bars.GetBar(new DateTime(Time[0].Year, Time[0].Month, Time[0].Day, 15, 0, 0));
endBar = Bars.GetBar(new DateTime(Time[0].Year, Time[0].Month, Time[0].Day, Time[0].Hour, Time[0].Minute, 0));
overNightHi = MAX(High, Bars.BarsSinceNewTradingDay + 1)[CurrentBar - endBar];
overNightLow = MIN(Low, Bars.BarsSinceNewTradingDay + 1)[CurrentBar - endBar];
RemoveDrawObject("OverNightHI");
RemoveDrawObject("OverNightLow");
Draw.HorizontalLine(this, ("OverNightHI"), overNightHi, Brushes.DarkBlue, DashStyleHelper.Dash, 2, true);
Draw.HorizontalLine(this, ("OverNightLow"), overNightLow, Brushes.DarkGray, DashStyleHelper.Dash, 2, true);
}
Draw.HorizontalLine(this, "PrevDayHI", priorDayHi, Brushes.DarkGreen, DashStyleHelper.Solid, 2, true);
Draw.HorizontalLine(this, "PrevDayLow", priorDayLow, Brushes.DarkRed, DashStyleHelper.Solid, 2, true);
} else {
if(((ToTime(Time[0]) > 150000) && (ToTime(Time[0]) <= 235959)) ||
((ToTime(Time[0]) >= 000000) && (ToTime(Time[0]) < 063000)))
{
if(High[0] > overNightHi || Low[0] < overNightLow){
overNightHi = Math.Max(overNightHi, High[0]);
overNightLow = Math.Min(overNightLow, Low[0]);
MyPrint("OverNightHI : " + overNightHi + " OverNightLow : " + overNightLow );
RemoveDrawObject("OverNightHI");
RemoveDrawObject("OverNightLow");
Draw.HorizontalLine(this, ("OverNightHI"), overNightHi, Brushes.DarkBlue, DashStyleHelper.Dash, 2, true);
Draw.HorizontalLine(this, ("OverNightLow"), overNightLow, Brushes.DarkGray, DashStyleHelper.Dash, 2, true);
}
}
}
if((ToTime(Time[0]) > 063100) && (ToTime(Time[0]) < 131500)) {
if (oncePerDay == 0) {
oncePerDay = 1;
}
}
}
*/
protected override void OnExecutionUpdate(Execution execution, string executionId, double price,
int quantity, MarketPosition marketPosition, string orderId, DateTime time)
{
MyPrint("Execution Order Name " + execution.Order.Name + " and Size " + quantity + " and Price " + price);
if (execution.Order.Name == "Long" && (execution.Order.OrderState == OrderState.Filled)) {
_entryOrder = execution.Order;
if ((_entryOrder != null) && (execution.Order.Filled == execution.Order.Quantity)) {
MyPrint ("Entered Long @ " + _entryOrder.AverageFillPrice + " @ Time: " + Time[0].Date.ToShortDateString() + " " + ToTime(Time[0]));
Draw.ArrowUp(this, "EnteringLong"+_entryOrder.Id, false, 0, (Low[0] + (-5 * TickSize)) , Brushes.Lime);
// Stop only when we are in full position
if ((EntriesPerDirection * ContSize) == Position.Quantity){
//MyPrint ("Placing a stop order for the price: " + (stopPricePercentage - TickSize) + " with TickSize: " + TickSize);
//ExitLongStopMarket(0, true, Position.Quantity, _entryOrder.AverageFillPrice * (100 - stopPricePercentage)/100, "StopLong", "Long");
}
//TradeBias = 0;
}
}
/*if ((execution.Order.Name == "StopLong") && (stopLongOrder != null) && (execution.Order == stopLongOrder)) {
if (execution.Order.Quantity == execution.Order.Filled){
MyPrint ("Stop Long @ " + _entryOrder.AverageFillPrice + " @ Time: " + Time[0].Date.ToShortDateString() + " " + ToTime(Time[0]));
Draw.ArrowDown(this, "Stopped"+_entryOrder.Id, false, 0, (High[0] + (5 * TickSize)) , Brushes.Red);
ticksAchieved = ticksAchieved + ((execution.Order.AverageFillPrice - _entryOrder.AverageFillPrice) * 4 * execution.Order.Quantity);
if (execution.Order.Quantity == ContSize)
lossTradeCount = lossTradeCount + 1;
_entryOrder = null;
stopLongOrder = null;
stopPricePercentage = 0;
breakEvenPrice = 0;
activePrice = 0;
TradeBias = 0;
// Cancel outstanding orders, if any
if (exitLongLimitBEOrder != null) {
CancelOrder(exitLongLimitBEOrder);
}
if (exitLongLimitOrder != null) {
CancelOrder(exitLongLimitOrder);
}
}
}*/
if ((execution.Order.Name == "ExitLong") ) {
if (execution.Order.Quantity == execution.Order.Filled){
MyPrint ("Exit Long @ " + _entryOrder.AverageFillPrice + " @ Time: " + Time[0].Date.ToShortDateString() + " " + ToTime(Time[0]));
Draw.ArrowDown(this, "TargetAchieved"+_entryOrder.Id, false, 0, (High[0] + (5 * TickSize)) , Brushes.Blue);
_entryOrder = null;
if (stopLongOrder != null) {
CancelOrder(stopLongOrder);
}
}
}
if (execution.Order.Name == "Exit on session close") {
if (execution.Order.Quantity == execution.Order.Filled){
MyPrint ("Exit on Session Close is executed @ " + _entryOrder.AverageFillPrice + " @ Time: " + Time[0].Date.ToShortDateString() + " " + ToTime(Time[0]));
//MyPrint("Exit on Session Close is executed with Quantity " + execution.Order.Filled + " Stop at this time is " + stopPricePercentage);
_entryOrder = null;
}
}
}
/*
protected override void OnOrderUpdate(Order order, double limitPrice, double stPrice, int quantity,
int filled, double averageFillPrice, OrderState orderState,
DateTime time, ErrorCode error, string comment) {
MyPrint("Order " + order.Name + " is updated with state " + orderState + " Quantity " + quantity + " Error Code " + error);
if ((order.Name == "StopShort") && (orderState != OrderState.Rejected)) {
// MyPrint("ShortStop is Accepted ");
stopShortOrder = order;
}
if ((order.Name == "StopShort") && (orderState == OrderState.Rejected)) {
// MyPrint("StopShort Order Rejected. Setting to null");
stopShortOrder = null;
// OnBarUpdate should take care of this
}
if ((order.Name == "ExitBEShort") && (orderState != OrderState.Rejected)) {
//MyPrint("ExitBEShort is Accepted ");
exitShortLimitBEOrder = order;
}
if ((order.Name == "ExitShort") && (orderState != OrderState.Rejected)) {
// MyPrint("ExitShort is Accepted ");
exitShortLimitOrder = order;
}
if ((order.Name == "StopLong") && (orderState != OrderState.Rejected))
stopLongOrder = order;
if ((order.Name == "ExitBELong") && (orderState != OrderState.Rejected))
exitLongLimitBEOrder = order;
if ((order.Name == "ExitLong") && (orderState != OrderState.Rejected))
exitLongLimitOrder = order;
if ((order.Name == "stopLong" ) && (order.OrderState == OrderState.Rejected)) {
MyPrint("StopLong Order Rejected");
stopLongOrder = null;
// OnBarUpdate should take care of this
}
if (order.OrderState == OrderState.Cancelled) {
if (order.Name == "StopLong") {
// MyPrint("Stops Cancelled");
stopLongOrder = null;
stopPricePercentage = 0;
activePrice = 0;
TradeBias = 0;
}
if (order.Name == "ExitBELong") {
// MyPrint("ExitBELong Cancelled");
exitLongLimitBEOrder = null;
}
if (order.Name == "ExitLong") {
//MyPrint("ExitLong Cancelled");
exitLongLimitOrder = null;
activePrice = 0;
TradeBias = 0;
}
if (order.Name == "StopShort") {
// MyPrint("Stops Cancelled");
stopShortOrder = null;
stopPricePercentage = 0;
activePrice = 0;
TradeBias = 0;
}
if (order.Name == "ExitBEShort") {
// MyPrint("ExitBEShort Cancelled");
exitShortLimitBEOrder = null;
}
if (order.Name == "ExitShort") {
//MyPrint("ExitShort Cancelled");
exitShortLimitOrder = null;
activePrice = 0;
TradeBias = 0;
}
}
}*/
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment