- ago
I have A / B / C / D / E / F six symbols in Dataset.

All money has gone to buy three (A / B / C) symbols, there are three other (D / E / F) symbols buying signals today,

I have to sell A / B / C symbols first in Execute before buy D / E / F symbols to avoid NSF, What should i do?

Thx
0
1,480
Solved
12 Replies

Reply

Bookmark

Sort
Cone8
 ( 7.72% )
- ago
#1
Not enough information about the buys and sells.

But, if we're talking about market orders, if I'm not mistaken, exits at market will occur first by backtest design. If I am mistaken (don't think so, but possible), you can set the Transaction.Weight for all trades. The highest Weights are executed first.
0
- ago
#2
This strategy buys only one symbol.

Strategy description:

DataSet : two symbols

calculate 5-day return timeseries

select are two symbols maximum value ( return ) on Thursday

buy the symbol with all capital.

CODE:
using WealthLab.Backtest; using System; using WealthLab.Core; using System.Collections.Generic; namespace WealthScript4 {       public class NSF_strategy : UserStrategyBase    {             private static List<BarHistory> Buys = new List<BarHistory>();       TimeSeries _Ts_Rtn;       double _TE_val;              public NSF_strategy()       {          AddParameter(" Window ", ParameterTypes.Int32, 5, 5, 60, 1);       }              public override void Initialize(BarHistory bars)       {          StartIndex = Parameters[0].AsInt;          _Ts_Rtn = new TimeSeries(bars.DateTimes, 0);                    for (int i = StartIndex; i < bars.Count -1; i++)             _Ts_Rtn[i] = (bars.Close[i] - bars.Close[i - StartIndex]) / bars.Close[i - StartIndex];          bars.Cache["Return"] = _Ts_Rtn;          PlotTimeSeries(_Ts_Rtn, "T(5)-T(0)", "ReturnTimeSeries_Pane");       }        public override void PreExecute(DateTime dt, List<BarHistory> participants) {          foreach (BarHistory bh in participants)          {                TimeSeries _TE = (TimeSeries)bh.Cache["Return"];                int idx = GetCurrentIndex(bh);                _TE_val = _TE[idx];                bh.UserData = _TE_val;          }          participants.Sort((a, b) => -a.UserDataAsDouble.CompareTo(b.UserDataAsDouble)); //H to L                    Buys.Clear();          Buys.Add(participants[0]); } public override void Execute(BarHistory bars, int idx)       {          bool _BuyList = Buys.Contains(bars);                    if(((int)bars.GetDate(idx).DayOfWeek).ToString() == "4")          {             if (!_BuyList)             {                if (HasOpenPosition(bars, PositionType.Long))                   ClosePosition(LastPosition, OrderType.Market);             }             else if (_BuyList)             {                if (!HasOpenPosition(bars, PositionType.Long))                {                   var Q = Math.Floor(CurrentEquity * 1 / bars.Close[idx]);                   PlaceTrade(bars, TransactionType.Buy, OrderType.Market).Quantity = Q;                }             }          }       }    } }


Strategy Settings :



problem 1. Why buy two symbols ( See Backtest Results Equity Curve image )



problem 2. Why is NSF produced ( See Backtest Results Metrics Report image )



Thx.
0
Cone8
 ( 7.72% )
- ago
#3
The NSF issue is easy. You're using 100% equity but the Basis Price is "Market Close this Bar". To avoid NSF with 100% sizing:
1. select Basis Price "Market Open Next Bar", OR,
2. reduce the sizing to account for gaps, OR,
3. Use some Margin, like 1.20

I'll have to look more closely at the script to see how you can end up with 2 positions.
1
Cone8
 ( 7.72% )
- ago
#4
I actually can't duplicate the 2-symbol issue with the 2 instruments I tested with (ZS, TTD).

However, your logic requires a DayOfWeek = 4 to execute. That would be a problem if one of the instruments doesn't trade on that day. Check the questionable trades and the data for that week. Maybe there's a day or two missing.
1
- ago
#5
Hi, Cone

QUOTE:

I actually can't duplicate the 2-symbol issue with the 2 instruments I tested with (ZS, TTD).

However, your logic requires a DayOfWeek = 4 to execute. That would be a problem if one of the instruments doesn't trade on that day. Check the questionable trades and the data for that week. Maybe there's a day or two missing.


I use the IsTradingDay function to determine whether the next day is a trading day

but the symbol (SH600196) date 2010/1/8 does not exist in the data

print out IsTradingDay is true, Why?

CODE:
         string Result = string.Format(" {0:20} {1:20} \r\n {2:20} {3:20} \r\n {4:20} {5:20} \r\n {6:20} {7:20} \r\n {8:20} {9:20}"             , " Today = ", bars.GetDate(idx).ToString("yyyy/M/d")             , " Symbol = ", bars.Symbol             , " NextDayIsTrading = ", bars.Market.IsTradingDay(bars.GetDate(idx).AddDays(1))             , " NextDate = ", bars.GetDate(idx).AddDays(1).ToString("yyyy/M/d")             , " NextDateOfWeek = ", ((int)bars.GetDate(idx).AddDays(1).DayOfWeek).ToString());          WriteToDebugLog("----------------------------------");          WriteToDebugLog(Result);




0
- ago
#6
QUOTE:
but the symbol (SH600196) date 2010/1/8 does not exist in the data

print out IsTradingDay is true, Why?

Because as far the U.S. market schedule is concerned, it's a business day. Apparently, your ASCII symbols are assigned the default market (US Stocks) whereas you're trading Chinese markets.

You could create a new market for Chinese stocks in Tools > Markets and Symbols and configure its properties. Then use its Symbols tab to set up a pattern for stocks like SH###### (assuming all your stocks follow this pattern).

Pay attention to entering holidays so that 2010/1/8 would be recognized. If you did everything right, all symbols starting with SH... and having 6 digits will be assigned to the newly defined China market.

Finally, if you know a reliable historical source of holiday dates for the Chinese market, please let us know so we could beef up WL7 with a new market and include the holiday schedule.
1
Best Answer
- ago
#7
QUOTE:
But, if we're talking about market orders, if I'm not mistaken, exits at market will occur first by backtest design.

This thread is a couple of years old and I'm wondering if we have a more definitive answer today. Based on the WL current build, will WL prioritize sell orders before buy orders on the same bar assuming:
1. Market orders for all signals
2. Live trading

This is critical to know when using a quasi-rotation-type strategy with an IRA account where there is limited margin (only allows immediate use of pending cash for new positions). Assuming account cash is near zero, the broker will reject an attempt to open a new position, unless it is preceded by closing a position with an equal or higher cash value.
0
Cone8
 ( 7.72% )
- ago
#8
Market Exits first, Stop/Limit Exits next, then Entries. Always that order.
This isn't a "priority" question. It always happens that way.

If you're trying to immediately use cash from an exit and don't have margin or cash for a new entry, there's always a chance that order will be rejected. NYSE stocks may open late for example, so a MOO exit may be "Active" for several minutes before the first trade on the primary exchange.
0
- ago
#9
Yes, I understand. These trades are happening mid-market hours. Thanks for the confirmation.
0
- ago
#10
@Cone, I have a type of rotation strategy that requires the cash from a Sell signal to finance a Buy signal (with a limited margin account like an IRA). I have this testing with WL Dummy Broker and today it apparently tried to process the Buy before the Sell and failed. I thought this had happened before, which is why I asked my question.



Is this a quirk with the Dummy Broker or is it likely to perform the same way with a live broker?
0
- ago
#11
Error message was cut off in previous image

0
Cone8
 ( 7.72% )
- ago
#12
Same answer as Post #8.

The dummy broker can take several seconds or more to exit a market order, and, sorting the list for items with the same timestamp won't guarantee that you see the sequence that the orders were processed. Market exits are processed before market entries.
0

Reply

Bookmark

Sort