Use this strategy to auto draw the last trend lines and trade according to the trendlines. When touch the up trend line, buy; when touch the down line, sell. When break out the up line, sell, when break out the down line, buy.
Code:
using System;
using System.Drawing;
using Broker.StrategyLanguage.Function.BuiltIn;
using Fx2GoCommon;
using System.Collections.Generic;
namespace Broker.StrategyLanguage.Strategy {
public class AutoTrendLine : BaseStrategyAdvisor {
private int m_swhistrength = 10;
private int m_swlostrength = 10;
private int m_barspast = 30;
private string m_history = "No";
private Color m_dntlcolor = Color.FromKnownColor(KnownColor.Red);
private Color m_uptlcolor = Color.FromKnownColor(KnownColor.Cyan);
private string m_alerttype = "IntraBar";
private BarNumber m_barnumber1;
private SwingHighBar m_swinghighbar1;
private SwingLowBar m_swinglowbar1;
private int m_value1;
private int m_value2;
private SeriesVar<ITrendLineDrw> m_dntlref;
private SimpleVar<Int32> m_dntlendbar;
private SimpleVar<Boolean> m_dntlbreak;
private Color m_dntlcolornum;
private SeriesVar<ITrendLineDrw> m_uptlref;
private SimpleVar<Int32> m_uptlendbar;
private SimpleVar<Boolean> m_uptlbreak;
private Color m_uptlcolornum;
private SimpleVar<Int32> m_index;
private int m_barnum;
private SimpleVar<Boolean> m_historytf;
private string m_alerttypecaps;
private SimpleArray1D<DateTime> m_swhitime;
private SimpleArray1D<Double> m_swhival;
private SimpleArray1D<DateTime> m_swlotime;
private SimpleArray1D<Double> m_swloval;
public AutoTrendLine(object _ctx):base(_ctx){}
[Input]
public int swhistrength{
get { return m_swhistrength; }
set { m_swhistrength = value; }
}
[Input]
public int swlostrength{
get { return m_swlostrength; }
set { m_swlostrength = value; }
}
[Input]
public int barspast{
get { return m_barspast; }
set { m_barspast = value; }
}
public string history{
get { return m_history; }
set { m_history = value; }
}
[Input]
public KnownColor dntlcolor{
get { return m_dntlcolor.ToKnownColor(); }
set { m_dntlcolor = Color.FromKnownColor(value); }
}
[Input]
public KnownColor uptlcolor{
get { return m_uptlcolor.ToKnownColor(); }
set { m_uptlcolor = Color.FromKnownColor(value); }
}
[Input]
public string alerttype{
get { return m_alerttype; }
set { m_alerttype = value; }
}
private int m_LotSize = 1;
[Input]
public int LotSize
{
get{return m_LotSize;}
set{m_LotSize=value;}
}
private int m_Limit = 20;
[Input]
public int Limit
{
get{return m_Limit;}
set{m_Limit=value;}
}
private int m_Stop = 20;
[Input]
public int Stop
{
get{return m_Stop;}
set{m_Stop=value;}
}
private int m_PipsToBreakOut = 0;
[Input]
public int PipsToBreakOut
{
get{return m_PipsToBreakOut;}
set{m_PipsToBreakOut=value;}
}
private IMarketOrder buy_order;
private IPriceOrder buy_orderTP;
private IPriceOrder buy_orderSL;
private IMarketOrder sellshort_order;
private IPriceOrder sellshort_orderTP;
private IPriceOrder sellshort_orderSL;
private ITrendLineDrw m_BlueLine;
private ITrendLineDrw m_RedLine;
private double m_TP, m_SL;
private bool m_TouchedBuy, m_TouchedSell;
protected override void Construct() {
m_barnumber1 = new BarNumber(this);
m_swinghighbar1 = new SwingHighBar(this);
m_swinglowbar1 = new SwingLowBar(this);
m_dntlref = new SeriesVar<ITrendLineDrw>(this);
m_dntlendbar = new SimpleVar<Int32>(this);
m_dntlbreak = new SimpleVar<Boolean>(this);
m_uptlref = new SeriesVar<ITrendLineDrw>(this);
m_uptlendbar = new SimpleVar<Int32>(this);
m_uptlbreak = new SimpleVar<Boolean>(this);
m_index = new SimpleVar<Int32>(this);
m_historytf = new SimpleVar<Boolean>(this);
m_swhitime = new SimpleArray1D<DateTime>(this, 11);
m_swhival = new SimpleArray1D<Double>(this, 11);
m_swlotime = new SimpleArray1D<DateTime>(this, 11);
m_swloval = new SimpleArray1D<Double>(this, 11);
buy_order = OrdersFactory.CreateMarketNextBar(new OrdersCreateParams(Lots.Variable, "Buy", OrderAction.Buy));
buy_orderTP = OrdersFactory.CreateLimit(new OrdersCreateParams(Lots.Variable, "BuyTP", OrderAction.Sell));
buy_orderSL = OrdersFactory.CreateStop(new OrdersCreateParams(Lots.Variable, "BuySL", OrderAction.Sell));
sellshort_order = OrdersFactory.CreateMarketNextBar(new OrdersCreateParams(Lots.Variable, "SellShort", OrderAction.SellShort));
sellshort_orderTP = OrdersFactory.CreateLimit(new OrdersCreateParams(Lots.Variable, "SellShortTP", OrderAction.BuyToCover));
sellshort_orderSL = OrdersFactory.CreateStop(new OrdersCreateParams(Lots.Variable, "SellShortSL", OrderAction.BuyToCover));
}
protected override void Initialize() {
m_swinghighbar1.instance = new ConstantExpression<int>(1);
m_swinghighbar1.price = Bars.High;
m_swinghighbar1.strength = new Serie---pression<Int32>(delegate { return swhistrength; });
m_swinghighbar1.length = new Serie---pression<Int32>(delegate { return (swhistrength + 1); });
m_swinglowbar1.instance = new ConstantExpression<int>(1);
m_swinglowbar1.price = Bars.Low;
m_swinglowbar1.strength = new Serie---pression<Int32>(delegate { return swlostrength; });
m_swinglowbar1.length = new Serie---pression<Int32>(delegate { return (swlostrength + 1); });
m_value1 = default(int);
m_value2 = default(int);
m_dntlendbar.DefaultValue = 0;
m_dntlbreak.DefaultValue = false;
m_dntlcolornum = m_dntlcolor;
m_uptlendbar.DefaultValue = 0;
m_uptlbreak.DefaultValue = false;
m_uptlcolornum = m_uptlcolor;
m_index.DefaultValue = 0;
m_barnum = 0;
m_historytf.DefaultValue = false;
m_alerttypecaps = default(string);
m_swhival.DefaultValue = (-1*1000000);
m_swloval.DefaultValue = 1000000;
m_TP = 0;
m_SL = 0;
m_TouchedBuy = false;
m_TouchedSell = false;
}
protected override void Execute(){
DrawTrendLines();
if(Environment.StrategyAuto && !Environment.RealTime) //Bypass backtest data when in auto is on.
return;
InitializeLines();
CheckExitLogic();
CheckTradingLogic();
}
private void InitializeLines()
{
List<ITrendLineDrw> trendLines = new List<ITrendLineDrw>(DrwTrendLine.TrendLineDrws(EOrigin.AnyTechOrManual));
foreach (ITrendLineDrw drw in trendLines)
{
if(drw.Color.ToArgb() == m_uptlcolor.ToArgb())
m_BlueLine = drw;
if(drw.Color.ToArgb() == m_dntlcolor.ToArgb())
m_RedLine = drw;
}
}
private void CheckTradingLogic()
{
double bluePrice;
if(m_BlueLine != null)
bluePrice = GetLineValueByTime(m_BlueLine, Bars.Time[1]);
else
bluePrice = 0;
double redPrice;
if(m_RedLine != null)
redPrice = GetLineValueByTime(m_RedLine, Bars.Time[1]);
else
redPrice = 0;
if(bluePrice > 0 || redPrice > 0)
{
bool touchBlue = CheckForTouch(1, bluePrice);
bool touchRed = CheckForTouch(1, redPrice);
//If touches blue
if(touchBlue && !touchRed)
{
m_TouchedBuy = true;
m_TouchedSell = false;
MarketOrderBuy();
}
//If touches red
else if(touchRed && !touchBlue)
{
m_TouchedSell = true;
m_TouchedBuy = false;
MarketOrderSell();
}
else if(touchRed && touchBlue)
{
m_TouchedBuy = true;
m_TouchedSell = true;
}
//If breaks out of blue
if(m_TouchedBuy && Bars.High[1] < bluePrice - PipsToBreakOut*Point)
{
MarketOrderSell();
m_TouchedBuy = false;
m_TouchedSell = false;
}
else if(m_TouchedSell && Bars.Low[1] > redPrice + PipsToBreakOut*Point)
{
MarketOrderBuy();
m_TouchedBuy = false;
m_TouchedSell = false;
}
}
}
private bool CheckForTouch(int barsAgo, double price)
{
if(Bars.Low[barsAgo] <= price && Bars.High[barsAgo] >= price)
return true;
else
return false;
}
private double GetLineValueByTime(ITrendLineDrw drw, DateTime time)
{
DrwCoordinate startPoint;
DrwCoordinate endPoint;
if(drw.Begin.Time <= drw.End.Time)
{
startPoint = drw.Begin;
endPoint = drw.End;
}
else
{
startPoint = drw.End;
endPoint = drw.Begin;
}
if(time >= startPoint.Time) //Get the price at certain time for certain trend line
{
TimeSpan tsTotal = endPoint.Time - startPoint.Time;
TimeSpan ts = time - startPoint.Time;
double price = (endPoint.Price-startPoint.Price)/tsTotal.TotalMinutes*ts.TotalMinutes + startPoint.Price;
return price;
}
else
return 0;
}
private void MarketOrderBuy()
{
if(StrategyInfo.MarketPosition <= 0)
buy_order.Generate(LotSize);
}
private void MarketOrderSell()
{
if(StrategyInfo.MarketPosition >= 0)
sellshort_order.Generate(LotSize);
}
private void CheckExitLogic()
{
if(StrategyInfo.MarketPosition != 0)
{
if(StrategyInfo.MarketPosition > 0)
{
if(Limit > 0)
m_TP = StrategyInfo.AvgEntryPrice + Limit*Point; //Set TP
else
m_TP = 0;
if(Stop > 0)
m_SL = StrategyInfo.AvgEntryPrice - Stop*Point; //Set SL
else
m_SL = 0;
if(m_TP > 0)
buy_orderTP.Generate(m_TP, Math.Abs(StrategyInfo.MarketPosition)); //Check TP
if(m_SL > 0)
buy_orderSL.Generate(m_SL, Math.Abs(StrategyInfo.MarketPosition)); //Check SL
}
if(StrategyInfo.MarketPosition < 0)
{
if(Limit > 0)
m_TP = StrategyInfo.AvgEntryPrice - Limit*Point; //Same as above
else
m_TP = 0;
if(Stop > 0)
m_SL = StrategyInfo.AvgEntryPrice + Stop*Point;
else
m_SL = 0;
if(m_TP > 0)
sellshort_orderTP.Generate(m_TP, Math.Abs(StrategyInfo.MarketPosition));
if(m_SL > 0)
sellshort_orderSL.Generate(m_SL, Math.Abs(StrategyInfo.MarketPosition));
}
}
else
{
m_TP = 0;
m_SL = 0;
}
}
private double Point //Returns the point value
{
get{
if(Bars.Point < 0.01)
{
return(Bars.Point * 10);
}
else
{
return Bars.Point;
}
}
}
private void DrawTrendLines()
{
if ((Bars.CurrentBar == 1)){
m_historytf.Value = ((history.ToUpper() == "YES")
|| (history.ToUpper() == "Y"));
}
m_barnum = m_barnumber1[0];
if ((m_swinghighbar1[0] == swhistrength)){
for (m_value1 = 9; m_value1 >= 0; m_value1 = (m_value1 - 1)){
m_swhitime[0][(((m_value1 + 1)))] = m_swhitime[0][((m_value1))];
m_swhival[0][(((m_value1 + 1)))] = m_swhival[0][((m_value1))];
}
m_swhitime[0][((0))] = Bars.Time[swhistrength];
m_swhival[0][((0))] = Bars.High[swhistrength];
for (m_value2 = 1; m_value2 <= 10; m_value2 = (m_value2 + 1)){
if ((m_swhival[0][((m_value2))] > m_swhival[0][((0))])){
m_index.Value = m_value2;
m_value2 = 11;
}
}
if ((m_value2 == 12)){
if (m_dntlref[0] != null && m_dntlref[0].Exist){
if ((m_historytf.Value
&& (m_dntlbreak.Value == false))){
m_dntlref.Value.End = new DrwCoordinate(Bars.Time[0],
m_dntlref.Value.GetPriceByDateTime(Bars.Time[0]));
m_dntlref.Value.ExtRight = false;
}
else{
if ((m_historytf.Value == false)){
m_dntlref.Value.Delete();
}
}
}
m_dntlref.Value =
DrwTrendLine.Create(
new DrwCoordinate(m_swhitime[0][((m_index.Value))], m_swhival[0][((m_index.Value))]),
new DrwCoordinate(m_swhitime[0][((0))], m_swhival[0][((0))]));
if (m_dntlbreak.Value){
m_dntlbreak.Value = false;
}
m_dntlendbar.Value = (m_barnum - swhistrength);
m_dntlref.Value.ExtLeft = false;
m_dntlref.Value.ExtRight = true;
m_dntlref.Value.Color = m_dntlcolornum;
if ((m_alerttypecaps == "ONCLOSE")){
m_dntlref.Value.Alert = EAlertStatus.BreakoutOnClose;
}
else{
if ((m_alerttypecaps == "INTRABAR")){
m_dntlref.Value.Alert = EAlertStatus.BreakoutIntrabar;
}
else{
m_dntlref.Value.Alert = EAlertStatus.Disabled;
}
}
}
}
if ((m_swinglowbar1[0] == swlostrength)){
for (m_value1 = 9; m_value1 >= 0; m_value1 = (m_value1 - 1)){
m_swlotime[0][(((m_value1 + 1)))] = m_swlotime[0][((m_value1))];
m_swloval[0][(((m_value1 + 1)))] = m_swloval[0][((m_value1))];
}
m_swlotime[0][((0))] = Bars.Time[swlostrength];
m_swloval[0][((0))] = Bars.Low[swlostrength];
for (m_value2 = 1; m_value2 <= 10; m_value2 = (m_value2 + 1)){
if ((m_swloval[0][((m_value2))] < m_swloval[0][((0))])){
m_index.Value = m_value2;
m_value2 = 11;
}
}
if ((m_value2 == 12)){
if (m_uptlref.Value != null && m_uptlref.Value.Exist){
if ((m_historytf.Value
&& (m_uptlbreak.Value == false))){
m_uptlref.Value.End = new DrwCoordinate(Bars.Time[0],
m_uptlref.Value.GetPriceByDateTime(Bars.Time[0]));
m_uptlref.Value.ExtRight = false;
}
else{
if ((m_historytf.Value == false)){
m_uptlref.Value.Delete();
}
}
}
m_uptlref.Value =
DrwTrendLine.Create(
new DrwCoordinate(m_swlotime[0][((m_index.Value))], m_swloval[0][((m_index.Value))]),
new DrwCoordinate(m_swlotime[0][((0))], m_swloval[0][((0))]));
if (m_uptlbreak.Value){
m_uptlbreak.Value = false;
}
m_uptlendbar.Value = (m_barnum - swlostrength);
m_uptlref.Value.ExtLeft = false;
m_uptlref.Value.ExtRight = true;
m_uptlref.Value.Color = m_uptlcolornum;
if ((m_alerttypecaps == "ONCLOSE")){
m_uptlref.Value.Alert = EAlertStatus.BreakoutOnClose;
}
else{
if ((m_alerttypecaps == "INTRABAR")){
m_uptlref.Value.Alert = EAlertStatus.BreakoutIntrabar;
}
else{
m_uptlref.Value.Alert = EAlertStatus.Disabled;
}
}
}
}
if ((((m_dntlref.Value != null && m_dntlref.Value.Exist)
&& (m_dntlbreak.Value == false))
&& Functions.DoubleGreater(m_barnum, ((m_dntlendbar.Value + swhistrength)
+ barspast)))
&& Functions.DoubleGreater(Bars.Close[barspast], m_dntlref.Value.GetPriceByDateTime(Bars.Time[0]))){
m_dntlref.Value.End = new DrwCoordinate(Bars.Time[0], m_dntlref.Value.GetPriceByDateTime(Bars.Time[0]));
m_dntlref.Value.ExtRight = false;
m_dntlbreak.Value = true;
}
if ((((m_uptlref.Value != null && m_uptlref.Value.Exist
&& (m_uptlbreak.Value == false))
&& Functions.DoubleGreater(m_barnum, ((m_uptlendbar.Value + swlostrength)
+ barspast)))
&& Functions.DoubleLess(Bars.Close[barspast], m_uptlref.Value.GetPriceByDateTime(Bars.Time[0])))){
m_uptlref.Value.End = new DrwCoordinate(Bars.Time[0], m_uptlref.Value.GetPriceByDateTime(Bars.Time[0]));
m_uptlref.Value.ExtRight = false;
m_uptlbreak.Value = true;
}
}
}
}
Last edited by Lucas Izidoro; 12-08-2010 at 04:14 PM.
When I apply it to the chart, there are no trendline drawn and it doesn't seem to buy/sell.
I am interested in designing my own strategy using the AutoTrendLines function, And i am wondering if you would like to get in contact with me so we can analyze how exactly the trendlines get drawn.
I have made another post in this forum for someone to help comment the "AutoTrendLines" function.
Thanks for posting to the forum. The TrendLineAutomatic indicator is based off discovery of swing low/swing high pivots and then connecting these pivots as long as they fall within a specified time. Hope this has been helpful.
Disclaimer: Trading foreign exchange on margin carries a high level of risk, and may not be suitable for all investors. The high degree of leverage can work against you as well as for you. Before deciding to trade foreign exchange you should carefully consider your investment objectives, level of experience, and risk appetite. The possibility exists that you could sustain a loss of some or all of your initial investment and therefore you should not invest money that you cannot afford to lose. You should be aware of all the risks associated with foreign exchange trading, and seek advice from an independent financial advisor if you have any doubts. Any opinions, news, research, analyses, prices, or other information contained on this website is provided as general market commentary and does not constitute investment advice. Forex Capital Markets LLC. will not accept liability for any loss or damage, including without limitation to, any loss of profit, which may arise directly or indirectly from use of or reliance on such information.