i have a problem with my adaptive moving average trading system - c#

I created a trading system with an adaptive moving average on the average true range but the program reports this error to me
the modifier public is not valid for this item
at line 21 of the code
public int avgTrueRange.value1 { get; set; }
I tried to change public but it always reports this error.
this is the code :
public class MediaMobileAdattiva : SignalObject
{
public MediaMobileAdattiva(object _ctx): base(_ctx)
{
Range = 14;
FirstLength = 10;
AvgTrueRange.value1 = 1;
}
private IOrderMarket buy_order;
public int Range { get; set; }
public double FirstLength { get; set; }
public int AvgTrueRange.value1 { get; set; }
private double FirstAverage()
{
if (AverageTrueRange < AvgTrueRange.value1)
return FirstLength;
}
protected override void Create()
{
// create variable objects, function objects, order objects
buy_order = OrderCreator.MarketNextBar(new SOrderParameters(Contracts.Default, EOrderAction.Buy));
}
protected override void StartCalc()
{
// assign inputs
}
protected override void CalcBar()
{
// strategy logic
if (Bars.CurrentBar > 1)
{
switch (FirstAverage)
{
case FirstLength:
return 1;
}
}
if (Bars.CurrentBar > 1 && Bars.Close.CrossesOver(FirstAverage, ExecInfo.MaxBarsBack)
{
switch (FirstLength)
{
case 1:
buy_order.Send(Bars.Close[0]);
}
}
}
}

What you need is to make a struct for AvgTrueRange:
public struct Range
{
public int value1 {get; set;}
}
and change:
public int AvgTrueRange.value1 { get; set; }
to
public Range AvgTrueRange { get; set; }
Your code still won't compile btw but I don't really understand what you are trying to do in this line:
if (AverageTrueRange < AvgTrueRange.value1)
Also, change:
switch (FirstAverage)
{
case FirstLength:
return 1;
}
to
var avg = FirstAverage();
int? result = avg switch
{
var avg when avg == FirstLength => 1,
_ => null
};
if (result.HasValue) return result.Value;
as cases can only be constant values.

Related

Can property setter condition acitvate by constructor?

I was expected that constructor can go into the setter condition, I have done the following attempts.
static void Main(string[] args)
{
Iitem car = new Car(7000);
Console.WriteLine($"cost={car.cost}");//expect output "too expensive",but actually show 7000
car.cost = 7000;
Console.ReadLine();
}
public interface Iitem
{
int cost { get; set; }
string status {get;set; }
}
class Car:Iitem
{
private int mycost;
public int cost
{
get { return mycost; }
set
{
if (value > 5000)
{
mycost = 0;
Console.WriteLine("too expensive");
}
else
{
mycost = value;
}
}
}
public string status { get; set; }
public Car(int cost)
{
this.mycost = cost;
}
}
If I discard car.cost=7000 from Main() function, then I can't get the output of too expensive.
you are not getting the desired result because you are setting the value directly into the variable "mycost" in the constructor. Replace it with this.cost = cost;

C# Accessing a property within a property?

I'm trying to pass some tests in the Exercism C# exercise 'weighing machine' which uses properties. I have these properties:
using System;
enum Units
{
Pounds,
Kilograms
}
class WeighingMachine
{
private decimal inputWeight;
public decimal InputWeight
{
get { return inputWeight; }
set { if (value >= 0)
inputWeight = value;
else throw new ArgumentOutOfRangeException();
}
}
private decimal displayWeight;
public decimal DisplayWeight
{
get
{ return displayWeight; }
set
{
displayWeight = InputWeight - TareAdjustment;
if (displayWeight <= 0)
throw new ArgumentOutOfRangeException();
}
}
private decimal _pounds;
public USWeight USDisplayWeight
{
get { return _pounds; }
set { _pounds = new USWeight(InputWeight).Pounds; }
}
public decimal TareAdjustment { private get; set; }
public int Units
{ get; set; }
}
struct USWeight
{
public USWeight(decimal weightInPounds)
{
Pounds = (int)weightInPounds;
Ounces = (weightInPounds - Pounds)*16;
}
public int Pounds { get; set; }
public decimal Ounces { get; set; }
}
My stumbling block is the tests:
[Fact]
public void Get_us_display_weight_pounds()
{
var wm = new WeighingMachine();
wm.InputWeight = 60m;
Assert.Equal(132, wm.USDisplayWeight.Pounds);
}
I can't get my head around how the test is asking for wm.USDisplayWeight.Pounds - how is the .Pounds accessed on the end? it's like there is a property set within the USDisplayWeight property, but that's not possible is it? I can't make the compiler stop complaining about the .Pounds - I get ''decimal' does not contain a definition for 'Pounds' and no accessible extension method 'Pounds' accepting a first argument of type 'decimal' could be found.
I'm sure it's a simple thing that I'm overlooking here, but I would appreciate any help at all.

Auto calculate property within class

I have these two classes:
public class LeadPerformanceItem
{
public string name { get; set; }
public int visitors { get; set; }
public decimal visitorspercentoftotal
{
get
{
// ?
}
}
}
public class LeadPerformanceItemCollection
{
public List<LeadPerformanceItem> items {get;set;}
public int totalvisitors
{
get
{
return items.Sum(x => x.visitors);
}
}
}
Is there anyway my visitorspercentoftotal property could be automatically calculated as items are added and removed from the collection?
public class LeadPerformanceItem
{
public string name { get; set; }
public int Visitors { get; set; }
private int _totalVisitors = 0;
public void UpdateTotalVisitors(int total)
{
this._totalVisitors = total;
}
public decimal Visitorspercentoftotal => _totalVisitors != 0
? Convert.ToDecimal(Math.Round(((double) (Visitors * 100)) / _totalVisitors))
: 0;
}
public class LeadPerformanceItemCollection
{
public List<LeadPerformanceItem> Items { get; set; }
public void AddToItems(LeadPerformanceItem item)
{
Items.Add(item);
var total = Items.Sum(x => x.Visitors);
Items.AsParallel().ForAll(i => i.UpdateTotalVisitors(total));
}
public int totalvisitors
{
get { return Items.Sum(x => x.Visitors); }
}
}
[TestFixture]
public class Class1
{
[Test]
public void Test()
{
var leadPerformanceItemCollection = new LeadPerformanceItemCollection();
leadPerformanceItemCollection.Items=new List<LeadPerformanceItem>();
leadPerformanceItemCollection.AddToItems(new LeadPerformanceItem()
{
name = "test",
Visitors = 10
});
leadPerformanceItemCollection.AddToItems(new LeadPerformanceItem()
{
name = "test2",
Visitors = 25
});
Console.WriteLine(leadPerformanceItemCollection.Items[0].Visitorspercentoftotal);
Console.WriteLine(leadPerformanceItemCollection.Items[1].Visitorspercentoftotal);
}
}
result:
29%
71%
One way would be to inherit from List and hide the Add method and create your own and do the calculation there.
public class LeadPerformanceItemCollection : List<LeadPerformanceItem>
{
public new void Add(LeadPerformanceItem item)
{
//calculate percent of total here
base.Add(item);
}
}

How to generalize a property pattern

I have classes that has multiple properties which have well-defined name and function but have the same implementation. For example:
class Stats
{
private int attack;
public int Attack
{
get =>
HasBuff ? attack + 1 : attack;
set
{
if (value < 1 || value > 10)
throw new ArgumentOutOfRangeException("Invalid value");
attack = value;
}
}
public int Defense {...}
public int Speed {...}
}
Where Defense and Speed are to be implemented just like Attack . How can I generalize this structure to avoid redundancy and make changes easier?
Make another class to generalize stats:
public class Stat
{
public bool HasBuff { get; set; }
private int _stat;
public int Score
{
get => HasBuff ? _stat + 1 : _stat;
set => _stat = value;
}
}
Then just use that for each of your skills:
public class CombatStats
{
public Stat Attack { get; } = new Stat();
public Stat Defense { get; } = new Stat();
public Stat Speed { get; } = new Stat();
}
Calling code would look like this:
var ninja = new Ninja();
ninja.skills = new CombatStats();
var attackStrength = ninja.skills.Attack.Score;
As further improvement, implicit operators can be used to avoid object creation and call to Score:
public class Stat
{
...
public static implicit operator int(Stat stat)
{
return stat.Score;
}
public static implicit operator Stat(int value)
{
return new Stat()
{
Score = value
};
}
}
This makes the change transparent to client code written w.r.t. to the example in the question:
ninja.skills = new CombatStats(){
Attack = 5,
Defense = 2
}
int attack = ninja.skills.Attack;
One approach to consider:
class Stats
{
// other existing code here
private int defense;
public int Defense
{
get
{
return GetValue(defense);
}
set
{
SetValue(value, ref defense);
}
}
private int GetValue(int value)
{
return HasBuff ? value + 1 : value;
}
private void SetValue(int value, ref int target)
{
if (value < 1 || value > 10)
throw new ArgumentOutOfRangeException("Invalid value");
target = value;
}
}
Attack etc will now be basically the same as Defence but passing in attack rather than defense to GetValue and SetValue.
I would go with composition
Stat:
public class Stats
{
private readonly StatProperty _defense;
private readonly StatProperty _attack;
private readonly StatProperty _speed;
public Stats()
{
_defense = new StatProperty(this);
_attack = new StatProperty(this);
_speed = new StatProperty(this);
}
public int Defense
{
get => _defense.Value;
set => _defense.Value = value;
}
public int Attack
{
get => _attack.Value;
set => _attack.Value = value;
}
public int Speed
{
get => _speed.Value;
set => _speed.Value = value;
}
public bool HasBuff { get; set; }
}
StatProperty:
public class StatProperty
{
public Stats Stats { get; }
public StatProperty(Stats stats)
{
Stats = stats;
}
private int _value = 1;
public int Value
{
get => Stats.HasBuff ? _value + 1 : _value;
set
{
if (value < 1 || value > 10)
throw new ArgumentOutOfRangeException("Invalid value");
_value = value;
}
}
}
I would need more details to know if it is the best option.
you also could make StatProperty as internal if don't want to show it outside of your library or nested private class if you want to use this just on the class Stats

Is there any way to do a mathematical addition between methods?

I want to know if there is any way to do a mathematical addition between methods? The code is as below.
From Main: (I need to the calculation but I can not do calculation between methods)
Ball.setPositionY = Ball.setPositionY + Ball.setSpeedY;
From a Class:
public class Ball
{
public int speedX { get; set; }
public int speedY { get; set; }
public int positionX { get; set; }
public int positionY { get; set; }
public Ball(int speedX, int speedY, int positionX, int positionY)
{
this.speedX = speedX;
this.speedY = speedY;
this.positionX = positionX;
this.positionY = positionY;
}
public void setSpeedX(int newSpeedX)
{
speedX = newSpeedX;
}
public void setSpeedY(int newSpeedY)
{
speedY = newSpeedY;
}
public void setPositionX(int newPositionX)
{
positionX = newPositionX;
}
public void setPositionY(int newPositionY)
{
positionY = newPositionY;
}
}
This is how you should do it:
public class Ball
{
public int SpeedX { get; set; }
public int SpeedY { get; set; }
public int PositionX { get; set; }
public int PositionY { get; set; }
public Ball(int speedX, int speedY, int positionX, int positionY)
{
this.SpeedX = speedX;
this.SpeedY = speedY;
this.PositionX = positionX;
this.PositionY = positionY;
}
}
public class Program
{
public static void Main(string[] args)
{
Ball ball1 = new Ball(1,1,1,1);
Ball ball2 = new Ball(2,2,2,2);
Ball ball3 = new Ball(3,3,3,3);
ball3.SpeedX = ball1.SpeedX + ball2.SpeedX;
}
}
How about letting the set method also return the value that was set or add a get method that gives you that same value. But...since you want that, why don't you just use the public properties on the object?
So, your method(s) can look like
public int setPositionX(int newPositionX)
{
positionX = newPositionX;
return newPositionX;
}
But, since you are creating your own getters and setters now and you already have them. Use the public properties and all should be fine.
After assigning the value, you just return the value. It will solve your problem. If you want to use methods.
For eg.
public int setSpeedX(int newSpeedX)
{
speedX = newSpeedX;
return speedX;
}
That's what properties are for; you should use the properties for that.
If you mean an addition in the functional programming sense, I can make no sense of your example.
Your methods must return value in order to add them,but public properties do what you want.
Ball.positionY =Ball.positionY + Ball.SpeedY;
Since all your methods have void return type there's no way to "add" them.
If you want to do that, change return type of your methods to int.
Edit
You can "add" methods that have int return type, but the result can't be a method.
Sample:
public int setPositionY(int newPositionY)
{
positionY = newPositionY;
return positionY;
}
public int setSpeedY(int newSpeedY)
{
speedY = newSpeedY;
return speedY;
}
positionY = setPositionY(/*new position*/) + setSpeedY(/*new speed*/);
try the below code...
namespace Foo
{
class Program
{
static void Main(string[] args)
{
Ball b = new Ball(1,2,3,4);
//b.setPositionY() = b.setSpeedY() + b.setSpeedY();
b.setPositionY(b.setSpeedX() + b.setSpeedY());
}
}
public class Ball
{
public int speedX { get; set; }
public int speedY { get; set; }
public int positionX { get; set; }
public int positionY { get; set; }
public Ball(int speedX, int speedY, int positionX, int positionY)
{
this.speedX = speedX;
this.speedY = speedY;
this.positionX = positionX;
this.positionY = positionY;
}
public int setSpeedX()
{
//speedX = newSpeedX;
return 10;
}
public int setSpeedY()
{
//speedY = newSpeedY;
return 20;
}
public int setPositionX()
{
//positionX = newPositionX;
return 1;
}
public void setPositionY(int newPositionY)
{
positionY = newPositionY;
}
}

Categories

Resources