Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jpfl/984a70997abaf3494f3264385b9d9f92 to your computer and use it in GitHub Desktop.
Save jpfl/984a70997abaf3494f3264385b9d9f92 to your computer and use it in GitHub Desktop.
csharptopy
//
// The original code in this file was created by Quagensia® N Edition.
//
// Please visit www.quagensia.com and download the Quagensia N Edition free trial which will empower you to:
//
// 1. Create your own algorithmic trading strategies without code by simply
// clicking choices on a screen as you would verbally describe your trading ideas.
//
// 2. Get no-code trading strategies that you can use as-is and customize without code.
//
// By using this code, you acknowledge that you have read and agree to the Quagensia, Inc. Terms of Service located at
// https://www.quagensia.com/company/terms-of-service and the Quagensia Desktop Application End-User
// License Agreement (EULA) located at https://www.quagensia.com/company/quagensia-desktop-application-eula.
//
// This paid-only content is exclusively for Quagensia N Edition paid
// license holders.
//
// The author and copyright holder of this Quagensia N Edition Strategy,
// or another user, has set it to be viewable, editable, and usable from
// within Quagensia N Edition exclusively by users who, like you, have a
// valid paid Quagensia N Edition license.
//
// Unless you are the copyright holder of this Quagensia N Edition
// Strategy or have permission from the copyright holder, it is a
// violation both of our Terms of Service and the Quagensia Desktop
// Application End-User License Agreement (EULA) to 1) manually re-create
// this Quagensia N Edition Strategy and save it without also setting the
// "Only Users with Valid Paid Quagensia N Edition Licenses Can View,
// Edit, and Use This Quagensia N Edition Strategy" field's value to
// "True" by clicking on the "View Advanced Permissions Fields" link in
// the "Strategy Summary" section of the new Quagensia N Edition Strategy
// then clicking on the appropriate link to set the field's value to
// "True", 2) share screenshots containing substantial portions of this
// Quagensia N Edition Strategy with users that do not have valid paid
// Quagensia N Edition licenses, 3) share the code that Quagensia N
// Edition generates for this Quagensia N Edition Strategy with users
// that do not have valid paid Quagensia N Edition licenses, or 4) share
// a substantial portion of this Quagensia N Edition Strategy in any way
// with users that do not have valid paid Quagensia N Edition licenses.
//
// Thank you very much from all of us at Quagensia both for purchasing a
// Quagensia N Edition license and for sharing paid-only content
// exclusively with other users who, like you, have a paid Quagensia N
// Edition license. This helps us keep our edge and helps you keep your
// edge.
//
// If you make changes to this code file outside of Quagensia N Edition and then regenerate and copy the code for this Quagensia N Edition Strategy
// from Quagensia N Edition to this file's location on disk, be aware that your changes made outside of Quagensia N Edition will be lost.
//
// Quagensia® N Edition is a product of Quagensia, Inc., a company which has no affiliation with NinjaTrader, LLC.
// Neither NinjaTrader, LLC nor have any of its affiliates endorsed, recommended, or approved Quagensia® N Edition.
//
// NinjaTrader® and NinjaScript® are registered trademarks of NinjaTrader, LLC.
//
// Under the terms of the Quagensia End-User License Agreement (EULA), neither this
// sentence nor any part of the message above may be removed or altered in any way.
//
// Algo Type: NinjaTrader® Strategy
//
// Strategy Name: Δ (2)
//
// Description & Notes:
// VERSION
//
// FIB weight MA entry
// Raw indicator print
// Real Time Logger
//
#region Using Declarations
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
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;
using System.Reflection;
using System.Globalization;
#endregion
// This namespace holds strategies in this folder and is required. Do not change it.
namespace NinjaTrader.NinjaScript.Strategies
{
public class Δ_2 : Strategy
{
private bool _ccishortripe;
private bool _ccirangeshortok;
private bool _awesomeshortripe;
private bool _rsishortripe;
private bool _rsirangeshortok;
private bool _dynamicmomentumshortripe;
private bool _dynamicmomentumrangeshortok;
// ________________________________________________________
//
// NAME OF STRATEGY
// ________________________________________________________
//
private string _STRATEGYNAME;
private ZLEMA _zlema8;
private MAEnvelopes _14pmaenvelopes;
private SMA _1000sma;
private bool _macddiffripe;
private bool _macdcrossup;
private bool _macdcrossdown;
private bool _macddefaultfilterripe;
private bool _macdlongripe;
private bool _macdshortripe;
private ZLEMA _62zlema;
private EMA _382ema;
private EMA _236ema;
private VOL _volume;
private CP_Plus _cpplusday;
private Aroon _aroon;
private DM _directionalmovement;
private VolumeUpDown _volumeupdown;
private LinRegIntercept _linregintercept;
private DisparityIndex _disparityindex;
private List<string> _entrysignalindicators;
private ATR _atrfilter;
private bool _atrrangeok;
private bool _atrripe;
// An array containing the first numbers in the Fibonacci sequence,
// starting with 1, 2, 3, 5 rather than 0, 1, 1, 2, 3, 5.
//
// The Fibonacci numbers in this array are used as the weightings for a
// "Fibonacci-weighted moving average", where the largest Fibonacci
// number stored in this array is used to weight the current bar's close
// price. The weightings applied to previous bars get successively lower.
private long[] _fibweightings;
// An Editable Time Series containing a custom-calculated
// "Fibonacci-weighted moving average".
private Series<double> _fibweightedma;
// An Editable Time Series containing a smoothed version of a
// custom-calculated "Fibonacci-weighted moving average", where the
// smoothing is done by calculating the simple moving average of the
// Fibonacci-weighted moving average.
private Series<double> _smoothedfibweightedma;
private int _fibnumberbeforepreviousonetempvar;
private int _previousfibnumbertempvar;
private int _nextfibnumbertempvar;
private int _counterforlooptempvar;
private long _sumoffibnumberweightings;
private double _fibweightedsumofrecentvaluestempvar;
private bool _fibweightmaInitialized;
private bool _fibweightexitmashortripe;
private bool _fibweightexitmalongripe;
private bool _fibweightmalongripe;
private bool _fibweightmashortripe;
private MACD _macd;
private DateTime _datetimecsv;
private ADX _adx;
private bool _conditionsripe;
private long _sequence;
private bool _initialised;
private bool _alltimesripe;
private bool _time1;
private bool _time2;
private bool _time3;
private bool _daysofweekripe;
private bool _flatstateripe;
private int _dayofweek;
private Vortex _vortex;
private PFE _polarizedfractalefficency;
private List<string> _indicatorlistprint;
private bool _indicatorprintflag;
private string _twoplumsforone;
private WilliamsR _williamsr;
private Momentum _momentum;
private CCI _cci;
private RSI _rsi;
private TRIX _trix;
private ChaikinOscillator _Chaikin;
private THE_VWAP_INTRADAY _vwap;
private FisherTransform _fishertransform;
private ZigZag _zigzag;
private ZLEMA _233zlema;
private EMA _618ema;
private SMA sma;
private VROC _vroc;
private RVI _rvi;
private MFI _mfi;
private ADL _accumulation_distribution;
private MAEnvelopes _maenvelopes;
private LinRegSlope _linregslope;
private RSquared _rsquared;
private OBV _obv;
private RIND _rind;
private Bollinger _500pbolli;
private ZLEMA _zlema13;
private string _filepathandname;
private string _filepathandparameters;
private WisemanAwesomeOscillator _wisemannawesome;
private StochasticsFast _stochfast;
private CMO _cmo;
private RSS _rss;
private APZ _apz;
private LinReg _linreg;
private DMIndex _dynamicmomentum;
private GannLines _gannlines;
private double _vwapdist;
private double _bolli500dist;
private bool _vwapdistripe;
private bool _vwappercentdistok;
private bool _bolli500distok;
private bool _bolli500distripe;
private List<SessionIterator> QS_SessionIterators;
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = "VERSION FIB weight MA entry Raw indicator print Real Time Logger ";
Name = "Δ_2";
Calculate = Calculate.OnBarClose;
DefaultQuantity = 1;
EntriesPerDirection = 1;
EntryHandling = EntryHandling.UniqueEntries;
IsExitOnSessionCloseStrategy = true;
ExitOnSessionCloseSeconds = 3600;
IsFillLimitOnTouch = false;
MaximumBarsLookBack = MaximumBarsLookBack.Infinite;
OrderFillResolution = OrderFillResolution.Standard;
Slippage = 2.0;
IncludeCommission = true;
IsAdoptAccountPositionAware = false;
StartBehavior = StartBehavior.WaitUntilFlat;
TimeInForce = TimeInForce.Gtc;
TraceOrders = true;
RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
StopTargetHandling = StopTargetHandling.PerEntryExecution;
BarsRequiredToTrade = 200;
AllowRemovalOfDrawObjects = false;
IsInstantiatedOnEachOptimizationIteration = !false;
IncludeTradeHistoryInBacktest = !false;
EnableCCI = true;
EnableAwesome = true;
EnableRSI = true;
EnableDynamicMomentum = true;
Sunday = true;
Monday = true;
Tuesday = true;
Wednesday = true;
Thursday = true;
Friday = true;
EnableTimeFilter1 = false;
StartTime1 = (new DateTime(1, 1, 1, 6, 30, 0));
StopTime1 = (new DateTime(1, 1, 1, 8, 30, 0));
EnableTimeFilter2 = false;
StartTime2 = (new DateTime(1, 1, 1, 9, 30, 0));
StopTime2 = (new DateTime(1, 1, 1, 11, 55, 0));
EnableTimeFilter3 = false;
StartTime3 = (new DateTime(1, 1, 1, 14, 0, 0));
StopTime3 = (new DateTime(1, 1, 1, 16, 30, 0));
EnableLong = true;
EnableShort = true;
StayInTradeFlatFirst = false;
EnableLimitOrdersOveridesMarket = false;
EnterLimitOutsideofSignal = false;
TicksAwayFromSignal = 30;
ChartExecutionMark = false;
QS_Brush_For_ExecutionMarkerColour = QS_GetBrush_SolidColor(Color.FromArgb(255, 128, 128, 128));
QTYENTRY1 = 1;
Entry2 = true;
QtyEntry2 = 1;
Entry3 = false;
QtyEntry3 = 1;
Entry4 = false;
QtyEntry4 = 1;
Entry5 = false;
QtyEntry5 = 1;
PSARonAllEntries = false;
AllEntriesSL = 90.0;
PSARSL1 = false;
SL1 = 60.0;
PSARSL2 = false;
SL2 = 120.0;
PSARSL3 = false;
SL3 = 90.0;
PSARSL4 = false;
SL4 = 140.0;
PSARSL5 = false;
SL5 = 160.0;
TP1 = true;
Target1 = 88.0;
TP2 = true;
Target2 = 144.0;
TP3 = true;
Target3 = 166.0;
TP4 = true;
Target4 = 233.0;
TP5 = true;
Target5 = 377.0;
CalculationModeProfitFixedSL = QS_CalculationMode.Ticks;
SimulatedStopFixed = true;
SimulatedStopPSAR = true;
CalculationModePSAR = QS_CalculationMode_ParabolicTrailingStops.Ticks;
PSARAcceleration = 0.02;
PSARMaxAcceleration = 0.2;
PSARAccelerationStep = 0.02;
PrintTradeLog = false;
PrintIndicatorValues = false;
PrintToCSV = false;
FileName = "Test";
EnableDebug = false;
EnableFibWeightMACross = true;
ShowFibWeightMAs = false;
FibWeightMAPeriod = 10;
QS_Brush_For_FibWeightMA = QS_GetBrush_SolidColor(Color.FromArgb(255, 154, 154, 154));
SmoothingSimpleMAPeriod = 20;
QS_Brush_For_SmoothingSimpleMA = QS_GetBrush_SolidColor(Color.FromArgb(255, 69, 69, 69));
ExitonFibCounterCross = false;
EnableMACDCross = false;
ShowMACD = false;
MACDFastEMA = 12;
MACDSlowEMA = 26;
EMASignalLine = 9;
EnableDistancefromVWAP = false;
EnableDistancefromBolli500Mid = false;
ShowCPDay = false;
ShowGannLines = false;
QS_DoCustomDrawingAndPainting_UserPreference = true;
QS_DoPrintToOutputWindow_UserPreference = true;
}
else if (State == State.Configure)
{
if (QS_Brushes_SolidColor_System == null)
QS_Populate_Brushes_SolidColor_System();
_ccishortripe = false;
_ccirangeshortok = false;
_awesomeshortripe = false;
_rsishortripe = false;
_rsirangeshortok = false;
_dynamicmomentumshortripe = false;
_dynamicmomentumrangeshortok = false;
_STRATEGYNAME = "Δ";
_macddiffripe = false;
_macdcrossup = false;
_macdcrossdown = false;
_macddefaultfilterripe = false;
_macdlongripe = false;
_macdshortripe = false;
_entrysignalindicators = new List<string>();
_atrrangeok = false;
_atrripe = false;
_fibweightings = new long[1];
QS_InitializeArray(ref _fibweightings, 0);
_fibnumberbeforepreviousonetempvar = 0;
_previousfibnumbertempvar = 1;
_nextfibnumbertempvar = 1;
_counterforlooptempvar = 0;
_sumoffibnumberweightings = 0;
_fibweightedsumofrecentvaluestempvar = 0.0;
_fibweightmaInitialized = false;
_fibweightexitmashortripe = false;
_fibweightexitmalongripe = false;
_fibweightmalongripe = false;
_fibweightmashortripe = false;
_datetimecsv = DateTime.Now;
_conditionsripe = false;
_sequence = -1;
_initialised = false;
_alltimesripe = false;
_time1 = false;
_time2 = false;
_time3 = false;
_daysofweekripe = false;
_flatstateripe = false;
_dayofweek = 0;
_indicatorlistprint = new List<string>();
_indicatorprintflag = false;
_twoplumsforone = "";
_filepathandname = ("C:\\Users\\Administrator\\Documents\\Strategy Output Files\\" + _STRATEGYNAME + "\\" + _datetimecsv.ToString("yyyy-MM-dd_HH-mm") + "__DataStream__" + FileName + ".csv");
_filepathandparameters = ("C:\\Users\\Administrator\\Documents\\Strategy Output Files\\" + _STRATEGYNAME + "\\" + _datetimecsv.ToString("yyyy-MM-dd_HH-mm") + "__Parameters__" + FileName + ".csv");
_vwapdist = 0.00362;
_bolli500dist = 0.007;
_vwapdistripe = false;
_vwappercentdistok = false;
_bolli500distok = false;
_bolli500distripe = false;
// PSAR ALL
if (PSARonAllEntries)
{
SetParabolicStop("", (CalculationMode)(CalculationModePSAR), AllEntriesSL, SimulatedStopPSAR, PSARAcceleration, PSARMaxAcceleration, PSARAccelerationStep);
}
// PSAR INDIVIDUAL
if ((PSARonAllEntries == false))
{
if (PSARSL1)
{
SetParabolicStop("LE1", (CalculationMode)(CalculationModePSAR), SL1, SimulatedStopPSAR, PSARAcceleration, PSARMaxAcceleration, PSARAccelerationStep);
}
if (PSARSL2)
{
SetParabolicStop("LE2", (CalculationMode)(CalculationModePSAR), SL2, SimulatedStopPSAR, PSARAcceleration, PSARMaxAcceleration, PSARAccelerationStep);
}
if (PSARSL3)
{
SetParabolicStop("LE3", (CalculationMode)(CalculationModePSAR), SL3, SimulatedStopPSAR, PSARAcceleration, PSARMaxAcceleration, PSARAccelerationStep);
}
if (PSARSL4)
{
SetParabolicStop("LE4", (CalculationMode)(CalculationModePSAR), SL4, SimulatedStopPSAR, PSARAcceleration, PSARMaxAcceleration, PSARAccelerationStep);
}
if (PSARSL5)
{
SetParabolicStop("LE5", (CalculationMode)(CalculationModePSAR), SL5, SimulatedStopPSAR, PSARAcceleration, PSARMaxAcceleration, PSARAccelerationStep);
}
if (PSARSL1)
{
SetParabolicStop("SE1", (CalculationMode)(CalculationModePSAR), SL1, SimulatedStopPSAR, PSARAcceleration, PSARMaxAcceleration, PSARAccelerationStep);
}
if (PSARSL2)
{
SetParabolicStop("SE2", (CalculationMode)(CalculationModePSAR), SL2, SimulatedStopPSAR, PSARAcceleration, PSARMaxAcceleration, PSARAccelerationStep);
}
if (PSARSL3)
{
SetParabolicStop("SE3", (CalculationMode)(CalculationModePSAR), SL3, SimulatedStopPSAR, PSARAcceleration, PSARMaxAcceleration, PSARAccelerationStep);
}
if (PSARSL4)
{
SetParabolicStop("SE4", (CalculationMode)(CalculationModePSAR), SL4, SimulatedStopPSAR, PSARAcceleration, PSARMaxAcceleration, PSARAccelerationStep);
}
if (PSARSL5)
{
SetParabolicStop("SE5", (CalculationMode)(CalculationModePSAR), SL5, SimulatedStopPSAR, PSARAcceleration, PSARMaxAcceleration, PSARAccelerationStep);
}
}
// FIXED SL
if ((PSARonAllEntries == false))
{
if ((PSARSL1 == false))
{
SetStopLoss("SE1", (CalculationMode)(CalculationModeProfitFixedSL), SL1, SimulatedStopFixed);
}
if ((PSARSL2 == false))
{
SetStopLoss("SE2", (CalculationMode)(CalculationModeProfitFixedSL), SL2, SimulatedStopFixed);
}
if ((PSARSL3 == false))
{
SetStopLoss("SE3", (CalculationMode)(CalculationModeProfitFixedSL), SL3, SimulatedStopFixed);
}
if ((PSARSL4 == false))
{
SetStopLoss("SE4", (CalculationMode)(CalculationModeProfitFixedSL), SL4, SimulatedStopFixed);
}
if ((PSARSL5 == false))
{
SetStopLoss("SE5", (CalculationMode)(CalculationModeProfitFixedSL), SL5, SimulatedStopFixed);
}
if ((PSARSL5 == false))
{
SetStopLoss("LE5", (CalculationMode)(QS_CalculationMode.Ticks), SL5, SimulatedStopFixed);
}
if ((PSARSL4 == false))
{
SetStopLoss("LE4", (CalculationMode)(CalculationModeProfitFixedSL), SL4, SimulatedStopFixed);
}
if ((PSARSL3 == false))
{
SetStopLoss("LE3", (CalculationMode)(QS_CalculationMode.Ticks), SL3, SimulatedStopFixed);
}
if ((PSARSL2 == false))
{
SetStopLoss("LE2", (CalculationMode)(CalculationModeProfitFixedSL), SL2, SimulatedStopFixed);
}
if ((PSARSL1 == false))
{
SetStopLoss("LE1", (CalculationMode)(CalculationModeProfitFixedSL), SL1, SimulatedStopFixed);
}
}
// TARGETS
if (true)
{
if (TP1)
{
SetProfitTarget("LE1", (CalculationMode)(CalculationModeProfitFixedSL), Target1, false);
SetProfitTarget("SE1", (CalculationMode)(CalculationModeProfitFixedSL), Target1, false);
}
if (TP2)
{
SetProfitTarget("LE2", (CalculationMode)(CalculationModeProfitFixedSL), Target2, false);
SetProfitTarget("SE2", (CalculationMode)(CalculationModeProfitFixedSL), Target2, false);
}
if (TP3)
{
SetProfitTarget("LE3", (CalculationMode)(CalculationModeProfitFixedSL), Target3, false);
SetProfitTarget("SE3", (CalculationMode)(CalculationModeProfitFixedSL), Target3, false);
}
if (TP4)
{
SetProfitTarget("LE4", (CalculationMode)(CalculationModeProfitFixedSL), Target4, false);
SetProfitTarget("SE4", (CalculationMode)(CalculationModeProfitFixedSL), Target4, false);
}
if (TP5)
{
SetProfitTarget("LE5", (CalculationMode)(CalculationModeProfitFixedSL), Target5, false);
SetProfitTarget("SE5", (CalculationMode)(CalculationModeProfitFixedSL), Target5, false);
}
}
if (ShowFibWeightMAs)
{
AddPlot(new Stroke(QS_GetBrush_SolidColor(FibWeightMA), DashStyleHelper.Solid, 1), PlotStyle.Line, "_fibweightedma");
}
if (ShowFibWeightMAs)
{
AddPlot(new Stroke(QS_GetBrush_SolidColor(SmoothingSimpleMA), DashStyleHelper.Solid, 2), PlotStyle.Line, "_smoothedfibweightedma");
}
}
else if (State == State.DataLoaded)
{
if (ShowFibWeightMAs)
{
_fibweightedma = Values[QS_GetPlotIndexByName("_fibweightedma")];
}
else
{
_fibweightedma = new Series<double>(this);
}
if (ShowFibWeightMAs)
{
_smoothedfibweightedma = Values[QS_GetPlotIndexByName("_smoothedfibweightedma")];
}
else
{
_smoothedfibweightedma = new Series<double>(this);
}
_zlema8 = ZLEMA(Closes[0], ((int)8));
_14pmaenvelopes = MAEnvelopes(Closes[0], ((double)1.5), ((int)3), ((int)14));
_1000sma = SMA(Closes[0], ((int)1000));
_62zlema = ZLEMA(Closes[0], ((int)62));
_382ema = EMA(Closes[0], ((int)382));
_236ema = EMA(Closes[0], ((int)236));
_volume = VOL(Closes[0]);
_cpplusday = CP_Plus(Closes[0], PivotRange.Daily, HLCCalculationMode.CalcFromIntradayData, ((double)0.0), ((double)0.0), ((double)0.0), ((int)240));
if (ShowCPDay)
{
QS_Indicator_OnInit_Plot_Indicator(ref _cpplusday, true, QS_TrueFalseOrUseDefaultValue.QS_TriStateBoolean_UseDefaultValue, 1);
}
_aroon = Aroon(Closes[0], ((int)14));
_directionalmovement = DM(Closes[0], ((int)14));
_volumeupdown = VolumeUpDown(Closes[0]);
_linregintercept = LinRegIntercept(Closes[0], ((int)14));
_disparityindex = DisparityIndex(Closes[0], ((int)25));
_atrfilter = ATR(Closes[0], ((int)14));
_macd = MACD(Closes[0], MACDFastEMA, MACDSlowEMA, EMASignalLine);
if (ShowMACD)
{
QS_Indicator_OnInit_Plot_Plot(ref _macd, 0, QS_GetBrush_SolidColor(Color.FromArgb(255, 0, 94, 94)), 1, PlotStyle.Line, DashStyleHelper.Solid);
QS_Indicator_OnInit_Plot_Plot(ref _macd, 1, QS_GetBrush_SolidColor(Color.FromArgb(255, 185, 0, 0)), 1, PlotStyle.Line, DashStyleHelper.Solid);
QS_Indicator_OnInit_Plot_Plot(ref _macd, 2, QS_GetBrush_SolidColor(Color.FromArgb(255, 154, 154, 154)), 1, PlotStyle.Line, DashStyleHelper.Solid);
QS_Indicator_OnInit_Plot_Indicator(ref _macd, true, QS_TrueFalseOrUseDefaultValue.QS_TriStateBoolean_UseDefaultValue, 1);
}
_adx = ADX(Closes[0], ((int)14));
_vortex = Vortex(Closes[0], ((int)14));
_polarizedfractalefficency = PFE(Closes[0], ((int)14), ((int)10));
_williamsr = WilliamsR(Closes[0], ((int)14));
_momentum = Momentum(Closes[0], ((int)14));
_cci = CCI(Closes[0], ((int)14));
_rsi = RSI(Closes[0], ((int)14), ((int)3));
_trix = TRIX(Closes[0], ((int)14), ((int)3));
_Chaikin = ChaikinOscillator(Closes[0], ((int)3), ((int)10));
_vwap = THE_VWAP_INTRADAY(Closes[0], ((double)1.0), ((double)2.0), (THE_VWAP_INTRADAY.EnumTimeFrame)(((int)0)), ((double)0.0));
_fishertransform = FisherTransform(Closes[0], ((int)10));
_zigzag = ZigZag(Closes[0], DeviationType.Points, ((double)0.5), false);
_233zlema = ZLEMA(Closes[0], ((int)233));
_618ema = EMA(Closes[0], ((int)618));
sma = SMA(Closes[0], ((int)144));
_vroc = VROC(Closes[0], ((int)14), ((int)3));
_rvi = RVI(Closes[0], ((int)14));
_mfi = MFI(Closes[0], ((int)14));
_accumulation_distribution = ADL(Closes[0]);
_maenvelopes = MAEnvelopes(Closes[0], ((double)1.5), ((int)3), ((int)14));
_linregslope = LinRegSlope(Closes[0], ((int)14));
_rsquared = RSquared(Closes[0], ((int)8));
_obv = OBV(Closes[0]);
_rind = RIND(Closes[0], ((int)3), ((int)10));
_500pbolli = Bollinger(Closes[0], ((double)1.0), ((int)500));
_zlema13 = ZLEMA(Closes[0], ((int)13));
_wisemannawesome = WisemanAwesomeOscillator(Closes[0]);
_stochfast = StochasticsFast(Closes[0], ((int)3), ((int)14));
_cmo = CMO(Closes[0], ((int)14));
_rss = RSS(Closes[0], ((int)10), ((int)40), ((int)5));
_apz = APZ(Closes[0], ((double)2.0), ((int)20));
_linreg = LinReg(Closes[0], ((int)14));
_dynamicmomentum = DMIndex(Closes[0], ((int)3));
_gannlines = GannLines(Closes[0]);
if (ShowGannLines)
{
QS_Indicator_OnInit_Plot_Plot(ref _gannlines, 0, QS_GetBrush_SolidColor(Color.FromArgb(255, 255, 255, 0)), null, null, null);
QS_Indicator_OnInit_Plot_Plot(ref _gannlines, 1, QS_GetBrush_SolidColor(Color.FromArgb(255, 0, 255, 255)), null, null, null);
QS_Indicator_OnInit_Plot_Plot(ref _gannlines, 2, QS_GetBrush_SolidColor(Color.FromArgb(255, 0, 255, 255)), null, null, null);
QS_Indicator_OnInit_Plot_Plot(ref _gannlines, 3, QS_GetBrush_SolidColor(Color.FromArgb(255, 0, 255, 255)), null, null, null);
QS_Indicator_OnInit_Plot_Plot(ref _gannlines, 4, QS_GetBrush_SolidColor(Color.FromArgb(255, 0, 255, 255)), null, null, null);
QS_Indicator_OnInit_Plot_Plot(ref _gannlines, 5, QS_GetBrush_SolidColor(Color.FromArgb(255, 0, 255, 255)), null, null, null);
QS_Indicator_OnInit_Plot_Plot(ref _gannlines, 6, QS_GetBrush_SolidColor(Color.FromArgb(255, 0, 255, 255)), null, null, null);
QS_Indicator_OnInit_Plot_Plot(ref _gannlines, 7, QS_GetBrush_SolidColor(Color.FromArgb(255, 0, 255, 255)), null, null, null);
QS_Indicator_OnInit_Plot_Plot(ref _gannlines, 8, QS_GetBrush_SolidColor(Color.FromArgb(255, 0, 255, 255)), null, null, null);
QS_Indicator_OnInit_Plot_Indicator(ref _gannlines, true, QS_TrueFalseOrUseDefaultValue.QS_TriStateBoolean_UseDefaultValue, 1);
}
QS_SessionIterators = new List<SessionIterator>();
for (int i = 0; i < BarsArray.Length; i++)
QS_SessionIterators.Add(new SessionIterator(BarsArray[i]));
}
else if (State == State.Terminated)
{
QS_OnTerminated();
}
}
protected override void OnBarUpdate()
{
if (BarsInProgress != 0
|| CurrentBars[0] < BarsRequiredToTrade)
return;
if (true)
{
// OUTPUT PARAMETERS & INITIALISE
if ((_initialised == false))
{
PrintTo = PrintTo.OutputTab2;
ClearOutputWindow();
QS_Print("Time[0]: " + QS_DateTimeToString_FullPrecision_InvariantCulture(Time[0]) + "\t\t"
+ ("\r\n" + "\r\n" + "\r\n"
+ "__________ " + _STRATEGYNAME + " __________ "
+ "\r\n" + "\r\n" + "\r\n"
+ "________ INPUT PARAMETERS ________"
+ "\r\n" + "\r\n"
+ "\r\n"
+ "________________" + "\r\n"));
QS_Print(GetStrategyInputParamsAsText());
QS_Print("\r\n"+ "________________" + "\r\n"
+ "\r\n" + "Calculate:___" + QS_ToString(Calculate)
+ "\r\n" + "Default Quantity:___" + QS_ToString(DefaultQuantity)
+ "\r\n" + "Entries Per Direction:___" + QS_ToString(EntriesPerDirection)
+ "\r\n" + "Entry Handling:___" + QS_ToString(EntryHandling)
+ "\r\n" + "Is Exit On Session Close Strategy:___" + QS_ToString(IsExitOnSessionCloseStrategy)
+ "\r\n" + "Exit On Session Close Seconds:___" + QS_ToString(ExitOnSessionCloseSeconds)
+ "\r\n" + "Is Fill Limit On Touch:___" + QS_ToString(IsFillLimitOnTouch)
+ "\r\n" + "Maximum Bars Look Back:___" + QS_ToString(MaximumBarsLookBack)
+ "\r\n" + "Order Fill Resolution:___" + QS_ToString(OrderFillResolution)
+ "\r\n" + "Slippage:___" + QS_ToString(Slippage)
+ "\r\n" + "Include Commission:___" + QS_ToString(IncludeCommission)
+ "\r\n" + "Is Adopt Account Position Aware:___" + QS_ToString(IsAdoptAccountPositionAware)
+ "\r\n" + "Start Behavior:___" + QS_ToString(StartBehavior)
+ "\r\n" + "Time In Force:___" + QS_ToString(TimeInForce)
+ "\r\n" + "Trace Orders:___" + QS_ToString(TraceOrders)
+ "\r\n" + "Realtime Error Handling:___" + QS_ToString(RealtimeErrorHandling)
+ "\r\n" + "Stop Target Handling:___" + QS_ToString(StopTargetHandling)
+ "\r\n" + "Bars Required To Trade:___" + QS_ToString(BarsRequiredToTrade)
+ "\r\n" + "Allow Removal Of Draw Objects:___" + QS_ToString(AllowRemovalOfDrawObjects)
+ "\r\n" + "Is Instantiated On Each Optimization Iteration:___" + QS_ToString(IsInstantiatedOnEachOptimizationIteration)
+ "\r\n" + "Include Trade History In Backtest:___" + QS_ToString(IncludeTradeHistoryInBacktest)
+ "\r\n"+ "\r\n"+ "\r\n");
QS_Print( "________________" + "\r\n"+ "\r\n") ;
QS_Print("Instrument: " + Bars.Instrument.FullName);
QS_Print("Bar Type: " + Bars.BarsPeriod.BarsPeriodType.ToString());
QS_Print("Bar Length: " + Bars.BarsPeriod.Value);
QS_Print("\r\n"+ "________________" + "\r\n") ;
PrintTo = PrintTo.OutputTab1;
if (PrintToCSV)
{
// CLEAN DATA LOG FILE - INITIALISE
QS_Directory_CreateParentDirectoryIfDoesNotExist(_filepathandname);
QS_File_WriteTextToTextFile(_filepathandname, false, Encoding.GetEncoding(65001, new EncoderExceptionFallback(), new DecoderExceptionFallback()), (("Timestamp" + ";" + "Event" + ";" + "Qty" + ";" + "Fill_Price" + ";" + "$_Commission" + ";" + "$_Profit_Loss" + ";" + "$_Strategy" + ";" + "$_Account" + ";" + "Signal" + ";" + "Indicators") + "\r\n"));
// PRINT PARAMETERS
QS_Directory_CreateParentDirectoryIfDoesNotExist(_filepathandparameters);
QS_File_WriteTextToTextFile(_filepathandparameters, false, Encoding.GetEncoding(65001, new EncoderExceptionFallback(), new DecoderExceptionFallback()), (GetStrategyInputParamsAsText() + "\r\n"));
QS_File_WriteTextToTextFile(_filepathandparameters, true, Encoding.GetEncoding(65001, new EncoderExceptionFallback(), new DecoderExceptionFallback()),
"Instrument: " + Bars.Instrument.FullName + "\r\n" +
"Bar Type: " + Bars.BarsPeriod.BarsPeriodType.ToString() + "\r\n" +
"Bar Length: " + Bars.BarsPeriod.Value.ToString() + "\r\n");
}
}
_initialised = true;
}
if (true)
{
// TIMES & DAYS
if (true)
{
_daysofweekripe = false;
_alltimesripe = false;
_time3 = false;
_time2 = false;
_time1 = false;
}
_time1 = (((QS_DateTime_TimeOfDay(Times[BarsInProgress][((int)0)]) >= StartTime1) && (QS_DateTime_TimeOfDay(Times[BarsInProgress][((int)0)]) <= StopTime1)) || ((QS_DateTime_TimeOfDay(Times[BarsInProgress][((int)0)]) >= StopTime1) && (QS_DateTime_TimeOfDay(Times[BarsInProgress][((int)0)]) <= StartTime1)));
_time2 = (((QS_DateTime_TimeOfDay(Times[BarsInProgress][((int)0)]) >= StartTime2) && (QS_DateTime_TimeOfDay(Times[BarsInProgress][((int)0)]) <= StopTime2)) || ((QS_DateTime_TimeOfDay(Times[BarsInProgress][((int)0)]) >= StopTime2) && (QS_DateTime_TimeOfDay(Times[BarsInProgress][((int)0)]) <= StartTime2)));
_time3 = (((QS_DateTime_TimeOfDay(Times[BarsInProgress][((int)0)]) >= StartTime3) && (QS_DateTime_TimeOfDay(Times[BarsInProgress][((int)0)]) <= StopTime3)) || ((QS_DateTime_TimeOfDay(Times[BarsInProgress][((int)0)]) >= StopTime3) && (QS_DateTime_TimeOfDay(Times[BarsInProgress][((int)0)]) <= StartTime3)));
_alltimesripe = ((
EnableTimeFilter1
&&
_time1
)
||
(
EnableTimeFilter2
&&
_time2
)
||
(
EnableTimeFilter3
&&
_time3
)
||
(
(EnableTimeFilter1 == false)
&&
(EnableTimeFilter2 == false)
&&
(EnableTimeFilter3 == false)
));
_daysofweekripe = ((
Sunday
&&
((Times[0][0].DayOfWeek) == DayOfWeek.Sunday)
)
||
(
Monday
&&
((Times[0][0].DayOfWeek) == DayOfWeek.Monday)
)
||
(
Tuesday
&&
((Times[0][0].DayOfWeek) == DayOfWeek.Tuesday)
)
||
(
Wednesday
&&
((Times[0][0].DayOfWeek) == DayOfWeek.Wednesday)
)
||
(
Thursday
&&
((Times[0][0].DayOfWeek) == DayOfWeek.Thursday)
)
||
(
Friday
&&
((Times[0][0].DayOfWeek) == DayOfWeek.Friday)
)
&&
(
Sunday
||
Monday
||
Tuesday
||
Wednesday
||
Thursday
||
Friday
));
}
if (true)
{
// FLAT FIRST / STAY IN TRADE
_flatstateripe = false;
_flatstateripe = ((
(StayInTradeFlatFirst == true)
&&
(Position.MarketPosition == MarketPosition.Flat)
)
||
(StayInTradeFlatFirst == false));
}
if (true)
{
// FIB WEIGHTED MA
if ((_fibweightmaInitialized == false))
{
_fibweightmaInitialized = true;
QS_ReDimArray(ref _fibweightings, FibWeightMAPeriod, ((long)0));
_nextfibnumbertempvar = 1;
_previousfibnumbertempvar = 1;
_fibnumberbeforepreviousonetempvar = 0;
_counterforlooptempvar = 0;
while ((((long)_counterforlooptempvar) < ((long)FibWeightMAPeriod)))
{
_nextfibnumbertempvar = (((int)_fibnumberbeforepreviousonetempvar) + ((int)_previousfibnumbertempvar));
_fibweightings[_counterforlooptempvar] = ((long)_nextfibnumbertempvar);
_fibnumberbeforepreviousonetempvar = _previousfibnumbertempvar;
_previousfibnumbertempvar = _nextfibnumbertempvar;
_counterforlooptempvar = (((int)_counterforlooptempvar) + ((int)1));
}
QS_ReverseArray(ref _fibweightings);
_sumoffibnumberweightings = QS_SumOfValuesInArray_Int64s(ref _fibweightings);
}
_fibweightedsumofrecentvaluestempvar = 0.0;
_counterforlooptempvar = 0;
while ((((long)_counterforlooptempvar) < ((long)FibWeightMAPeriod)))
{
_fibweightedsumofrecentvaluestempvar = (((double)_fibweightedsumofrecentvaluestempvar) + (((double)_fibweightings[_counterforlooptempvar]) * ((double)Closes[0][_counterforlooptempvar])));
_counterforlooptempvar = (((int)_counterforlooptempvar) + ((int)1));
}
_fibweightedma[0] = (((double)_fibweightedsumofrecentvaluestempvar) / ((double)_sumoffibnumberweightings));
_smoothedfibweightedma[0] = SMA(_fibweightedma, SmoothingSimpleMAPeriod)[0];
_fibweightmalongripe = ((EnableFibWeightMACross == false)
||
(
EnableFibWeightMACross
&&
(CrossAbove(_fibweightedma, _smoothedfibweightedma, 1) && IsRising(_fibweightedma))
));
_fibweightmashortripe = ((EnableFibWeightMACross == false)
||
(
EnableFibWeightMACross
&&
(CrossBelow(_fibweightedma, _smoothedfibweightedma, 1) && IsFalling(_fibweightedma))
));
_fibweightexitmalongripe = (ExitonFibCounterCross
&&
CrossBelow(_fibweightedma, _smoothedfibweightedma, 1));
_fibweightexitmashortripe = (ExitonFibCounterCross
&&
CrossAbove(_fibweightedma, _smoothedfibweightedma, 1));
}
if (true)
{
// DMI FILTER
_dynamicmomentumshortripe = false;
if (EnableDynamicMomentum)
{
_dynamicmomentumrangeshortok = ((
(((_dynamicmomentum[0] >= ((double)27.73)) && (_dynamicmomentum[0] <= ((double)29.13))) || ((_dynamicmomentum[0] >= ((double)29.13)) && (_dynamicmomentum[0] <= ((double)27.73))))
||
(((_dynamicmomentum[0] >= ((double)31.53)) && (_dynamicmomentum[0] <= ((double)38.27))) || ((_dynamicmomentum[0] >= ((double)38.27)) && (_dynamicmomentum[0] <= ((double)31.53))))
||
(((_dynamicmomentum[0] >= ((double)45.39)) && (_dynamicmomentum[0] <= ((double)56.40))) || ((_dynamicmomentum[0] >= ((double)56.40)) && (_dynamicmomentum[0] <= ((double)45.39))))
));
}
_dynamicmomentumshortripe = ((EnableDynamicMomentum == false)
||
(
EnableDynamicMomentum
&&
_dynamicmomentumrangeshortok
));
}
if (true)
{
// RSI FILTER
_rsishortripe = false;
if (EnableRSI)
{
_rsirangeshortok = ((
(((_rsi.Default[0] >= ((double)36.65)) && (_rsi.Default[0] <= ((double)38.22))) || ((_rsi.Default[0] >= ((double)38.22)) && (_rsi.Default[0] <= ((double)36.65))))
||
(((_rsi.Default[0] >= ((double)39.38)) && (_rsi.Default[0] <= ((double)42.94))) || ((_rsi.Default[0] >= ((double)42.94)) && (_rsi.Default[0] <= ((double)39.38))))
||
(((_rsi.Default[0] >= ((double)44.42)) && (_rsi.Default[0] <= ((double)45.36))) || ((_rsi.Default[0] >= ((double)45.36)) && (_rsi.Default[0] <= ((double)44.42))))
||
(((_rsi.Default[0] >= ((double)49.04)) && (_rsi.Default[0] <= ((double)51.30))) || ((_rsi.Default[0] >= ((double)51.30)) && (_rsi.Default[0] <= ((double)49.04))))
||
(((_rsi.Default[0] >= ((double)55.92)) && (_rsi.Default[0] <= ((double)56.84))) || ((_rsi.Default[0] >= ((double)56.84)) && (_rsi.Default[0] <= ((double)55.92))))
||
(((_rsi.Default[0] >= ((double)63.0)) && (_rsi.Default[0] <= ((double)102.0))) || ((_rsi.Default[0] >= ((double)102.0)) && (_rsi.Default[0] <= ((double)63.0))))
));
}
_rsishortripe = ((EnableRSI == false)
||
(
EnableRSI
&&
_rsirangeshortok
));
}
if (true)
{
// AWESOME FILTER
_awesomeshortripe = false;
if (EnableAwesome)
{
_awesomeshortripe = ((
(((_wisemannawesome[0] >= ((double)-12.15)) && (_wisemannawesome[0] <= ((double)-8.45))) || ((_wisemannawesome[0] >= ((double)-8.45)) && (_wisemannawesome[0] <= ((double)-12.15))))
||
(((_wisemannawesome[0] >= ((double)-4.26)) && (_wisemannawesome[0] <= ((double)1.11))) || ((_wisemannawesome[0] >= ((double)1.11)) && (_wisemannawesome[0] <= ((double)-4.26))))
||
(((_wisemannawesome[0] >= ((double)3.60)) && (_wisemannawesome[0] <= ((double)9.73))) || ((_wisemannawesome[0] >= ((double)9.73)) && (_wisemannawesome[0] <= ((double)3.60))))
));
}
_awesomeshortripe = ((EnableAwesome == false)
||
(
EnableAwesome
&&
_awesomeshortripe
));
}
if (true)
{
// CCI FILTER
_ccishortripe = false;
if (EnableCCI)
{
_ccishortripe = ((
(((_cci[0] >= ((double)-150.0)) && (_cci[0] <= ((double)-31.88))) || ((_cci[0] >= ((double)-31.88)) && (_cci[0] <= ((double)-150.0))))
));
}
_ccishortripe = ((EnableCCI == false)
||
(
EnableCCI
&&
_ccirangeshortok
));
}
if (true)
{
// MACD [VS]
_macdlongripe = false;
_macdshortripe = false;
if (EnableMACDCross)
{
_macdcrossdown = CrossBelow(_macd.Default, _macd.Avg, 1);
_macdcrossup = CrossAbove(_macd.Default, _macd.Avg, 1);
}
_macdlongripe = ((EnableMACDCross == false)
||
(
EnableMACDCross
&&
_macdcrossup
));
_macdshortripe = ((EnableMACDCross == false)
||
(
EnableMACDCross
&&
_macdcrossdown
));
}
if (true)
{
// PRINT INDICATORS CSV
if (PrintIndicatorValues
&&
(State == State.Realtime))
{
if (PrintToCSV)
{
_indicatorlistprint.Clear();
_indicatorlistprint.Add(("ADX;" + QS_DoubleToString_ComputerReadable(_adx[0], ((int)2))));
_indicatorlistprint.Add(("ATR;" + QS_DoubleToString_ComputerReadable(_atrfilter[0], ((int)2))));
_indicatorlistprint.Add(("VORTEX_PLUS;" + QS_DoubleToString_ComputerReadable(_vortex.VIPlus[0], ((int)2))));
_indicatorlistprint.Add(("VORTEX_MINUS;" + QS_DoubleToString_ComputerReadable(_vortex.VIMinus[0], ((int)2))));
_indicatorlistprint.Add(("PFE;" + QS_DoubleToString_ComputerReadable(_polarizedfractalefficency[0], ((int)2))));
_indicatorlistprint.Add(("MACD_DEFAULT;" + QS_DoubleToString_ComputerReadable(_macd.Default[0], ((int)2))));
_indicatorlistprint.Add(("MACD_AVG;" + QS_DoubleToString_ComputerReadable(_macd.Avg[0], ((int)2))));
_indicatorlistprint.Add(("MACD_DIFF;" + QS_DoubleToString_ComputerReadable(_macd.Diff[0], ((int)2))));
_indicatorlistprint.Add(("WILLIAMS_%R;" + QS_DoubleToString_ComputerReadable(_williamsr[0], ((int)2))));
_indicatorlistprint.Add(("MOMENTUM;" + QS_DoubleToString_ComputerReadable(_momentum[0], ((int)2))));
_indicatorlistprint.Add(("CCI;" + QS_DoubleToString_ComputerReadable(_cci[0], ((int)2))));
_indicatorlistprint.Add(("RSI_DEFAULT;" + QS_DoubleToString_ComputerReadable(_rsi.Default[0], ((int)2))));
_indicatorlistprint.Add(("RSI_AVERAGE;" + QS_DoubleToString_ComputerReadable(_rsi.Avg[0], ((int)2))));
_indicatorlistprint.Add(("TRIX_DEFAULT;" + QS_DoubleToString_ComputerReadable(_trix.Default[0], ((int)2))));
_indicatorlistprint.Add(("TRIX_SIGNAL;" + QS_DoubleToString_ComputerReadable(_trix.Signal[0], ((int)2))));
_indicatorlistprint.Add(("CHAIKIN;" + QS_DoubleToString_ComputerReadable(_Chaikin[0], ((int)2))));
_indicatorlistprint.Add(("VWAP;" + QS_DoubleToString_ComputerReadable(_vwap.VWAP[0], ((int)2))));
_indicatorlistprint.Add(("VWAP_U1;" + QS_DoubleToString_ComputerReadable(_vwap.UpperBand_1[0], ((int)2))));
_indicatorlistprint.Add(("VWAP_L1;" + QS_DoubleToString_ComputerReadable(_vwap.LowerBand_1[0], ((int)2))));
_indicatorlistprint.Add(("VWAP_U2;" + QS_DoubleToString_ComputerReadable(_vwap.UpperBand_2[0], ((int)2))));
_indicatorlistprint.Add(("VWAP_L2;" + QS_DoubleToString_ComputerReadable(_vwap.LowerBand_2[0], ((int)2))));
_indicatorlistprint.Add(("VWAP_CLOUD_HIGH;" + QS_DoubleToString_ComputerReadable(_vwap.Cloud_H[0], ((int)2))));
_indicatorlistprint.Add(("VWAP_CLOUD_LOW;" + QS_DoubleToString_ComputerReadable(_vwap.Cloud_L[0], ((int)2))));
_indicatorlistprint.Add(("FISHER_TRANSFORM;" + QS_DoubleToString_ComputerReadable(_fishertransform[0], ((int)2))));
_indicatorlistprint.Add(("ZIGZAG_HIGH;" + QS_DoubleToString_ComputerReadable(_zigzag.ZigZagHigh[0], ((int)2))));
_indicatorlistprint.Add(("ZIGZAG_LOW;" + QS_DoubleToString_ComputerReadable(_zigzag.ZigZagLow[0], ((int)2))));
_indicatorlistprint.Add(("618_EMA;" + QS_DoubleToString_ComputerReadable(_618ema[0], ((int)2))));
_indicatorlistprint.Add(("382_EMA;" + QS_DoubleToString_ComputerReadable(_382ema[0], ((int)2))));
_indicatorlistprint.Add(("236_EMA;" + QS_DoubleToString_ComputerReadable(_236ema[0], ((int)2))));
_indicatorlistprint.Add(("144_SMA;" + QS_DoubleToString_ComputerReadable(sma[0], ((int)2))));
_indicatorlistprint.Add(("VROC;" + QS_DoubleToString_ComputerReadable(_vroc[0], ((int)2))));
_indicatorlistprint.Add(("RVI;" + QS_DoubleToString_ComputerReadable(_rvi[0], ((int)2))));
_indicatorlistprint.Add(("MFI;" + QS_DoubleToString_ComputerReadable(_mfi[0], ((int)2))));
_indicatorlistprint.Add(("ACCUM_DIST;" + QS_DoubleToString_ComputerReadable(_accumulation_distribution[0], ((int)2))));
_indicatorlistprint.Add(("14_P_MA_ENVELOPES_UPPER;" + QS_DoubleToString_ComputerReadable(_14pmaenvelopes.Upper[0], ((int)2))));
_indicatorlistprint.Add(("14_P_MA_ENVELOPES_MID;" + QS_DoubleToString_ComputerReadable(_14pmaenvelopes.Middle[0], ((int)2))));
_indicatorlistprint.Add(("14_P_MA_ENVELOPES_LOWER;" + QS_DoubleToString_ComputerReadable(_14pmaenvelopes.Lower[0], ((int)2))));
_indicatorlistprint.Add(("LIN_REG_SLOPE;" + QS_DoubleToString_ComputerReadable(_linregslope[0], ((int)2))));
_indicatorlistprint.Add(("R_SQUARED;" + QS_DoubleToString_ComputerReadable(_rsquared[0], ((int)2))));
_indicatorlistprint.Add(("OBV;" + QS_DoubleToString_ComputerReadable(_obv[0], ((int)2))));
_indicatorlistprint.Add(("RIND;" + QS_DoubleToString_ComputerReadable(_rind[0], ((int)2))));
_indicatorlistprint.Add(("BOLLI_500_P_UPPER;" + QS_DoubleToString_ComputerReadable(_500pbolli.Upper[0], ((int)2))));
_indicatorlistprint.Add(("BOLLI_500_P_MID;" + QS_DoubleToString_ComputerReadable(_500pbolli.Middle[0], ((int)2))));
_indicatorlistprint.Add(("BOLLI_500_P_LOWER;" + QS_DoubleToString_ComputerReadable(_500pbolli.Lower[0], ((int)2))));
_indicatorlistprint.Add(("AWESOME;" + QS_DoubleToString_ComputerReadable(_wisemannawesome[0], ((int)2))));
_indicatorlistprint.Add(("STOCH_FAST_D;" + QS_DoubleToString_ComputerReadable(_stochfast.D[0], ((int)2))));
_indicatorlistprint.Add(("STOCH_FAST_K;" + QS_DoubleToString_ComputerReadable(_stochfast.K[0], ((int)2))));
_indicatorlistprint.Add(("CMO;" + QS_DoubleToString_ComputerReadable(_cmo[0], ((int)2))));
_indicatorlistprint.Add(("RSS;" + QS_DoubleToString_ComputerReadable(_rss[0], ((int)2))));
_indicatorlistprint.Add(("APZ_LOW;" + QS_DoubleToString_ComputerReadable(_apz.Lower[0], ((int)2))));
_indicatorlistprint.Add(("APZ_UPPER;" + QS_DoubleToString_ComputerReadable(_apz.Upper[0], ((int)2))));
_indicatorlistprint.Add(("LIN_REG;" + QS_DoubleToString_ComputerReadable(_linreg[0], ((int)2))));
_indicatorlistprint.Add(("DYNAMIC_MOMENTUM;" + QS_DoubleToString_ComputerReadable(_dynamicmomentum[0], ((int)2))));
_indicatorlistprint.Add(("DISPARITY_INDEX;" + QS_DoubleToString_ComputerReadable(_disparityindex[0], ((int)2))));
_indicatorlistprint.Add(("LIN_REG_INTERCEPT;" + QS_DoubleToString_ComputerReadable(_linregintercept[0], ((int)2))));
_indicatorlistprint.Add(("VOLUME_UP;" + QS_DoubleToString_ComputerReadable(_volumeupdown.UpVolume[0], ((int)2))));
_indicatorlistprint.Add(("VOLUME_DOWN;" + QS_DoubleToString_ComputerReadable(_volumeupdown.DownVolume[0], ((int)2))));
_indicatorlistprint.Add(("DM_DI_PLUS;" + QS_DoubleToString_ComputerReadable(_directionalmovement.DiPlus[0], ((int)2))));
_indicatorlistprint.Add(("DM_ADX_PLOT;" + QS_DoubleToString_ComputerReadable(_directionalmovement.ADXPlot[0], ((int)2))));
_indicatorlistprint.Add(("DM_DI_MINUS;" + QS_DoubleToString_ComputerReadable(_directionalmovement.DiMinus[0], ((int)2))));
_indicatorlistprint.Add(("AROON UP;" + QS_DoubleToString_ComputerReadable(_aroon.Up[0], ((int)2))));
_indicatorlistprint.Add(("AROON DOWN;" + QS_DoubleToString_ComputerReadable(_aroon.Down[0], ((int)2))));
_indicatorlistprint.Add(("CP+_C;" + QS_DoubleToString_ComputerReadable(_cpplusday.C[0], ((int)2))));
_indicatorlistprint.Add(("CP+_R1;" + QS_DoubleToString_ComputerReadable(_cpplusday.R1[0], ((int)2))));
_indicatorlistprint.Add(("CP+_R2;" + QS_DoubleToString_ComputerReadable(_cpplusday.R2[0], ((int)2))));
_indicatorlistprint.Add(("CP+_R3;" + QS_DoubleToString_ComputerReadable(_cpplusday.R3[0], ((int)2))));
_indicatorlistprint.Add(("CP+_R4;" + QS_DoubleToString_ComputerReadable(_cpplusday.R4[0], ((int)2))));
_indicatorlistprint.Add(("CP+_R5;" + QS_DoubleToString_ComputerReadable(_cpplusday.R5[0], ((int)2))));
_indicatorlistprint.Add(("CP+_R6;" + QS_DoubleToString_ComputerReadable(_cpplusday.R6[0], ((int)2))));
_indicatorlistprint.Add(("CP+_S1;" + QS_DoubleToString_ComputerReadable(_cpplusday.S1[0], ((int)2))));
_indicatorlistprint.Add(("CP+_S2;" + QS_DoubleToString_ComputerReadable(_cpplusday.S2[0], ((int)2))));
_indicatorlistprint.Add(("CP+_S3;" + QS_DoubleToString_ComputerReadable(_cpplusday.S3[0], ((int)2))));
_indicatorlistprint.Add(("CP+_S4;" + QS_DoubleToString_ComputerReadable(_cpplusday.S4[0], ((int)2))));
_indicatorlistprint.Add(("CP+_S5;" + QS_DoubleToString_ComputerReadable(_cpplusday.S5[0], ((int)2))));
_indicatorlistprint.Add(("CP+_S6;" + QS_DoubleToString_ComputerReadable(_cpplusday.S6[0], ((int)2))));
_indicatorlistprint.Add(("VOLUME;" + QS_DoubleToString_ComputerReadable(_volume[0], ((int)2))));
_indicatorlistprint.Add(("8_ZLEMA;" + QS_DoubleToString_ComputerReadable(_zlema8[0], ((int)2))));
_indicatorlistprint.Add(("62_ZLEMA;" + QS_DoubleToString_ComputerReadable(_62zlema[0], ((int)2))));
_indicatorlistprint.Add(("1000_SMA;" + QS_DoubleToString_ComputerReadable(_1000sma[0], ((int)2))));
}
}
QS_SortList(ref _indicatorlistprint, false);
// SIGNAL INDICATORS
if (PrintIndicatorValues
&&
(State == State.Realtime))
{
_entrysignalindicators.Clear();
if (EnableFibWeightMACross)
{
_entrysignalindicators.Add("FIB_EMA_CROSS;");
}
if (EnableMACDCross)
{
_entrysignalindicators.Add("MACD_CROSS;");
}
}
_twoplumsforone = (QS_ConvertListToString(_entrysignalindicators, (Times[0][0].ToString("s") + ";" + "Signal" + ";;;;;;;"), "", "", "", ";") + QS_ConvertListToString(_indicatorlistprint, ("\r" + Times[0][0].ToString("s") + ";" + "Indicator" + ";;;;;;;;"), "", "", "", ";"));
}
if (true)
{
//
// FILTERS
//
if (true)
{
// VWAP DISTANCE FILTER
_vwappercentdistok = ((Closes[0][0] <= (((double)_vwap.VWAP[0]) * (((double)1.0) - ((double)_vwapdist))))
||
(Closes[0][0] >= (((double)_vwap.VWAP[0]) * (((double)1.0) + ((double)_vwapdist)))));
_vwapdistripe = ((EnableDistancefromVWAP == false)
||
(
EnableDistancefromVWAP
&&
_vwappercentdistok
));
}
if (true)
{
// BOLLI 500 DISTANCE FILTER
_bolli500distok = ((Closes[0][0] <= (((double)_500pbolli.Middle[0]) * (((double)1.0) - ((double)_bolli500dist))))
||
(Closes[0][0] >= (((double)_500pbolli.Middle[0]) * (((double)1.0) + ((double)_bolli500dist)))));
_bolli500distripe = ((EnableDistancefromBolli500Mid == false)
||
(
EnableDistancefromBolli500Mid
&&
_bolli500distok
));
}
}
//
// FIRST
// [ENABLED] EXECUTIONS
//
//
if (EnableFibWeightMACross
||
EnableMACDCross)
{
// __ RIPE __
// GERNERAL CONDITIONS LOGIC FOR BOTH SHORT & LONG
_conditionsripe = false;
if (_daysofweekripe
&&
_alltimesripe
&&
_flatstateripe
&&
_vwapdistripe
&&
_bolli500distripe)
{
_conditionsripe = true;
}
}
// EXECUTION LOGIC LONG
if (_conditionsripe
&&
_fibweightmalongripe
&&
_macdlongripe)
{
// LONG ENTRIES BLOCK
if (EnableLong)
{
// MARKET LONG EXECUTE
if ((EnableLimitOrdersOveridesMarket == false)
&&
(EnterLimitOutsideofSignal == false))
{
EnterLong(QTYENTRY1, "LE1");
if (ChartExecutionMark)
{
QS_DrawTriangleUp(this, true, ((int)0), Medians[0][0], ExecutionMarkerColour, false);
}
if (Entry2)
{
EnterLong(QtyEntry2, "LE2");
}
if (Entry3)
{
EnterLong(QtyEntry3, "LE3");
}
if (Entry4)
{
EnterLong(QtyEntry4, "LE4");
}
if (Entry5)
{
EnterLong(QtyEntry5, "LE5");
}
}
// LIMIT LONG EXECUTE
if (EnableLong
&&
(EnableLimitOrdersOveridesMarket == true)
&&
(EnterLimitOutsideofSignal == false))
{
EnterLongLimit(QTYENTRY1, GetCurrentAsk(), "LE1");
if (ChartExecutionMark)
{
QS_DrawTriangleUp(this, true, ((int)0), Medians[0][0], ExecutionMarkerColour, false);
}
if (Entry2)
{
EnterLongLimit(QtyEntry2, GetCurrentAsk(), "LE2");
}
if (Entry3)
{
EnterLongLimit(QtyEntry3, GetCurrentAsk(), "LE3");
}
if (Entry4)
{
EnterLongLimit(QtyEntry4, GetCurrentAsk(), "LE4");
}
if (Entry5)
{
EnterLongLimit(QtyEntry5, GetCurrentAsk(), "LE5");
}
}
// OUTSIDE ENTRY LONG
if (EnableLong
&&
EnterLimitOutsideofSignal
&&
(EnableLimitOrdersOveridesMarket == false))
{
EnterLongLimit(QTYENTRY1, (((double)GetCurrentAsk()) - ((double)TicksAwayFromSignal) * ((double)Instrument.MasterInstrument.TickSize)), "LE1");
if (ChartExecutionMark)
{
QS_DrawTriangleUp(this, true, ((int)0), Medians[0][0], ExecutionMarkerColour, false);
}
if (Entry2)
{
EnterLongLimit(QtyEntry2, GetCurrentAsk(), "LE2");
}
if (Entry3)
{
EnterLongLimit(QtyEntry3, (((double)GetCurrentAsk()) - ((double)TicksAwayFromSignal) * ((double)Instrument.MasterInstrument.TickSize)), "LE3");
}
if (Entry4)
{
EnterLongLimit(QtyEntry4, GetCurrentAsk(), "LE4");
}
if (Entry5)
{
EnterLongLimit(QtyEntry5, (((double)GetCurrentAsk()) - ((double)TicksAwayFromSignal) * ((double)Instrument.MasterInstrument.TickSize)), "LE5");
}
}
}
// PRINT
if (EnableLong
&&
PrintIndicatorValues
&&
PrintToCSV
&&
(State == State.Realtime))
{
QS_Directory_CreateParentDirectoryIfDoesNotExist(_filepathandname);
QS_File_WriteTextToTextFile(_filepathandname, true, Encoding.GetEncoding(65001, new EncoderExceptionFallback(), new DecoderExceptionFallback()), (_twoplumsforone + "\r\n"));
}
}
else
{
// EXIT CONDITIONS - EXIT LONG
if ((Position.MarketPosition == MarketPosition.Long))
{
if (_fibweightexitmalongripe)
{
ExitLong("LX", "");
}
}
}
// EXECUTION LOGIC SHORT
if (_conditionsripe
&&
_fibweightmashortripe
&&
_macdshortripe
&&
_rsishortripe
&&
_ccishortripe
&&
_awesomeshortripe)
{
// SHORT ENTRIES BLOCK
if (EnableShort)
{
// MARKET SHORT EXECUTE
if ((EnableLimitOrdersOveridesMarket == false)
&&
(EnterLimitOutsideofSignal == false))
{
EnterShort(QTYENTRY1, "SE1");
if (ChartExecutionMark)
{
QS_DrawTriangleDown(this, true, ((int)0), Medians[0][0], ExecutionMarkerColour, false);
}
if (Entry2)
{
EnterShort(QtyEntry2, "SE2");
}
if (Entry3)
{
EnterShort(QtyEntry3, "SE3");
}
if (Entry4)
{
EnterShort(QtyEntry4, "SE4");
}
if (Entry5)
{
EnterShort(QtyEntry5, "SE5");
}
}
// LIMIT SHORT EXECUTE
if (EnableShort
&&
(EnableLimitOrdersOveridesMarket == true)
&&
(EnterLimitOutsideofSignal == false))
{
EnterShortLimit(QTYENTRY1, GetCurrentAsk(), "SE1");
if (ChartExecutionMark)
{
QS_DrawTriangleDown(this, true, ((int)0), Medians[0][0], ExecutionMarkerColour, false);
}
if (Entry2)
{
EnterShortLimit(QtyEntry2, GetCurrentAsk(), "SE2");
}
if (Entry3)
{
EnterShortLimit(QtyEntry3, GetCurrentAsk(), "SE3");
}
if (Entry4)
{
EnterShortLimit(QtyEntry4, GetCurrentAsk(), "SE4");
}
if (Entry5)
{
EnterShortLimit(QtyEntry5, GetCurrentAsk(), "SE5");
}
}
// OUTSIDE ENTRY SHORT
if (EnableShort
&&
(EnableLimitOrdersOveridesMarket == false)
&&
EnterLimitOutsideofSignal)
{
EnterShortLimit(QTYENTRY1, (((double)GetCurrentAsk()) + (((double)TicksAwayFromSignal) * ((double)Instrument.MasterInstrument.TickSize))), "SE1");
if (ChartExecutionMark)
{
QS_DrawTriangleDown(this, true, ((int)0), Medians[0][0], ExecutionMarkerColour, false);
}
if (Entry2)
{
EnterShortLimit(QtyEntry2, (((double)GetCurrentAsk()) + (((double)TicksAwayFromSignal) * ((double)Instrument.MasterInstrument.TickSize))), "SE2");
}
if (Entry3)
{
EnterShortLimit(QtyEntry3, (((double)GetCurrentAsk()) + (((double)TicksAwayFromSignal) * ((double)Instrument.MasterInstrument.TickSize))), "SE3");
}
if (Entry4)
{
EnterShortLimit(QtyEntry4, (((double)GetCurrentAsk()) + (((double)TicksAwayFromSignal) * ((double)Instrument.MasterInstrument.TickSize))), "SE4");
}
if (Entry5)
{
EnterShortLimit(QtyEntry5, (((double)GetCurrentAsk()) + (((double)TicksAwayFromSignal) * ((double)Instrument.MasterInstrument.TickSize))), "SE5");
}
}
}
// PRINT
if (EnableShort
&&
PrintIndicatorValues
&&
PrintToCSV
&&
(State == State.Realtime))
{
QS_Directory_CreateParentDirectoryIfDoesNotExist(_filepathandname);
QS_File_WriteTextToTextFile(_filepathandname, true, Encoding.GetEncoding(65001, new EncoderExceptionFallback(), new DecoderExceptionFallback()), (_twoplumsforone + "\r\n"));
}
}
else
{
// EXIT CONDITIONS - EXIT SHORT
if ((Position.MarketPosition == MarketPosition.Short))
{
if (_fibweightexitmashortripe)
{
ExitShort("SX", "");
}
}
}
// **
//
// RAW CODE - *** NOTHING GOES AFTER HERE ***
//
// **
// PRINT TRADE LOG
}
private double lastRealized_PnL = 0.0;
private bool isFirstTradeAfterEntry = false;
private DateTime lastOrderTimestamp = DateTime.MinValue;
private void PrintToOutputTab2(string message)
{
PrintTo = PrintTo.OutputTab2;
QS_Print(message);
PrintTo = PrintTo.OutputTab1;
}
private void PrintTradeDetailsToCSV(string timestamp, string data)
{
if (PrintToCSV)
{
string isoTimestamp = DateTime.Parse(timestamp).ToString("yyyy-MM-ddTHH:mm:ss");
QS_File_WriteTextToTextFile(_filepathandname, true, Encoding.GetEncoding(65001, new EncoderExceptionFallback(), new DecoderExceptionFallback()), $"{isoTimestamp};{data}\r\n");
}
}
protected override void OnOrderUpdate(Cbi.Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, Cbi.OrderState orderState, DateTime time, Cbi.ErrorCode error, string comment)
{
if (State != State.Realtime)
return;
if (orderState == OrderState.Filled)
{
DateTime chartTime = Times[0][0];
bool isEntryOrder = order.OrderAction == OrderAction.Buy || order.OrderAction == OrderAction.SellShort;
if (isEntryOrder)
{
isFirstTradeAfterEntry = true;
lastOrderTimestamp = chartTime;
}
else
{
isFirstTradeAfterEntry = false;
}
string timestamp = TimeStamp(chartTime);
if (PrintTradeLog)
{
string orderAction = order.OrderAction == OrderAction.Buy ? "Long" : "Short";
string output;
if (order.Name.Contains("LX") || order.Name.Contains("SX"))
{
output = $"Exit {order.Name} {averageFillPrice:F2}";
}
else if (order.Name.ToLower().Contains("profit target"))
{
output = $"Target {averageFillPrice:F2}";
}
else if (order.Name.ToLower().Contains("stop"))
{
output = $"Stop {averageFillPrice:F2}";
}
else
{
output = $"{orderAction} {order.OrderType} {order.Name} {averageFillPrice:F2}";
}
PrintToOutputTab2($"{timestamp} ________ {output}");
string csvOutput = $"{order.Name};{quantity};{averageFillPrice:F2}";
PrintTradeDetailsToCSV(timestamp, csvOutput);
}
}
}
protected override void OnAccountItemUpdate(Cbi.Account account, Cbi.AccountItem accountItem, double value)
{
if (State != State.Realtime)
return;
if (accountItem == Cbi.AccountItem.RealizedProfitLoss)
{
DateTime chartTime = Times[0][0];
string timestamp = TimeStamp(chartTime);
double tradeProfitLoss = value - lastRealized_PnL;
lastRealized_PnL = value;
if (tradeProfitLoss != 0)
{
string profitOrLoss;
TimeSpan timeDifference = chartTime - lastOrderTimestamp;
// Only detect commissions immediately following an entry order and if the loss is less than $35
if (isFirstTradeAfterEntry && tradeProfitLoss < 0 && tradeProfitLoss > -35 && timeDifference.TotalSeconds < 0.7)
{
profitOrLoss = "Commission";
isFirstTradeAfterEntry = false;
PrintTradeDetailsToCSV(timestamp, $"{profitOrLoss};;;{tradeProfitLoss:F2}");
}
else
{
profitOrLoss = tradeProfitLoss > 0 ? "Profit" : "Loss";
isFirstTradeAfterEntry = false;
PrintTradeDetailsToCSV(timestamp, $"{profitOrLoss};;;;${tradeProfitLoss:F2}");
}
if (PrintTradeLog)
{
double netLiquidationValue = Account.Get(AccountItem.NetLiquidation, Currency.UsDollar);
PrintToOutputTab2($"{timestamp} ________ {profitOrLoss} ${tradeProfitLoss:F2}");
PrintToOutputTab2($"{timestamp} ________ Strategy: ${value:F2}");
PrintTradeDetailsToCSV(timestamp, $"Strategy;;;;;${value:F2}");
PrintTradeDetailsToCSV(timestamp, $"Account;;;;;;${netLiquidationValue:F2}");
}
}
}
}
private string TimeStamp(DateTime time)
{
return time.ToString("yyyy-MM-dd HH:mm:ss.fff");
// CLEAN LABEL - RENAME
// clean indicator example = {indicatorr}.Name ="";
}
public override string DisplayName
{
get{ return "Δ"; }
}
#region Properties
[NinjaScriptProperty]
[Display(Name="Enable CCI", Description="", Order=1, GroupName="Parameters")]
public bool EnableCCI { get; set; }
[NinjaScriptProperty]
[Display(Name="Enable Awesome", Description="", Order=2, GroupName="Parameters")]
public bool EnableAwesome { get; set; }
[NinjaScriptProperty]
[Display(Name="Enable RSI", Description="", Order=3, GroupName="Parameters")]
public bool EnableRSI { get; set; }
[NinjaScriptProperty]
[Display(Name="Enable Dynamic Momentum", Description="", Order=4, GroupName="Parameters")]
public bool EnableDynamicMomentum { get; set; }
[NinjaScriptProperty]
[Display(Name="Sunday", Description="", Order=5, GroupName="0. DAYS")]
public bool Sunday { get; set; }
[NinjaScriptProperty]
[Display(Name="Monday", Description="", Order=6, GroupName="0. DAYS")]
public bool Monday { get; set; }
[NinjaScriptProperty]
[Display(Name="Tuesday", Description="", Order=7, GroupName="0. DAYS")]
public bool Tuesday { get; set; }
[NinjaScriptProperty]
[Display(Name="Wednesday", Description="", Order=8, GroupName="0. DAYS")]
public bool Wednesday { get; set; }
[NinjaScriptProperty]
[Display(Name="Thursday", Description="", Order=9, GroupName="0. DAYS")]
public bool Thursday { get; set; }
[NinjaScriptProperty]
[Display(Name="Friday", Description="", Order=10, GroupName="0. DAYS")]
public bool Friday { get; set; }
[NinjaScriptProperty]
[Display(Name="Enable Time Filter 1", Description="", Order=11, GroupName="0. TIME")]
public bool EnableTimeFilter1 { get; set; }
[NinjaScriptProperty]
[PropertyEditor("NinjaTrader.Gui.Tools.AutoCloseTimeEditorKey")]
[Display(Name="> Start Time 1", Description="", Order=12, GroupName="0. TIME")]
public DateTime StartTime1 { get; set; }
[NinjaScriptProperty]
[PropertyEditor("NinjaTrader.Gui.Tools.AutoCloseTimeEditorKey")]
[Display(Name="> Stop Time 1", Description="", Order=13, GroupName="0. TIME")]
public DateTime StopTime1 { get; set; }
[NinjaScriptProperty]
[Display(Name="Enable Time Filter 2", Description="", Order=14, GroupName="0. TIME")]
public bool EnableTimeFilter2 { get; set; }
[NinjaScriptProperty]
[PropertyEditor("NinjaTrader.Gui.Tools.AutoCloseTimeEditorKey")]
[Display(Name="> Start Time 2", Description="", Order=15, GroupName="0. TIME")]
public DateTime StartTime2 { get; set; }
[NinjaScriptProperty]
[PropertyEditor("NinjaTrader.Gui.Tools.AutoCloseTimeEditorKey")]
[Display(Name="> Stop Time 2", Description="", Order=16, GroupName="0. TIME")]
public DateTime StopTime2 { get; set; }
[NinjaScriptProperty]
[Display(Name="Enable Time Filter 3", Description="", Order=17, GroupName="0. TIME")]
public bool EnableTimeFilter3 { get; set; }
[NinjaScriptProperty]
[PropertyEditor("NinjaTrader.Gui.Tools.AutoCloseTimeEditorKey")]
[Display(Name="> Start Time 3", Description="", Order=18, GroupName="0. TIME")]
public DateTime StartTime3 { get; set; }
[NinjaScriptProperty]
[PropertyEditor("NinjaTrader.Gui.Tools.AutoCloseTimeEditorKey")]
[Display(Name="> Stop Time 3", Description="", Order=19, GroupName="0. TIME")]
public DateTime StopTime3 { get; set; }
[NinjaScriptProperty]
[Display(Name="Enable Long", Description="", Order=20, GroupName="01. ORDER MANAGEMENT")]
public bool EnableLong { get; set; }
[NinjaScriptProperty]
[Display(Name="Enable Short", Description="", Order=21, GroupName="01. ORDER MANAGEMENT")]
public bool EnableShort { get; set; }
[NinjaScriptProperty]
[Display(Name="Stay In Trade / Flat First", Description="", Order=22, GroupName="01. ORDER MANAGEMENT")]
public bool StayInTradeFlatFirst { get; set; }
[NinjaScriptProperty]
[Display(Name="Enable Limit Orders [Overides Market]", Description="By Default Entries are Market Orders", Order=23, GroupName="01. ORDER MANAGEMENT")]
public bool EnableLimitOrdersOveridesMarket { get; set; }
[NinjaScriptProperty]
[Display(Name="Enter Limit Outside of Signal", Description="If Enabled - Limit Orders Must be disabled for this option to be\r\nActive.", Order=24, GroupName="01. ORDER MANAGEMENT")]
public bool EnterLimitOutsideofSignal { get; set; }
[NinjaScriptProperty]
[Range(int.MinValue, int.MaxValue)]
[Display(Name="> Ticks Away From Signal", Description="Order Placed Above or Below Signal Bar in Ticks", Order=25, GroupName="01. ORDER MANAGEMENT")]
public int TicksAwayFromSignal { get; set; }
[NinjaScriptProperty]
[Display(Name="Chart Execution Mark", Description="Prints Arrow on Entry", Order=26, GroupName="01. ORDER MANAGEMENT")]
public bool ChartExecutionMark { get; set; }
[NinjaScriptProperty]
[Browsable(false)]
[XmlIgnore()]
public Color ExecutionMarkerColour { get; set; }
private SolidColorBrush _qs_Brush_For_ExecutionMarkerColour = null;
[XmlIgnore()]
[Display(Name="Execution Marker Colour", Description="", Order=27, GroupName="01. ORDER MANAGEMENT")]
public SolidColorBrush QS_Brush_For_ExecutionMarkerColour
{
get
{
return _qs_Brush_For_ExecutionMarkerColour;
}
set
{
_qs_Brush_For_ExecutionMarkerColour = value;
ExecutionMarkerColour = _qs_Brush_For_ExecutionMarkerColour.Color;
}
}
[Browsable(false)]
public string QS_Brush_Serialization_String_For_ExecutionMarkerColour
{
get
{
return Serialize.BrushToString(QS_Brush_For_ExecutionMarkerColour);
}
set
{
SolidColorBrush solidColorBrush = Serialize.StringToBrush(value) as SolidColorBrush;
QS_Brush_For_ExecutionMarkerColour = QS_GetBrush_SolidColor(solidColorBrush != null ? solidColorBrush.Color : Color.FromArgb(255, 255, 0, 0));
}
}
[NinjaScriptProperty]
[Range(int.MinValue, int.MaxValue)]
[Display(Name="QTY ENTRY 1", Description="Quantity- This is the Primary Entry ", Order=28, GroupName="01. ORDER MANAGEMENT")]
public int QTYENTRY1 { get; set; }
[NinjaScriptProperty]
[Display(Name="Entry 2", Description="Optional", Order=29, GroupName="01. ORDER MANAGEMENT")]
public bool Entry2 { get; set; }
[NinjaScriptProperty]
[Range(int.MinValue, int.MaxValue)]
[Display(Name="> Qty Entry 2", Description="Quantity", Order=30, GroupName="01. ORDER MANAGEMENT")]
public int QtyEntry2 { get; set; }
[NinjaScriptProperty]
[Display(Name="Entry 3", Description="Optional", Order=31, GroupName="01. ORDER MANAGEMENT")]
public bool Entry3 { get; set; }
[NinjaScriptProperty]
[Range(int.MinValue, int.MaxValue)]
[Display(Name="> Qty Entry 3", Description="Quantity", Order=32, GroupName="01. ORDER MANAGEMENT")]
public int QtyEntry3 { get; set; }
[NinjaScriptProperty]
[Display(Name="Entry 4", Description="Optional", Order=33, GroupName="01. ORDER MANAGEMENT")]
public bool Entry4 { get; set; }
[NinjaScriptProperty]
[Range(int.MinValue, int.MaxValue)]
[Display(Name="> Qty Entry 4", Description="Quantity", Order=34, GroupName="01. ORDER MANAGEMENT")]
public int QtyEntry4 { get; set; }
[NinjaScriptProperty]
[Display(Name="Entry 5", Description="Optional", Order=35, GroupName="01. ORDER MANAGEMENT")]
public bool Entry5 { get; set; }
[NinjaScriptProperty]
[Range(int.MinValue, int.MaxValue)]
[Display(Name="> Qty Entry 5", Description="Quantity", Order=36, GroupName="01. ORDER MANAGEMENT")]
public int QtyEntry5 { get; set; }
[NinjaScriptProperty]
[Display(Name="PSAR on All Entries", Description="Use with OR PSAR on Individual - If both unchecked defaults to using\r\nStatic StopLoss.", Order=37, GroupName="01. ORDER MANAGEMENT - STOPS")]
public bool PSARonAllEntries { get; set; }
[NinjaScriptProperty]
[Range(double.MinValue, double.MaxValue)]
[Display(Name="All Entries SL", Description="", Order=38, GroupName="01. ORDER MANAGEMENT - STOPS")]
public double AllEntriesSL { get; set; }
[NinjaScriptProperty]
[Display(Name="PSAR SL 1", Description="", Order=39, GroupName="01. ORDER MANAGEMENT - STOPS")]
public bool PSARSL1 { get; set; }
[NinjaScriptProperty]
[Range(double.MinValue, double.MaxValue)]
[Display(Name="> SL 1", Description="", Order=40, GroupName="01. ORDER MANAGEMENT - STOPS")]
public double SL1 { get; set; }
[NinjaScriptProperty]
[Display(Name="PSAR SL 2", Description="", Order=41, GroupName="01. ORDER MANAGEMENT - STOPS")]
public bool PSARSL2 { get; set; }
[NinjaScriptProperty]
[Range(double.MinValue, double.MaxValue)]
[Display(Name="> SL 2", Description="", Order=42, GroupName="01. ORDER MANAGEMENT - STOPS")]
public double SL2 { get; set; }
[NinjaScriptProperty]
[Display(Name="PSAR SL 3", Description="", Order=43, GroupName="01. ORDER MANAGEMENT - STOPS")]
public bool PSARSL3 { get; set; }
[NinjaScriptProperty]
[Range(double.MinValue, double.MaxValue)]
[Display(Name="> SL 3", Description="", Order=44, GroupName="01. ORDER MANAGEMENT - STOPS")]
public double SL3 { get; set; }
[NinjaScriptProperty]
[Display(Name="PSAR SL 4", Description="", Order=45, GroupName="01. ORDER MANAGEMENT - STOPS")]
public bool PSARSL4 { get; set; }
[NinjaScriptProperty]
[Range(double.MinValue, double.MaxValue)]
[Display(Name="> SL 4", Description="", Order=46, GroupName="01. ORDER MANAGEMENT - STOPS")]
public double SL4 { get; set; }
[NinjaScriptProperty]
[Display(Name="PSAR SL 5", Description="", Order=47, GroupName="01. ORDER MANAGEMENT - STOPS")]
public bool PSARSL5 { get; set; }
[NinjaScriptProperty]
[Range(double.MinValue, double.MaxValue)]
[Display(Name="> SL 5", Description="", Order=48, GroupName="01. ORDER MANAGEMENT - STOPS")]
public double SL5 { get; set; }
[NinjaScriptProperty]
[Display(Name="TP 1", Description="Optional", Order=49, GroupName="01. ORDER MANAGEMENT - TARGETS")]
public bool TP1 { get; set; }
[NinjaScriptProperty]
[Range(double.MinValue, double.MaxValue)]
[Display(Name="> Target 1", Description="Optional", Order=50, GroupName="01. ORDER MANAGEMENT - TARGETS")]
public double Target1 { get; set; }
[NinjaScriptProperty]
[Display(Name="TP 2", Description="Optional", Order=51, GroupName="01. ORDER MANAGEMENT - TARGETS")]
public bool TP2 { get; set; }
[NinjaScriptProperty]
[Range(double.MinValue, double.MaxValue)]
[Display(Name="> Target 2", Description="", Order=52, GroupName="01. ORDER MANAGEMENT - TARGETS")]
public double Target2 { get; set; }
[NinjaScriptProperty]
[Display(Name="TP 3", Description="Optional", Order=53, GroupName="01. ORDER MANAGEMENT - TARGETS")]
public bool TP3 { get; set; }
[NinjaScriptProperty]
[Range(double.MinValue, double.MaxValue)]
[Display(Name="> Target 3", Description="", Order=54, GroupName="01. ORDER MANAGEMENT - TARGETS")]
public double Target3 { get; set; }
[NinjaScriptProperty]
[Display(Name="TP 4", Description="Optional", Order=55, GroupName="01. ORDER MANAGEMENT - TARGETS")]
public bool TP4 { get; set; }
[NinjaScriptProperty]
[Range(double.MinValue, double.MaxValue)]
[Display(Name="> Target 4", Description="Optional", Order=56, GroupName="01. ORDER MANAGEMENT - TARGETS")]
public double Target4 { get; set; }
[NinjaScriptProperty]
[Display(Name="TP 5", Description="Optional", Order=57, GroupName="01. ORDER MANAGEMENT - TARGETS")]
public bool TP5 { get; set; }
[NinjaScriptProperty]
[Range(double.MinValue, double.MaxValue)]
[Display(Name="> Target 5", Description="", Order=58, GroupName="01. ORDER MANAGEMENT - TARGETS")]
public double Target5 { get; set; }
[NinjaScriptProperty]
[Display(Name="Calculation Mode Profit & Fixed SL", Description="Used for TP & Fixed SL", Order=59, GroupName="CALCULATION")]
public QS_CalculationMode CalculationModeProfitFixedSL { get; set; }
[NinjaScriptProperty]
[Display(Name="Simulated Stop Fixed", Description="", Order=60, GroupName="CALCULATION")]
public bool SimulatedStopFixed { get; set; }
[NinjaScriptProperty]
[Display(Name="Simulated Stop PSAR", Description="FOR PSAR INDIVIDUAL ", Order=61, GroupName="CALCULATION")]
public bool SimulatedStopPSAR { get; set; }
[NinjaScriptProperty]
[Display(Name="Calculation Mode PSAR", Description="", Order=62, GroupName="CALCULATION")]
public QS_CalculationMode_ParabolicTrailingStops CalculationModePSAR { get; set; }
[NinjaScriptProperty]
[Range(double.MinValue, double.MaxValue)]
[Display(Name="> PSAR Acceleration ", Description="", Order=63, GroupName="CALCULATION")]
public double PSARAcceleration { get; set; }
[NinjaScriptProperty]
[Range(double.MinValue, double.MaxValue)]
[Display(Name="> PSAR Max Acceleration", Description="", Order=64, GroupName="CALCULATION")]
public double PSARMaxAcceleration { get; set; }
[NinjaScriptProperty]
[Range(double.MinValue, double.MaxValue)]
[Display(Name="> PSAR Acceleration Step", Description="", Order=65, GroupName="CALCULATION")]
public double PSARAccelerationStep { get; set; }
[NinjaScriptProperty]
[Display(Name="Print Trade Log", Description="", Order=66, GroupName="PRINT OUTPUT")]
public bool PrintTradeLog { get; set; }
[NinjaScriptProperty]
[Display(Name="Print Indicator Values", Description="", Order=67, GroupName="PRINT OUTPUT")]
public bool PrintIndicatorValues { get; set; }
[NinjaScriptProperty]
[Display(Name="Print To CSV", Description="", Order=68, GroupName="PRINT OUTPUT")]
public bool PrintToCSV { get; set; }
[NinjaScriptProperty]
[Display(Name="> File Name", Description="", Order=69, GroupName="PRINT OUTPUT")]
public string FileName { get; set; }
[NinjaScriptProperty]
[Display(Name="Enable Debug", Description="", Order=70, GroupName="PRINT OUTPUT")]
public bool EnableDebug { get; set; }
[NinjaScriptProperty]
[Display(Name="Enable Fib-Weight MA Cross", Description="", Order=71, GroupName="FIBONACCI WEIGHTED MA")]
public bool EnableFibWeightMACross { get; set; }
[NinjaScriptProperty]
[Display(Name="Show Fib-Weight MA's", Description="", Order=72, GroupName="FIBONACCI WEIGHTED MA")]
public bool ShowFibWeightMAs { get; set; }
[NinjaScriptProperty]
[Range(3, int.MaxValue)]
[Display(Name="> Fib-Weight MA Period", Description="The number of bars, including the current bar, whose close prices\r\nshould be averaged together using weightings based on the numbers in\r\nthe Fibonacci sequence.", Order=73, GroupName="FIBONACCI WEIGHTED MA")]
public int FibWeightMAPeriod { get; set; }
[NinjaScriptProperty]
[Browsable(false)]
[XmlIgnore()]
public Color FibWeightMA { get; set; }
private SolidColorBrush _qs_Brush_For_FibWeightMA = null;
[XmlIgnore()]
[Display(Name="Fib-Weight MA", Description="", Order=74, GroupName="FIBONACCI WEIGHTED MA")]
public SolidColorBrush QS_Brush_For_FibWeightMA
{
get
{
return _qs_Brush_For_FibWeightMA;
}
set
{
_qs_Brush_For_FibWeightMA = value;
FibWeightMA = _qs_Brush_For_FibWeightMA.Color;
}
}
[Browsable(false)]
public string QS_Brush_Serialization_String_For_FibWeightMA
{
get
{
return Serialize.BrushToString(QS_Brush_For_FibWeightMA);
}
set
{
SolidColorBrush solidColorBrush = Serialize.StringToBrush(value) as SolidColorBrush;
QS_Brush_For_FibWeightMA = QS_GetBrush_SolidColor(solidColorBrush != null ? solidColorBrush.Color : Color.FromArgb(255, 255, 0, 0));
}
}
[NinjaScriptProperty]
[Range(4, int.MaxValue)]
[Display(Name="> Smoothing Simple MA Period", Description="The number of bars, including the current bar, whose\r\nFibonacci-weighted moving average values should be averaged together\r\nusing a simple moving average in order to create a smoothed version of\r\nthe Fibonacci-weighted moving average.", Order=75, GroupName="FIBONACCI WEIGHTED MA")]
public int SmoothingSimpleMAPeriod { get; set; }
[NinjaScriptProperty]
[Browsable(false)]
[XmlIgnore()]
public Color SmoothingSimpleMA { get; set; }
private SolidColorBrush _qs_Brush_For_SmoothingSimpleMA = null;
[XmlIgnore()]
[Display(Name="Smoothing Simple MA", Description="", Order=76, GroupName="FIBONACCI WEIGHTED MA")]
public SolidColorBrush QS_Brush_For_SmoothingSimpleMA
{
get
{
return _qs_Brush_For_SmoothingSimpleMA;
}
set
{
_qs_Brush_For_SmoothingSimpleMA = value;
SmoothingSimpleMA = _qs_Brush_For_SmoothingSimpleMA.Color;
}
}
[Browsable(false)]
public string QS_Brush_Serialization_String_For_SmoothingSimpleMA
{
get
{
return Serialize.BrushToString(QS_Brush_For_SmoothingSimpleMA);
}
set
{
SolidColorBrush solidColorBrush = Serialize.StringToBrush(value) as SolidColorBrush;
QS_Brush_For_SmoothingSimpleMA = QS_GetBrush_SolidColor(solidColorBrush != null ? solidColorBrush.Color : Color.FromArgb(255, 255, 0, 0));
}
}
[NinjaScriptProperty]
[Display(Name="Exit on Fib Counter Cross", Description="", Order=77, GroupName="FIBONACCI WEIGHTED MA")]
public bool ExitonFibCounterCross { get; set; }
[NinjaScriptProperty]
[Display(Name="Enable MACD Cross", Description="", Order=78, GroupName="FILTER MACD")]
public bool EnableMACDCross { get; set; }
[NinjaScriptProperty]
[Display(Name="Show MACD", Description="", Order=79, GroupName="FILTER MACD")]
public bool ShowMACD { get; set; }
[NinjaScriptProperty]
[Range(int.MinValue, int.MaxValue)]
[Display(Name="> MACD Fast EMA", Description="", Order=80, GroupName="FILTER MACD")]
public int MACDFastEMA { get; set; }
[NinjaScriptProperty]
[Range(int.MinValue, int.MaxValue)]
[Display(Name="> MACD Slow EMA", Description="", Order=81, GroupName="FILTER MACD")]
public int MACDSlowEMA { get; set; }
[NinjaScriptProperty]
[Range(int.MinValue, int.MaxValue)]
[Display(Name="> EMA Signal Line", Description="", Order=82, GroupName="FILTER MACD")]
public int EMASignalLine { get; set; }
[NinjaScriptProperty]
[Display(Name="Enable % Distance from VWAP", Description="", Order=83, GroupName="FILTERS")]
public bool EnableDistancefromVWAP { get; set; }
[NinjaScriptProperty]
[Display(Name="Enable % Distance from Bolli 500 Mid", Description="", Order=84, GroupName="FILTERS")]
public bool EnableDistancefromBolli500Mid { get; set; }
[NinjaScriptProperty]
[Display(Name="Show CP+Day", Description="", Order=85, GroupName="SUPPORT & RESISTANCE - CP+INTRADAY")]
public bool ShowCPDay { get; set; }
[NinjaScriptProperty]
[Display(Name="Show Gann Lines", Description="", Order=86, GroupName="SUPPORT & RESISTANCE")]
public bool ShowGannLines { get; set; }
[Display(Name="Show Custom Drawn Objects", Description="When this property is set to true, custom drawn objects like dots,\r\nlines, rectangles, triangles, etc., and all custom changes to other\r\nvisuals, such as the chart background color, will be visible on the\r\nchart. If you want large optimizations of your strategy to run faster\r\nand don't need to see the custom drawn objects and custom painting,\r\nset this property to false. The value of this property only affects\r\nobjects that are drawn using the custom drawing functions built into\r\nQuagensia. Plots of indicators, editable time series, and horizontal\r\nlines that are configured by checking the \"Plot This\" check boxes in\r\nthe \"Internal Variables\" and \"Input Parameters\" sections of a\r\nQuagensia Strategy are not affected by the value of this property.", Order=87, GroupName ="Parameters")]
public bool QS_DoCustomDrawingAndPainting_UserPreference { get; set; }
[Display(Name="Print to NinjaScript® Output Window ", Description="If this strategy normally prints to the NinjaScript® Output window\r\nusing the \"Print to Output Window\" functions built into Quagensia, you\r\ncan set this parameter to \"false\" instead of \"true\" to cause your\r\nstrategy to not print to the NinjaScript® Output window. Setting this\r\ninput parameter to \"false\" can improve the performance of your\r\nstrategy in scenarios where it would otherwise print to the\r\nNinjaScript® Output window thousands of times, including reducing the\r\ntime it takes to finish an optimization of your strategy over a large\r\nnumber of parameter sets. Examples of situations where you should\r\nconsider setting this input parameter to \"false\" to stop all printing\r\nto the NinjaScript® Output window include situations such as if your\r\nstrategy normally prints to the NinjaScript® Output window on every\r\nbar or tick or on a high percentage of bars or ticks and you are\r\nrunning it on a chart with many thousands of bars or ticks, or if you\r\nare optimizing this strategy over a large number of parameter sets.", Order=88, GroupName ="Parameters")]
public bool QS_DoPrintToOutputWindow_UserPreference { get; set; }
#endregion
#region Dynamically Generated Quagensia Functions (Created by Quagensia, Inc. and/or Other Users of Quagensia). Do Not Change Or Delete.
private string GetUDefStrategyInputParamsAsStructuredText(string TexttoAddtotheBeginningoftheReturnValue, string TexttoAddtotheEndoftheReturnValue, string TexttoAddtotheBeginningofEachSetofInputParameterNameValuePairs, string TexttoAddtotheEndofEachSetofInputParameterNameValuePairs, string TexttoAddBetweenEachSetofInputParameterNameValuePairs, string TexttoAddBetweentheInputParameterNameandValue, string TexttoReturnInsteadofInputParameterNameValuePairsIfNoInputParameters)
{
string returnString = "";
List<PropertyInfo> inputParamPropertyInfos = this.GetType()
.GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList()
.Where(pi => pi.GetIndexParameters().Length == 0
&& Attribute.IsDefined(pi, typeof(NinjaScriptPropertyAttribute))).ToList();
int inputParamPropertyInfosCount = inputParamPropertyInfos.Count;
if (inputParamPropertyInfosCount > 0)
{
StringBuilder s = new StringBuilder();
for (int i = 0; i < inputParamPropertyInfosCount; i++)
{
PropertyInfo inputParamPropertyInfo = inputParamPropertyInfos[i];
string propertyName = string.Empty;
string propertyValue = string.Empty;
try
{
propertyName = inputParamPropertyInfo.Name;
object propertyValueObject = inputParamPropertyInfo.GetValue(this, null);
propertyValue = propertyValueObject == null ? "null" : propertyValueObject.ToString();
}
catch
{
if (propertyName == string.Empty)
propertyName = "Property Name Unknown Because An Error Occurred";
if (propertyValue == string.Empty)
propertyValue = "Property Value Unknown Because An Error Occurred";
}
s.Append(TexttoAddtotheBeginningofEachSetofInputParameterNameValuePairs).Append(propertyName).Append(TexttoAddBetweentheInputParameterNameandValue).Append(propertyValue).Append(TexttoAddtotheEndofEachSetofInputParameterNameValuePairs);
if (i < inputParamPropertyInfosCount - 1)
s.Append(TexttoAddBetweenEachSetofInputParameterNameValuePairs);
}
returnString = TexttoAddtotheBeginningoftheReturnValue + s.ToString() + TexttoAddtotheEndoftheReturnValue;
}
else
{
returnString = TexttoAddtotheBeginningoftheReturnValue + TexttoReturnInsteadofInputParameterNameValuePairsIfNoInputParameters + TexttoAddtotheEndoftheReturnValue;
}
return returnString;
}
private string GetStrategyInputParamsAsText()
{
return GetUDefStrategyInputParamsAsStructuredText("", "", "", "", "\r\n", ": ", "This strategy has no user-defined input parameters.");
}
#endregion
#region Quagensia System Functions. Do Not Change Or Delete.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Quagensia N Edition's system functions are below. Do not change anything below this line.
// The following copyright notice applies to all code and other content below this line:
// Copyright © 2023-2024 Quagensia, Inc. All rights reserved.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void QS_Indicator_OnInit_Plot_Plot<T>(ref T indicator, int plotIndex, Brush plotColorBrush, int? plotWidth, PlotStyle? plotStyle, DashStyleHelper? dashStyleHelper) where T : IndicatorBase
{
if (plotIndex >= 0 && plotIndex < indicator.Plots.Length)
{
if (plotColorBrush != null)
indicator.Plots[plotIndex].Brush = plotColorBrush;
if (plotWidth.HasValue)
indicator.Plots[plotIndex].Width = plotWidth.Value;
if (plotStyle.HasValue)
indicator.Plots[plotIndex].PlotStyle = plotStyle.Value;
if (dashStyleHelper.HasValue)
indicator.Plots[plotIndex].DashStyleHelper = dashStyleHelper.Value;
}
}
private void QS_Indicator_OnInit_Plot_Indicator<T>(ref T indicator, bool plotOnDefaultPanel, QS_TrueFalseOrUseDefaultValue overlayOnMainChartPanel, int plotOnPanelNumber) where T : IndicatorBase
{
AddChartIndicator(indicator);
if (!plotOnDefaultPanel)
{
if (overlayOnMainChartPanel != QS_TrueFalseOrUseDefaultValue.QS_TriStateBoolean_UseDefaultValue)
indicator.IsOverlay = (overlayOnMainChartPanel == QS_TrueFalseOrUseDefaultValue.QS_TriStateBoolean_True);
indicator.Panel = plotOnPanelNumber - 1;
}
}
private int QS_GetPlotIndexByName (string plotName)
{
for (int i = 0; i < Plots.Length; i++)
{
if (string.Compare(Plots[i].Name, plotName, StringComparison.Ordinal) == 0)
return i;
}
return -1;
}
private void QS_DrawSquare(NinjaScriptBase owner, bool isAutoScale, int barsAgo, double y, Color color, bool drawOnPricePanel)
{
if (QS_DrawCustomObjects())
{
string newGuidString = QS_NewGuidString();
string uniqueTagName = "QS_Square_" + newGuidString + "_" + QS_Int32ToString_Unformatted_ValueStore(CurrentBar) + "_" + QS_DoubleToString_ComputerReadable(y, 17);
QS_DrawOrModifySquare(owner, uniqueTagName, isAutoScale, barsAgo, y, color, drawOnPricePanel);
}
}
private void QS_DrawOrModifySquare(NinjaScriptBase owner, string tag, bool isAutoScale, int barsAgo, double y, Color color, bool drawOnPricePanel)
{
if (QS_DrawCustomObjects())
Draw.Square(owner, tag, isAutoScale, barsAgo, y, QS_GetBrush_SolidColor(color), drawOnPricePanel);
}
private void QS_DrawArrowUp(NinjaScriptBase owner, bool isAutoScale, int barsAgo, double y, Color color, bool drawOnPricePanel)
{
if (QS_DrawCustomObjects())
{
string newGuidString = QS_NewGuidString();
string uniqueTagName = "QS_ArrowUp_" + newGuidString + "_" + QS_Int32ToString_Unformatted_ValueStore(CurrentBar) + "_" + QS_DoubleToString_ComputerReadable(y, 17);
QS_DrawOrModifyArrowUp(owner, uniqueTagName, isAutoScale, barsAgo, y, color, drawOnPricePanel);
}
}
private void QS_DrawOrModifyArrowUp(NinjaScriptBase owner, string tag, bool isAutoScale, int barsAgo, double y, Color color, bool drawOnPricePanel)
{
if (QS_DrawCustomObjects())
Draw.ArrowUp(owner, tag, isAutoScale, barsAgo, y, QS_GetBrush_SolidColor(color), drawOnPricePanel);
}
private void QS_DrawArrowDown(NinjaScriptBase owner, bool isAutoScale, int barsAgo, double y, Color color, bool drawOnPricePanel)
{
if (QS_DrawCustomObjects())
{
string newGuidString = QS_NewGuidString();
string uniqueTagName = "QS_ArrowDown_" + newGuidString + "_" + QS_Int32ToString_Unformatted_ValueStore(CurrentBar) + "_" + QS_DoubleToString_ComputerReadable(y, 17);
QS_DrawOrModifyArrowDown(owner, uniqueTagName, isAutoScale, barsAgo, y, color, drawOnPricePanel);
}
}
private void QS_DrawOrModifyArrowDown(NinjaScriptBase owner, string tag, bool isAutoScale, int barsAgo, double y, Color color, bool drawOnPricePanel)
{
if (QS_DrawCustomObjects())
Draw.ArrowDown(owner, tag, isAutoScale, barsAgo, y, QS_GetBrush_SolidColor(color), drawOnPricePanel);
}
private void QS_DrawTriangleUp(NinjaScriptBase owner, bool isAutoScale, int barsAgo, double y, Color color, bool drawOnPricePanel)
{
if (QS_DrawCustomObjects())
{
string newGuidString = QS_NewGuidString();
string uniqueTagName = "QS_TriangleUp_" + newGuidString + "_" + QS_Int32ToString_Unformatted_ValueStore(CurrentBar) + "_" + QS_DoubleToString_ComputerReadable(y, 17);
QS_DrawOrModifyTriangleUp(owner, uniqueTagName, isAutoScale, barsAgo, y, color, drawOnPricePanel);
}
}
private void QS_DrawOrModifyTriangleUp(NinjaScriptBase owner, string tag, bool isAutoScale, int barsAgo, double y, Color color, bool drawOnPricePanel)
{
if (QS_DrawCustomObjects())
Draw.TriangleUp(owner, tag, isAutoScale, barsAgo, y, QS_GetBrush_SolidColor(color), drawOnPricePanel);
}
private void QS_DrawTriangleDown(NinjaScriptBase owner, bool isAutoScale, int barsAgo, double y, Color color, bool drawOnPricePanel)
{
if (QS_DrawCustomObjects())
{
string newGuidString = QS_NewGuidString();
string uniqueTagName = "QS_TriangleDown_" + newGuidString + "_" + QS_Int32ToString_Unformatted_ValueStore(CurrentBar) + "_" + QS_DoubleToString_ComputerReadable(y, 17);
QS_DrawOrModifyTriangleDown(owner, uniqueTagName, isAutoScale, barsAgo, y, color, drawOnPricePanel);
}
}
private void QS_DrawOrModifyTriangleDown(NinjaScriptBase owner, string tag, bool isAutoScale, int barsAgo, double y, Color color, bool drawOnPricePanel)
{
if (QS_DrawCustomObjects())
Draw.TriangleDown(owner, tag, isAutoScale, barsAgo, y, QS_GetBrush_SolidColor(color), drawOnPricePanel);
}
private void QS_DrawTriangle(NinjaScriptBase owner, bool isAutoScale, int startBarsAgo, double startY, int middleBarsAgo, double middleY, int endBarsAgo, double endY, Color colorBorder, Color colorArea, int areaOpacity, bool drawOnPricePanel)
{
if (QS_DrawCustomObjects())
{
string newGuidString = QS_NewGuidString();
string uniqueTagName = "QS_Triangle_" + newGuidString + "_" + QS_Int32ToString_Unformatted_ValueStore(CurrentBar) + "_" + QS_Int32ToString_Unformatted_ValueStore(startBarsAgo)
+ "_" + QS_DoubleToString_ComputerReadable(startY, 17) + "_" + QS_Int32ToString_Unformatted_ValueStore(middleBarsAgo) + "_" + QS_DoubleToString_ComputerReadable(middleY, 17)
+ "_" + QS_Int32ToString_Unformatted_ValueStore(endBarsAgo)+ "_" + QS_DoubleToString_ComputerReadable(endY, 17);
QS_DrawOrModifyTriangle(owner, uniqueTagName, isAutoScale, startBarsAgo, startY, middleBarsAgo, middleY, endBarsAgo, endY, colorBorder, colorArea, areaOpacity, drawOnPricePanel);
}
}
private void QS_DrawOrModifyTriangle(NinjaScriptBase owner, string tag, bool isAutoScale, int startBarsAgo, double startY, int middleBarsAgo, double middleY, int endBarsAgo, double endY, Color colorBorder, Color colorArea, int areaOpacity, bool drawOnPricePanel)
{
if (QS_DrawCustomObjects())
Draw.Triangle(owner, tag, isAutoScale, startBarsAgo, startY, middleBarsAgo, middleY, endBarsAgo, endY, QS_GetBrush_SolidColor(colorBorder), QS_GetBrush_SolidColor(colorArea), areaOpacity, drawOnPricePanel);
}
private bool QS_DrawCustomObjects()
{
return QS_DoCustomDrawingAndPainting_UserPreference;
}
private void QS_Print(string messageToPrint)
{
if (QS_PrintToOutputWindow())
Print(messageToPrint);
}
private bool QS_PrintToOutputWindow()
{
return QS_DoPrintToOutputWindow_UserPreference;
}
private void QS_OnTerminated()
{
lock (QS_LockObject_Drawing)
{
if (QS_Brushes_SolidColor_Custom != null)
{
List<Color> keys = new List<Color>(QS_Brushes_SolidColor_Custom.Keys);
foreach (Color key in keys)
QS_Brushes_SolidColor_Custom[key] = null;
QS_Brushes_SolidColor_Custom = null;
}
}
}
private static ReaderWriterLockSlim QS_ReaderWriterLockSlim = null;
private static object QS_LockObject_FileIO = new object();
private static string QS_File_ReadAllTextFromTextFile(string filePath, Encoding encoding, bool detectEncodingFromByteOrderMarks)
{
if (QS_ReaderWriterLockSlim == null)
{
lock (QS_LockObject_FileIO)
{
if (QS_ReaderWriterLockSlim == null)
QS_ReaderWriterLockSlim = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
}
}
try
{
QS_ReaderWriterLockSlim.EnterReadLock();
using (StreamReader streamReader = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read), encoding, detectEncodingFromByteOrderMarks))
{
return streamReader.ReadToEnd();
}
}
finally
{
QS_ReaderWriterLockSlim.ExitReadLock();
}
}
private static void QS_File_WriteTextToTextFile(string filePath, bool appendDontOverwrite, Encoding encoding, string stringToWriteToFile)
{
if (QS_ReaderWriterLockSlim == null)
{
lock (QS_LockObject_FileIO)
{
if (QS_ReaderWriterLockSlim == null)
QS_ReaderWriterLockSlim = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
}
}
try
{
QS_ReaderWriterLockSlim.EnterWriteLock();
using (StreamWriter streamWriter = new StreamWriter(new FileStream(filePath, (appendDontOverwrite ? FileMode.Append : FileMode.Create), FileAccess.Write, FileShare.None), encoding))
{
streamWriter.Write(stringToWriteToFile);
}
}
finally
{
QS_ReaderWriterLockSlim.ExitWriteLock();
}
}
private static void QS_Directory_CreateParentDirectoryIfDoesNotExist(string fileOrDirectoryPath)
{
DirectoryInfo parentDirectory = Directory.GetParent(fileOrDirectoryPath);
string parentDirectoryPath = parentDirectory.FullName;
QS_Directory_CreateDirectoryIfDoesNotExist(parentDirectoryPath);
}
private static void QS_Directory_CreateDirectoryIfDoesNotExist(string fileOrDirectoryPath)
{
if (!Directory.Exists(fileOrDirectoryPath))
Directory.CreateDirectory(fileOrDirectoryPath);
}
private static object QS_LockObject_Drawing = new object();
private SolidColorBrush QS_GetBrush_SolidColor(Color color)
{
SolidColorBrush b = QS_GetBrush_SolidColor_System(color);
if (b != null)
return b;
else
return QS_GetBrush_SolidColor_Custom(color);
}
private Dictionary<Color, SolidColorBrush> QS_Brushes_SolidColor_Custom = null;
private SolidColorBrush QS_GetBrush_SolidColor_Custom(Color color)
{
SolidColorBrush b = null;
lock (QS_LockObject_Drawing)
{
if (QS_Brushes_SolidColor_Custom == null)
QS_Brushes_SolidColor_Custom = new Dictionary<Color, SolidColorBrush>();
if (!QS_Brushes_SolidColor_Custom.TryGetValue(color, out b))
{
b = new SolidColorBrush(color);
b.Freeze();
QS_Brushes_SolidColor_Custom.Add(color, b);
}
}
return b;
}
private Dictionary<Color, SolidColorBrush> QS_Brushes_SolidColor_System = null;
private SolidColorBrush QS_GetBrush_SolidColor_System(Color color)
{
SolidColorBrush b = null;
lock (QS_LockObject_Drawing)
{
if (QS_Brushes_SolidColor_System == null)
QS_Populate_Brushes_SolidColor_System();
QS_Brushes_SolidColor_System.TryGetValue(color, out b);
}
return b;
}
private void QS_Populate_Brushes_SolidColor_System()
{
lock (QS_LockObject_Drawing)
{
QS_Brushes_SolidColor_System = new Dictionary<Color, SolidColorBrush>();
PropertyInfo[] brushPropertyInfos = typeof(Brushes).GetProperties(BindingFlags.Static | BindingFlags.Public);
foreach (PropertyInfo brushPropertyInfo in brushPropertyInfos)
{
SolidColorBrush b = brushPropertyInfo.GetValue(null) as SolidColorBrush;
if (b != null && !QS_Brushes_SolidColor_System.ContainsKey(b.Color))
QS_Brushes_SolidColor_System.Add(b.Color, b);
}
}
}
private static double QS_SumOfValuesInArray_Doubles(ref double[] array)
{
double sum = 0;
foreach (double doubleValue in array)
sum += doubleValue;
return sum;
}
private static int QS_SumOfValuesInArray_Int32s(ref int[] array)
{
int sum = 0;
foreach (int intValue in array)
sum += intValue;
return sum;
}
private static long QS_SumOfValuesInArray_Int64s(ref long[] array)
{
long sum = 0;
foreach (long longValue in array)
sum += longValue;
return sum;
}
private static double QS_SumOfValuesInArray<T>(ref T[] array)
{
if (array.Length > 0 && QS_TypeIsNumeric(typeof(T)))
{
double sum = 0;
foreach (T t in array)
sum += Convert.ToDouble(t);
return sum;
}
else
{
return 0;
}
}
private static void QS_ReverseArray<T>(ref T[] arrayToReverse)
{
arrayToReverse = arrayToReverse.Reverse().ToArray();
}
private static void QS_InitializeArray<T>(ref T[] arrayToInitialize, T valueToSetAllItemsTo)
{
for (int i = 0; i < arrayToInitialize.GetLength(0); i++)
arrayToInitialize[i] = valueToSetAllItemsTo;
}
private static void QS_InitializeArray<T>(ref T[,] arrayToInitialize, T valueToSetAllItemsTo)
{
for (int i = 0; i < arrayToInitialize.GetLength(0); i++)
for (int j = 0; j < arrayToInitialize.GetLength(1); j++)
arrayToInitialize[i, j] = valueToSetAllItemsTo;
}
private static void QS_InitializeArray<T>(ref T[,,] arrayToInitialize, T valueToSetAllItemsTo)
{
for (int i = 0; i < arrayToInitialize.GetLength(0); i++)
for (int j = 0; j < arrayToInitialize.GetLength(1); j++)
for (int k = 0; k < arrayToInitialize.GetLength(2); k++)
arrayToInitialize[i, j, k] = valueToSetAllItemsTo;
}
private static void QS_InitializeArray<T>(ref T[,,,] arrayToInitialize, T valueToSetAllItemsTo)
{
for (int i = 0; i < arrayToInitialize.GetLength(0); i++)
for (int j = 0; j < arrayToInitialize.GetLength(1); j++)
for (int k = 0; k < arrayToInitialize.GetLength(2); k++)
for (int m = 0; m < arrayToInitialize.GetLength(3); m++)
arrayToInitialize[i, j, k, m] = valueToSetAllItemsTo;
}
private static void QS_ReDimArray<T>(ref T[] arrayToRedim, int newDim1Length, T defaultValue)
{
T[] arrayWithNewDimensionSizes = new T[newDim1Length];
int oldDim1Length = arrayToRedim.GetLength(0);
for (int i = 0; i < newDim1Length; i++)
arrayWithNewDimensionSizes[i] = (i < oldDim1Length) ? arrayToRedim[i] : defaultValue;
arrayToRedim = arrayWithNewDimensionSizes;
}
private static void QS_ReDimArray<T>(ref T[,] arrayToRedim, int newDim1Length, int newDim2Length, T defaultValue)
{
T[,] arrayWithNewDimensionSizes = new T[newDim1Length, newDim2Length];
int oldDim1Length = arrayToRedim.GetLength(0);
int oldDim2Length = arrayToRedim.GetLength(1);
for (int i = 0; i < newDim1Length; i++)
for (int j = 0; j < newDim2Length; j++)
arrayWithNewDimensionSizes[i, j] = (i < oldDim1Length && j < oldDim2Length) ? arrayToRedim[i, j] : defaultValue;
arrayToRedim = arrayWithNewDimensionSizes;
}
private static void QS_ReDimArray<T>(ref T[,,] arrayToRedim, int newDim1Length, int newDim2Length, int newDim3Length, T defaultValue)
{
T[,,] arrayWithNewDimensionSizes = new T[newDim1Length, newDim2Length, newDim3Length];
int oldDim1Length = arrayToRedim.GetLength(0);
int oldDim2Length = arrayToRedim.GetLength(1);
int oldDim3Length = arrayToRedim.GetLength(2);
for (int i = 0; i < newDim1Length; i++)
for (int j = 0; j < newDim2Length; j++)
for (int k = 0; k < newDim3Length; k++)
arrayWithNewDimensionSizes[i, j, k]
= (i < oldDim1Length && j < oldDim2Length && k < oldDim3Length) ? arrayToRedim[i, j, k] : defaultValue;
arrayToRedim = arrayWithNewDimensionSizes;
}
private static void QS_ReDimArray<T>(ref T[,,,] arrayToRedim, int newDim1Length, int newDim2Length, int newDim3Length, int newDim4Length, T defaultValue)
{
T[,,,] arrayWithNewDimensionSizes = new T[newDim1Length, newDim2Length, newDim3Length, newDim4Length];
int oldDim1Length = arrayToRedim.GetLength(0);
int oldDim2Length = arrayToRedim.GetLength(1);
int oldDim3Length = arrayToRedim.GetLength(2);
int oldDim4Length = arrayToRedim.GetLength(3);
for (int i = 0; i < newDim1Length; i++)
for (int j = 0; j < newDim2Length; j++)
for (int k = 0; k < newDim3Length; k++)
for (int m = 0; m < newDim4Length; m++)
arrayWithNewDimensionSizes[i, j, k, m]
= (i < oldDim1Length && j < oldDim2Length && k < oldDim3Length && m < oldDim4Length) ? arrayToRedim[i, j, k, m] : defaultValue;
arrayToRedim = arrayWithNewDimensionSizes;
}
private static string QS_ConvertListToString<T>(List<T> listToPrint, string returnStringPrefix, string returnStringSuffix, string itemPrefix, string itemSuffix, string itemDelimiter)
{
StringBuilder s = new StringBuilder();
int count = listToPrint.Count;
for (int i = 0; i < count; i++)
{
s.Append(itemPrefix).Append(listToPrint[i]).Append(itemSuffix);
if (i < count - 1)
s.Append(itemDelimiter);
}
return returnStringPrefix + QS_ToString(s) + returnStringSuffix;
}
private static void QS_SortList<T>(ref List<T> listToSort, bool sortInDescendingOrder)
{
if (listToSort.Count > 0 && (listToSort[0] is IComparable || listToSort[0] is IComparable<T>))
{
if (sortInDescendingOrder)
listToSort = listToSort.OrderByDescending(i => i).ToList();
else
listToSort = listToSort.OrderBy(i => i).ToList();
}
}
private static DateTime QS_DateTime_TimeOfDay(DateTime dateTime)
{
return new DateTime(DateTime.MinValue.Year, DateTime.MinValue.Month, DateTime.MinValue.Day, dateTime.Hour, dateTime.Minute, dateTime.Second).AddTicks(dateTime.TimeOfDay.Ticks % TimeSpan.TicksPerSecond);
}
private static DateTime QS_DateTime_From_Date_And_TimeOfDay(DateTime date, DateTime time)
{
return new DateTime(date.Year, date.Month, date.Day, time.Hour, time.Minute, time.Second).AddTicks(time.TimeOfDay.Ticks % TimeSpan.TicksPerSecond);
}
private static string QS_Int32ToString_Unformatted_ValueStore(int intValue)
{
return intValue.ToString(CultureInfo.InvariantCulture);
}
private static string QS_Int64ToString_Unformatted_ValueStore(long longValue)
{
return longValue.ToString(CultureInfo.InvariantCulture);
}
private static string QS_ToString(object value)
{
if (value == null)
return string.Empty;
else if (value is System.DateTime)
return QS_DateTimeToString_FullPrecision_InvariantCulture((System.DateTime)value);
else if (value is System.Double)
return QS_DoubleToString_FullPrecision_CurrentCulture((System.Double)value);
else if (value is System.Single)
return QS_SingleToString_FullPrecision_CurrentCulture((System.Single)value);
return value.ToString();
}
private static string QS_DateTimeToString_FullPrecision_InvariantCulture(DateTime value)
{
return value.ToString("yyyy-MM-dd HH:mm:ss.FFFFFFF", CultureInfo.InvariantCulture);
}
private static string QS_DoubleToString_FullPrecision_CurrentCulture(double value)
{
return value.ToString("G17");
}
private static string QS_SingleToString_FullPrecision_CurrentCulture(float value)
{
return value.ToString("G9");
}
private static string QS_DoubleToString_ComputerReadable_Not_Rounded_FormatInfoString = "0." + new string('#', 339);
private static string QS_DoubleToString_ComputerReadable(double doubleValue)
{
return doubleValue.ToString(QS_DoubleToString_ComputerReadable_Not_Rounded_FormatInfoString, System.Globalization.CultureInfo.InvariantCulture);
}
private static string QS_DoubleToString_ComputerReadable(double doubleValue, int roundingDecimalPlaces)
{
return doubleValue.ToString("0." + new string('#', roundingDecimalPlaces), System.Globalization.CultureInfo.InvariantCulture);
}
private static string QS_NewGuidString()
{
Guid guid = Guid.NewGuid();
return QS_GetHGuidString(guid);
}
private static string QS_GetHGuidString(Guid guid)
{
return guid.ToString("N", CultureInfo.InvariantCulture);
}
private static HashSet<Type> QS_NumericTypes
= new HashSet<Type>() { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong),
typeof(float), typeof(double), typeof(decimal) };
private static bool QS_TypeIsNumeric(Type typeToCheckIfIsNumeric)
{
return QS_NumericTypes.Contains(typeToCheckIfIsNumeric);
}
public enum QS_TrueFalseOrUseDefaultValue
{
QS_TriStateBoolean_False = 1,
QS_TriStateBoolean_True = 2,
QS_TriStateBoolean_UseDefaultValue = 3
}
public enum QS_CalculationMode
{
Currency__WARNING_StopTargetHandling_Must_Be_Set_To_ByStrategyPosition = CalculationMode.Currency,
Percent = CalculationMode.Percent,
Pips = CalculationMode.Pips,
Price = CalculationMode.Price,
Ticks = CalculationMode.Ticks
}
public enum QS_CalculationMode_TrailingStops
{
Percent = CalculationMode.Percent,
Pips = CalculationMode.Pips,
Ticks = CalculationMode.Ticks
}
public enum QS_CalculationMode_ParabolicTrailingStops
{
Currency__WARNING_StopTargetHandling_Must_Be_Set_To_ByStrategyPosition = CalculationMode.Currency,
Percent = CalculationMode.Percent,
Pips = CalculationMode.Pips,
Ticks = CalculationMode.Ticks
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment