In the following code the trailing will happen, but once the profit is 500 and the stoploss is 250 and the profit is falling to 400, the stoploss will be 150 and not maintain the 250. I am not using the setstoploss or setdollartrailing. I coded the amounts per contract.
Code: Select all
[IntrabarOrderGeneration = True]
inputs: StockAmt (5000),
ProfittargetAmt (500),
StoplossAmt (500),
TrailingTrigger (100),
TrailingAmt (250),
variables: Stoploss_Fixed (0),
Profit_Fixed (0),
Trailing_Value(0),
TrailingStop_Trigger (False),
Brokerposition(0),
Profit_Fixed = ProfittargetAmt/StockAmt;
Stoploss_Fixed = StoplossAmt/StockAmt;
Trailing_value = ((openpositionprofit/stockamt)-(TrailingAmt/Stockamt));
//TEST conditions
Condition1 = price > price[1];
//Entry Conditions
If (barstatus(1) = 2)then begin;
if Condition1 and marketposition = 0 then begin;
Buy ("Long") next bar at market;
end;
End;
//Exit Conditions ---------------------------------------------------------------------------------------
//Stoploss and profit target
If marketposition = 0 then TrailingStop_Trigger = false;
If openpositionprofit >= Trailingtrigger and (trailingtrigger <>0) then trailingstop_trigger = true;
//Profit target fixed
//Long exit:
If marketposition = 1 then
Sell ("CloseProfitLong") next bar Round((avgEntryPrice + Profit_Fixed),2) limit;
end;
//Short exit
If marketposition = -1 then
BuytoCover ("CloseProfitShort") next bar Round((avgEntryPrice - Profit_Fixed),2) limit;
end;
//Stoploss fixed --------------------------------------------------------------------------------------------
//Long exit:
if marketposition = 1 then
Sell ("StopLossLong") next bar Round((avgEntryPrice - Stoploss_Fixed),2) stop;
end;
//Short exit:
if marketposition = -1 then
Buytocover ("StopLossshort") next bar Round((avgEntryPrice + Stoploss_Fixed),2) stop;
end;
//Trailingstoploss -----------------------------------------------------
//Long exit:
if (Trailingstop_Trigger=true) and (StoplossAmt > 0) and TrailingAmt > 0 then begin;
if marketposition = 1 then
Sell ("TrailingStopLong") next bar Round((avgEntryPrice + Trailing_Value),2) stop;
end;
//Short exit:
if (Trailingstop_Trigger=true) and (StoplossAmt > 0) and TrailingAmt > 0 then begin;
if marketposition = -1 then
BuytoCover ("TrailingStopShort") next bar Round((avgEntryPrice - Trailing_value),2) stop;
end;
I tried all sorts of combinations but I can't get it to work, anyone have an idea?