ErrorCode--Crashed in OnTick with NullReferenceException: Object reference not set to an instance of an object.
ErrorCode--Crashed in OnTick with NullReferenceException: Object reference not set to an instance of an object.
24 May 2018, 02:24
Hi.I received ErrorCode↓ Crashed in OnTick with NullReferenceException: Object reference not set to an instance of an object. Im not a programmer so I can't find problems. Pls help me.Thank you for looking. using System; using System.Linq; using cAlgo.API; using cAlgo.API.Indicators; using cAlgo.API.Internals; using cAlgo.API.Requests; using cAlgo.Indicators; namespace cAlgo.Robots { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)] public class Main : Robot { //Prameters //Main [Parameter("Source")] public DataSeries Source { get; set; } [Parameter("Volume", DefaultValue = 1000, MinValue = 1000)] public int Volume { get; set; } [Parameter("TakeProfit(pips)", DefaultValue = 60, MinValue = 1)] public int TakeProfitPI { get; set; } [Parameter("Stop Loss (pips)", DefaultValue = 80, MinValue = 1)] public int StopLossPI { get; set; } [Parameter("Max Slippage (pips)", DefaultValue = 4, MinValue = 0)] public double SlippagePI { get; set; } [Parameter("Trail start(pips)", DefaultValue = 29, MinValue = 1)] public int Trailstart { get; set; } [Parameter("Trail", DefaultValue = 3, MinValue = 1)] public int Trail { get; set; } [Parameter("Compression Rario", DefaultValue = 4)] public int CR { get; set; } [Parameter("Expansion", DefaultValue = 3)] public int ER { get; set; } //STO [Parameter("K Periods", DefaultValue = 5)] public int KPeriods { get; set; } [Parameter("D Periods", DefaultValue = 3)] public int DPeriods { get; set; } [Parameter("K Slowing", DefaultValue = 3)] public int KSlowing { get; set; } //for divergence [Parameter("STOcycle", DefaultValue = 6)] public int SC { get; set; } //RSI [Parameter("Periods RSI", DefaultValue = 14)] public int PeriodsRSI { get; set; } //SMA [Parameter("Periods SMA-M720", DefaultValue = 144)] public int PeriodsSMAM720 { get; set; } [Parameter("Periods SMA-H48", DefaultValue = 48)] public int PeriodsSMAH48 { get; set; } [Parameter("Periods SMA-D21", DefaultValue = 21)] public int PeriodsSMAD21 { get; set; } [Parameter("Periods SMA-D200", DefaultValue = 200)] public int PeriodsSMAD200 { get; set; } //MACD [Parameter("Periods MACD", DefaultValue = 9)] public int PeriodsMACD { get; set; } [Parameter("ShortCyvle", DefaultValue = 12)] public int ShortCycle { get; set; } [Parameter("LongCyvle", DefaultValue = 26)] public int LongCycle { get; set; } //for divergence [Parameter("MACDcycle", DefaultValue = 20)] public int MC { get; set; } //BB [Parameter("Bollinger Bands Periods", DefaultValue = 21)] public int BBPeriods { get; set; } [Parameter("Band Height (pips)", DefaultValue = 40.0, MinValue = 0)] public double BHPI { get; set; } [Parameter("Consolidation Periods", DefaultValue = 2)] public int CPeriods { get; set; } [Parameter("EquityStop", DefaultValue = 2)] public int EquityStop { get; set; } [Parameter("Balance Stop Loss (ratio)", DefaultValue = 0.2, MinValue = 0, MaxValue = 1)] public double BalanceStop { get; set; } // Maximum simultaneous long positions [Parameter("Max Long Positions", DefaultValue = 2, MinValue = 0)] public int MaxLongP { get; set; } [Parameter("Max Short Positions", DefaultValue = 2, MinValue = 0)] public int MaxShortP { get; set; } [Parameter("Trade Biasing", DefaultValue = 3, MinValue = 0, MaxValue = 3)] public int Bias { get; set; } // Minimum time delay between trades [Parameter("Trade Delay Count (bars)", DefaultValue = 4, MinValue = 1)] public int TradeDelayBC { get; set; } // Minimum time delay between trades [Parameter("Trade Delay Count (trade entry times)", DefaultValue = 2, MinValue = 1)] public int TradeDelayTC { get; set; } // Trade suspension period on loss [Parameter("Wait on Loss (bars)", DefaultValue = 0, MinValue = 0)] public int WaitOnLoss { get; set; } //instance number [Parameter("Number", DefaultValue = 1, MinValue = 1)] public int Number { get; set; } [Parameter("Max Tries", DefaultValue = 20, MinValue = 2)] public double MaxTries { get; set; } //near Trail [Parameter("Trigger (pips)", DefaultValue = 2.0, MinValue = 0)] public double TriggerPips { get; set; } [Parameter("Trail SL (pips)", DefaultValue = 10.0, MinValue = 0)] public double TrailSLPips { get; set; } [Parameter("Trail TP (pips)", DefaultValue = 5.0, MinValue = 0)] public double TrailTPPips { get; set; } [Parameter("Time Filter(AM4-AM8)", DefaultValue = true)] public bool TimeFilter { get; set; } [Parameter("Trade Delay (bars)", DefaultValue = true)] public bool TradeDelayBFilter { get; set; } // Minimum time delay between trades [Parameter("Trade Delay (trade entry times)", DefaultValue = true)] public bool TradeDelayTFilter { get; set; } [Parameter("Close All on Bot Stop", DefaultValue = false)] public bool CloseOnStop { get; set; } [Parameter("Chaos Filter", DefaultValue = false)] public bool ChaosFilter { get; set; } [Parameter("Pibot Filter", DefaultValue = false)] public bool PibotFilter { get; set; } [Parameter("Martingale Enabled", DefaultValue = false)] public bool Martingale { get; set; } [Parameter("OCO Mode", DefaultValue = false)] public bool OCOMode { get; set; } [Parameter("Probability Mode", DefaultValue = false)] public bool ProbabilityMode { get; set; } [Parameter("Trade Probability(%)", DefaultValue = 80, MinValue = 0, MaxValue = 100)] public int P { get; set; } private Random rand = new Random(); //-------------------------------------------------------------------------------- // Globals private StochasticOscillator STO; private StochasticOscillator STO4; private RelativeStrengthIndex RSI; private RelativeStrengthIndex RSI4; private SimpleMovingAverage SMAH48; private MacdHistogram MACD4; private BollingerBands bB; private Symbol sym = null; private Position pos = null; //defination private const int STOhigh = 80, STOlow = 20, RSIhigh = 70, RSIlow = 30; private const double MACDhigh = 0.0006, MACDlow = -0.0006; private string botName, type; private double openingBalance = 0; private bool tradeSafe = true, buySafe = true, sellSafe = true; private double? newStopLossPR = 0, newTakeProfitPR = 0; private int randomNumber; private double highp, lowp, closep, pivot, Wpivot, FrB, FsB, Wr3, Ws3; private int MartingaleActive = 0, LongPositions = 0, ShortPositions = 0, BarCount = 0, TradeCount = 4, c = 0; //--------------------------------------------------------------------------------------------------------- protected override void OnStart() { botName = "MyMainBot" + "-" + type + "-" + Symbol.Code + "-" + MarketSeries.TimeFrame; openingBalance = Account.Balance; STO = Indicators.StochasticOscillator(KPeriods, KSlowing, DPeriods, MovingAverageType.Exponential); STO4 = Indicators.StochasticOscillator(KPeriods * CR, KSlowing * CR, DPeriods * CR, MovingAverageType.Exponential); RSI = Indicators.RelativeStrengthIndex(Source, PeriodsRSI); RSI4 = Indicators.RelativeStrengthIndex(Source, PeriodsRSI * CR); SMAH48 = Indicators.SimpleMovingAverage(Source, 48 * CR); MACD4 = Indicators.MacdHistogram(LongCycle * CR, ShortCycle * CR, PeriodsMACD * CR); bB = Indicators.BollingerBands(Source, BBPeriods * CR, 2, MovingAverageType.Simple); highp = MarketSeries.High.LastValue; lowp = MarketSeries.Low.LastValue; closep = MarketSeries.Close.LastValue; pivot = (highp + lowp + closep) / 3; Wpivot = (highp + lowp + (2 * closep)) / 4; FrB = pivot + (highp - lowp) * 1.382; FsB = pivot - (highp - lowp) * 1.382; Wr3 = Wpivot + 2 * (highp - lowp); Ws3 = Wpivot - 2 * (highp - lowp); Positions.Opened += onPositionsOpened; Positions.Closed += onPositionsClosed; // Identify existing trades from this instance foreach (var pos in Positions) { if (pos.Label == botName) switch (pos.TradeType) { case TradeType.Buy: LongPositions++; break; case TradeType.Sell: ShortPositions++; break; } } } protected override void OnStop() { if (CloseOnStop) closeAll(); } protected override void OnBar() { BarCount++; if (BarCount == 10) { Print("Barcount=10"); } if (BarCount == 20) { Print("Barcount=20"); } } /*var top = bB.Top.Last(1); var bottom = bB.Bottom.Last(1); if (top - bottom <= BHPI * Symbol.PipSize) { c = c + 1; } else { c = 0; } if (c >= CPeriods) { if (Symbol.Ask > top) { type = "BB"; open(TradeType.Sell); c = 0; } else if (Symbol.Bid < bottom) { type = "BB"; open(TradeType.Buy); c = 0; } }*/ //-------------------------------------------------------------------------------------------------------- protected override void OnTick() { tradeSafe = true; buySafe = true; sellSafe = true; if (Account.Balance / Account.Equity < EquityStop) { //Print("Equity protection stop triggered. All positions closed."); //closeAll(); //Stop(); } if (Account.Equity < Account.Balance * BalanceStop) { //Print("Account balance protection triggered. All positions closed."); //closeAll(); //Stop(); } //Nearshift foreach (var pos in Positions.FindAll(botName, Symbol)) { sym = MarketData.GetSymbol(pos.SymbolCode); if (isNearTargetSignal()) { //CalcNewValues(); //AdjustPosition(); } } foreach (var pos in Positions.FindAll(botName, Symbol)) { } /*if (pos.Pips > Trailstart) { Print("Trailstart"); // true:false double actualPrice = isBuy(pos) ? Symbol.Bid : Symbol.Ask; int factor = isBuy(pos) ? 1 : -1; double? newStopLossPR = pos.StopLoss; // Stop a ZERO if ((pos.EntryPrice - newStopLossPR) * factor > 0) newStopLossPR = pos.EntryPrice; //Trail if ((actualPrice - newStopLossPR) * factor > Trail * Symbol.PipSize) { newStopLossPR += factor * Trail * Symbol.PipSize; if (newStopLossPR != pos.StopLoss) ModifyPosition(pos, newStopLossPR, pos.TakeProfit.Value); } }*/ //Filter if (TimeFilter) { if (!isTradingTime) tradeSafe = false; } if (ChaosFilter) { //if (isChaosSignal) //{ //BarCount = 0; //if (BarCount <= TradeDelayB) //tradeSafe = false; //} } if (TradeDelayTFilter) { if (TradeCount < TradeDelayTC) { tradeSafe = false; } } if (PibotFilter) { if (isPibotLiskSignal) { tradeSafe = false; if (FsB > Symbol.Bid) { close(TradeType.Buy); } else if (FrB < Symbol.Ask) { close(TradeType.Sell); } } //if (isPibotSignal) //{ //} } //OpenPositions action if (buySafe == true) { //Range if (isSTOBuySignal() || isRSIBuySignal) { Print("isRangeBuySignal"); close(TradeType.Sell); open(TradeType.Buy); } //Trend if (isSMABuySignal() || isMACDBuySignal()) { Print("isTrendBuySignal"); close(TradeType.Sell); open(TradeType.Buy); } } if (sellSafe == true) { //Range if (isSTOSellSignal() || isRSISellSignal) { Print("isRangeSellSignal"); close(TradeType.Buy); open(TradeType.Sell); } //Trend if (isSMASellSignal() || isMACDSellSignal()) { Print("isTrendSellSignal"); close(TradeType.Buy); open(TradeType.Sell); } } } //--------------------------------------------------------------------------------------- private void onPositionsOpened(PositionOpenedEventArgs args) { var pos = args.Position; if (pos.Label != botName) return; else { switch (pos.TradeType) { case TradeType.Buy: LongPositions++; break; case TradeType.Sell: ShortPositions++; break; } } } private void onPositionsClosed(PositionClosedEventArgs args) { var pos = args.Position; switch (pos.TradeType) { case TradeType.Buy: LongPositions--; break; case TradeType.Sell: ShortPositions--; break; } if (Martingale) { } /*if (pos.GrossProfit < 0) { MartingaleActive++; Volume = Volume * 2; } else if (MartingaleActive > 0) { MartingaleActive--; Volume = (int)(Volume / 2); //update }*/ Print("Current Balance is {0}, Equity is {1}.", Account.Balance, Account.Equity); } //---------------------------------------------------------------------------------------------------------------------------- //cBot Action private void open(TradeType tradeType) { if (!ProbabilityMode) { TradeCount++; if (tradeSafe == true) { switch (tradeType) { case TradeType.Buy: LongPositions++; break; case TradeType.Sell: ShortPositions++; break; } Print("Execute"); ExecuteMarketOrder(tradeType, Symbol, Volume, botName, StopLossPI, TakeProfitPI, SlippagePI); } } else if (ProbabilityMode) { randomNumber = rand.Next(1, 100); if (randomNumber <= P) { TradeCount++; if (tradeSafe) { switch (tradeType) { case TradeType.Buy: LongPositions++; Print("Opened Long position {0} of {1}", LongPositions, MaxLongP); break; case TradeType.Sell: ShortPositions++; Print("Opened Short position {0} of {1}", ShortPositions, MaxShortP); break; } Print("Execute"); ExecuteMarketOrder(tradeType, Symbol, Volume, botName, StopLossPI, TakeProfitPI, SlippagePI); } } else if (randomNumber > P) { return; } } } private void close(TradeType tradeType) { foreach (var position in Positions.FindAll(botName, Symbol, tradeType)) { ClosePosition(position); if (position.NetProfit < 0) { TradeCount = 0; Print("TradeCount=0"); } else { return; } } } private void closeAll() { close(TradeType.Buy); close(TradeType.Sell); } //------------------------------------------------------------------------------------- private void CalcNewValues() { if (pos.TradeType == TradeType.Buy) { newStopLossPR = Symbol.Bid - (Symbol.PipSize * TrailSLPips); newTakeProfitPR = Symbol.Bid + (Symbol.PipSize * TrailSLPips); } else { newStopLossPR = Symbol.Ask + (Symbol.PipSize * TrailSLPips); newTakeProfitPR = Symbol.Ask - (Symbol.PipSize * TrailSLPips); } } private void AdjustPosition() { if (newStopLossPR == 0 || newTakeProfitPR == 0) return; ModifyPosition(pos, newStopLossPR, newTakeProfitPR); } private TradeType GetRandomTradeType() { return rand.Next(2) == 0 ? TradeType.Buy : TradeType.Sell; } //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ //cBot Signal private bool isRSIBuySignal { get { return ((RSI.Result.Last(1) < RSI.Result.Last(0)) && (RSI.Result.Last(1) == RSIlow)); } } private bool isRSISellSignal { get { return ((RSI.Result.Last(1) < RSI.Result.Last(0)) && (RSI.Result.Last(1) == RSIhigh)); } } private bool isSTOBuySignal() { if ((STO.PercentD.LastValue < 50) && (Functions.IsRising(STO4.PercentD)) && (Functions.IsRising(STO.PercentD))) { if ((Functions.Minimum(STO.PercentD, SC * 2) < STOlow) && (Functions.Minimum(STO.PercentD, SC * 2)) < (Functions.Minimum(STO.PercentD, SC))) { if (Functions.IsFalling(SMAH48.Result)) { type = "STOBuy Divergence(SMA-STO)"; return true; } type = "STOBuy Divergence(STO)"; return true; } type = "STOBuy"; return true; } return false; } private bool isSTOSellSignal() { if ((STO.PercentD.LastValue > 50) && (Functions.IsFalling(STO4.PercentD)) && (Functions.IsFalling(STO.PercentD))) { if ((Functions.Maximum(STO.PercentD, SC * 2) > STOhigh) && (Functions.Maximum(STO.PercentD, SC * 2)) > (Functions.Maximum(STO.PercentD, SC))) { if (Functions.IsFalling(SMAH48.Result)) { type = "STOSell Divergence(SMA-STO)"; return true; } type = "STOSell Divergence(STO)"; return true; } type = "STOSell"; return true; } return false; } private bool isSMABuySignal() { if ((SMAH48.Result.Last(1) < SMAH48.Result.Last(0)) && (SMAH48.Result.Last(1) == Symbol.Ask)) { if (SMAH48.Result.Last(2) < Symbol.Ask && SMAH48.Result.Last(0) < Symbol.Ask && Time.Hour > 14 && Time.Hour < 18) { type = "SMABuy Touch"; return true; } type = "SMABuy CrossUp"; return true; } type = "SMABuy"; return false; } private bool isSMASellSignal() { if ((SMAH48.Result.Last(1) > SMAH48.Result.Last(0)) && (SMAH48.Result.Last(1) == Symbol.Bid)) { if (SMAH48.Result.Last(2) > Symbol.Ask && SMAH48.Result.Last(0) > Symbol.Bid && Time.Hour > 14 && Time.Hour < 18) { type = "SMASell Touch"; return true; } type = "SMABuySell CrossDown"; return true; } type = "SMASellBuy"; return false; } private bool isMACDBuySignal() { if (Functions.IsRising(MACD4.Histogram) && MACD4.Histogram.LastValue < MACDlow) { if (Functions.Minimum(MACD4.Histogram, MC * 4) < Functions.Minimum(MACD4.Histogram, MC)) { if (Functions.IsFalling(SMAH48.Result)) { type = "MACD Divergence(SMA-MACD)"; return true; } type = "MACD Divergence(MACD)"; return true; } type = " MACD"; return true; } return false; } private bool isMACDSellSignal() { if (Functions.IsFalling(MACD4.Histogram) && MACD4.Histogram.LastValue > MACDhigh) { if (Functions.Maximum(MACD4.Histogram, MC * 4) < Functions.Maximum(MACD4.Histogram, MC)) { if (Functions.IsRising(SMAH48.Result)) { type = "MACD Divergence(SMA-MACD)"; return true; } type = "MACD Divergence(MACD)"; return true; } type = " MACD"; return true; } return false; } private bool isPibotLiskSignal { get { return (FsB > Symbol.Bid) || (FrB < Symbol.Ask); } } private bool isPibotSignal { get { return (pivot == Symbol.Bid) || (Wpivot == Symbol.Bid) || (pivot == Symbol.Ask) || (Wpivot == Symbol.Ask); } } private bool isTradingTime { get { return (Time.Hour < 4 || Time.Hour > 8); } } private bool isNearTargetSignal() { if (pos.TradeType == TradeType.Buy) { if (sym.Bid > pos.TakeProfit - (sym.PipSize * TriggerPips)) return true; } else if (pos.TradeType == TradeType.Sell) { if (sym.Ask < pos.TakeProfit + (sym.PipSize * TriggerPips)) return true; } return false; } //-------------------------------------------------------------------------------------------------------------------------------- //cBot Positions private bool isBuy(Position position) { return TradeType.Buy == position.TradeType; } private bool isSell(Position position) { return TradeType.Sell == position.TradeType; } private bool isBuyPositions { get { return Positions.Find(botName, Symbol, TradeType.Buy) != null; } } private bool isSellPositions { get { return Positions.Find(botName, Symbol, TradeType.Sell) != null; } } private bool isAnyPosition { get { return isBuyPositions || isSellPositions; } } private bool isNoPosition { get { return !isAnyPosition; } } } }
Replies
Waxy
26 Mar 2019, 19:45
private bool isNearTargetSignal() { if (pos == null) if (pos.TradeType == TradeType.Buy) { if (sym.Bid > pos.TakeProfit - (sym.PipSize * TriggerPips)) return true; } else if (pos.TradeType == TradeType.Sell) { if (sym.Ask < pos.TakeProfit + (sym.PipSize * TriggerPips)) return true; } return false; }
@Waxy
Waxy
26 Mar 2019, 19:45
private bool isNearTargetSignal()
{
if (pos == null) return false;
if (pos.TradeType == TradeType.Buy)
{
if (sym.Bid > pos.TakeProfit - (sym.PipSize * TriggerPips))
return true;
}
else if (pos.TradeType == TradeType.Sell)
{
if (sym.Ask < pos.TakeProfit + (sym.PipSize * TriggerPips))
return true;
}
return false;
}
@Waxy
solark
03 Jul 2018, 21:01
Seems to me you have
Which gets used unchecked in
@solark