I have updated the code of a long only strategy to trade short only. When applied on the chart is working correctly, but not able to adjust the backtest code to replicate the trades.
Below the code I need to covert from long to short. Anyone can assist on the changes needed since nowadays it is creating lot of trades without following the strategy?
DailyEntryOrderLimit = MaxPos;
Ticker = Name();
StaticVarSet(Ticker + "LimitEntryPrice", Ref(ShortLimit,-1));
SetCustomBacktestProc("");
if (Status("action") == actionPortfolio)
{
bo = GetBacktesterObject();
bo.PreProcess();
MaxOrdersToPlace = 0;
TotalOrdersPlaced = 0;
for (i = 0; i < BarCount; i++)
{
for (sig = bo.GetFirstSignal(i); sig; sig = bo.GetNextSignal(i))
{
if (sig.IsExit() && sig.IsLong())
bo.ExitTrade(i, sig.Symbol, sig.Price, 1);
}
MaxOrdersToPlace = MaxPos - bo.GetOpenPosQty();
TotalSignalCount = 0;
SigCount = 0;
for (sig = bo.GetFirstSignal(i); sig; sig = bo.GetNextSignal(i))
{
if (sig.IsEntry() && sig.IsLong())
TotalSignalCount++;
}
for (sig = bo.GetFirstSignal(i); sig; sig = bo.GetNextSignal(i))
{
if (sig.IsEntry() && sig.IsLong())
{
SigCount++;
LimitPrice = StaticVarGet(sig.Symbol + "LimitEntryPrice");
LowPrice = Foreign(sig.Symbol, "Low");
if (SigCount > MaxOrdersToPlace OR
SigCount > DailyEntryOrderLimit)
sig.Price = -1;
else
TotalOrdersPlaced++;
if (LimitPrice[i] < LowPrice[i])
sig.Price = -1;
}
}
bo.ProcessTradeSignals(i);
First the code is incomplete. If you want help, send complete code. Second thing, in the part given, do a text replace "Long" with "Short" and . Obviously it will replace IsLong with IsShort.
Using text replace was one of my first tentatives in order to replace all Buy/Sell to Short and Cover. It worked fine all the adjustments when applied to chart, but when backtest the trades are in a kind of loop losing all the equity and with no logic compared with the chart signals.
On the BackTest code I shared here at the beginning when I replace IsLong for IsShort I receive the following error:
Error 20.
COM method/function IsShort does not exist
@Tomasz did not meant that you would be finished then. If you read documentation here then you would see there isn't IsShort method. So to get opposite of IsLong you have to do some extra work e.g. by creating line with variable and adding NOT operator in front.
IsShort = NOT sig.IsLong();
FYI,
IsShort = ! sig.IsLong();// ! is equivalent to NOT
In addition remove sig. before and () after IsShort.