Null Exeception OnBar()
Null Exeception OnBar()
18 Aug 2016, 20:54
Hi,
I am getting a nullexception error in the first line of the code. Positions.Count !=0. How do I avoid this?
Thanks
///Exit on Close
if (Positions.Count != 0)
{
try
{
ClosePosition(Positions.Find("WRB"));
Print("Position Closed EOD");
} catch (Exception e)
{
Print(e.StackTrace);
}
}
else
{
Print("No open positions found");
}
Replies
DELETED_USER
18 Aug 2016, 21:51
I am getting a NullExceptionError at this line, do you get the same?
ClosePosition(Positions.Find("WRB"));
... Deleted by UFO ...
DELETED_USER
18 Aug 2016, 22:31
I am using this code with actual order execution. this line of code always gives null!
var posnumb = Positions.Find("Test");
thats why closed positions throws an error null reference exception object not set to an instance of an object
It never recognises when a new position is opened.
using System;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;
namespace cAlgo
{
[Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class Test : Robot
{
[Parameter(DefaultValue = 0.0)]
public double Parameter { get; set; }
public int count = 0;
protected override void OnStart()
{
count = 1;
Print(count = 1);
Print(Positions.Count);
}
protected override void OnBar()
{
// Put your core logic here
ExecuteMarketOrder(TradeType.Buy, Symbol, 100000);
var posnumb = Positions.Find("Test");
Print(posnumb);
if (posnumb != null)
{
Print("Close");
Print(posnumb);
ClosePosition(posnumb);
Print("Close Positions");
count = 0;
Print("Position Closed EOD");
Print(Positions.Count);
}
}
/*
if (Positions.Count < 2)
{
ExecuteMarketOrder(TradeType.Buy, Symbol, 100000);
count++;
Print(Positions.Count, count);
}
*/
protected override void OnStop()
{
// Put your deinitialization logic here
}
}
}
... Deleted by UFO ...
... Deleted by UFO ...
DELETED_USER
19 Aug 2016, 00:28
RE:
Thanks so much for your reply and suggestions. I will try tomorrow and let you know.
lucian said:
Try to replace:
var posnumb = Positions.Find("Test"); Print(posnumb); if (posnumb != null) { Print("Close"); Print(posnumb); ClosePosition(posnumb); Print("Close Positions"); count = 0; Print("Position Closed EOD"); Print(Positions.Count); }to:
using System; using System.Linq; using cAlgo.API; using cAlgo.API.Indicators; using cAlgo.API.Internals; using cAlgo.Indicators; namespace cAlgo { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)] public class NewcBot : Robot { public int count; protected override void OnBar() { foreach (var posnumb in Positions.FindAll("Test")) { Print(posnumb); { Print("Close"); Print(posnumb); ClosePosition(posnumb); Print("Close Positions"); count = 0; Print("Position Closed EOD"); Print(Positions.Count); } } } } }
... Deleted by UFO ...