Limiting Strategy to 1 Trade a Day

_Merch_Man_

Active member
Hey guys. Just when I thought I was getting the hang of this ThinkScript I get stumped! I am working on a strategy where I only want to execute one trade a day, even if the trade entry criteria are met multiple times in the day. In pseudo code:

tradeTrigger = if tradeCriteraMet and noTradeDoneToday then 1 else 0;

Here's what doesn't work:

Ruby:
def tradeCondition = if high > low then 1 else 0;
def tradeDoneToday;
    
addOrder(condition=tradeCondition && !tradeDoneToday, type=OrderType.BUY_TO_OPEN, price=high, tradeSize=1, name="B2O");
addOrder(condition=low < entryPrice()-2 or high > entryPrice()+2, type=OrderType.SELL_TO_CLOSE, price=close, tradeSize=1, name="S2C");)

tradeDoneToday = if tradeCondition == 1 then 1 else tradeDoneToday[1];
/CODE]

How can I create a variable that will allow me to check to see if a trade was already done today?

TIA - Matt.
 
to limit the quantity of orders in a day, you can count the buy signals and limit the buys based on a counter.

here is a lower test study, that allows you to,
...pick a quantity of max trades to do , 1 or greater, over some time period.
...choose to reset the trade counter every day. (set trade period to a day or entire chart)

when a trigger signal occurs, it increases a counter.
if the counter is <= the max trades, then the trigger signal is passed on to enable a buy signal.

it draws 3 signals to help you visualize what it does.

the top line and the middle line are the buy signal spikes
the bottom line is the input

in the image below,
maxtrades was set to 2 and
reset_each_day was equal to yes

Ruby:
# do_once_03
# halcyonguy
# 2020-07

# make an output var that changes only x times, with multiple input triggers

declare lower;

input maxtrades = 1;

def lastbar = !isnan(close) && isnan(close[-1]);
#def istoday = if GetLastDay() == GetDay() then 1 else 0;
def dow2 = GetDayofWeek(GetYYYYMMDD());

input reset_each_day = yes;
def dow = if reset_each_day then dow2 else 0;

# ==================================================================
# replace this section with your trigger formula(s)
# replace the trigger2 =  formula with your master trigger formula

# test formulas , 2 averages
def cls = close;
input length1 = 7;
input length2 = 11;
def AvgExp1 = ExpAverage(cls, length1);
def AvgExp2 = ExpAverage(cls, length2);
# trigger signal
def trigger2 = if avgexp1 > AvgExp2 then 1 else 0;
# =================================================================

# set it true when the trigger2 signal changes from a low to a high
def trigger = (trigger2[1] == 0 and trigger2[0] == 1);

def cnt = if barnumber() == 1 then 0
 else if ((dow <> dow[1]) and trigger) then 1
 else if (dow <> dow[1]) then 0
 else if trigger then (cnt[1] + 1)
 else cnt[1];

def buy = ( trigger and cnt <= maxtrades);

plot trig2 = if trigger2 then 2 else 1;
plot once2 = if buy then 4 else 3;
plot buy2 = if buy then 6 else 5;

# top and bottom lines, to make it easier to see signal lines
plot a = 0;
plot b = 7;

# desc bubbles location
input bubble_offset = 2;
input show_bubbles = yes;
def x = show_bubbles and lastbar[bubble_offset];

addchartbubble(x , 0.5 , "trigger" , Color.YELLOW , yes);
addchartbubble(x , 2.5 , maxtrades + "/" + (if reset_each_day then "day" else "chart"), Color.YELLOW , yes);
addchartbubble(x , 4.5 , "buy" , Color.YELLOW , yes);

# day separator lines
addverticalline((dow <> dow[1]), "day", color.cyan);

#addchartbubble(1, 9, dow + "\n" + dow[1] , color.cyan, no);
#addchartbubble(1, 9, trigger + "\n" + cnt , color.cyan, no);
#plot t = 9.5;
#

kUg089z.jpg
 

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

to limit the quantity of orders in a day, you can count the buy signals and limit the buys based on a counter.

here is a lower test study, that allows you to,
...pick a quantity of max trades to do , 1 or greater, over some time period.
...choose to reset the trade counter every day. (set trade period to a day or entire chart)

when a trigger signal occurs, it increases a counter.
if the counter is <= the max trades, then the trigger signal is passed on to enable a buy signal.

it draws 3 signals to help you visualize what it does.

the top line and the middle line are the buy signal spikes
the bottom line is the input

in the image below,
maxtrades was set to 2 and
reset_each_day was equal to yes

Ruby:
# do_once_03
# halcyonguy
# 2020-07

# make an output var that changes only x times, with multiple input triggers

declare lower;

input maxtrades = 1;

def lastbar = !isnan(close) && isnan(close[-1]);
#def istoday = if GetLastDay() == GetDay() then 1 else 0;
def dow2 = GetDayofWeek(GetYYYYMMDD());

input reset_each_day = yes;
def dow = if reset_each_day then dow2 else 0;

# ==================================================================
# replace this section with your trigger formula(s)
# replace the trigger2 =  formula with your master trigger formula

# test formulas , 2 averages
def cls = close;
input length1 = 7;
input length2 = 11;
def AvgExp1 = ExpAverage(cls, length1);
def AvgExp2 = ExpAverage(cls, length2);
# trigger signal
def trigger2 = if avgexp1 > AvgExp2 then 1 else 0;
# =================================================================

# set it true when the trigger2 signal changes from a low to a high
def trigger = (trigger2[1] == 0 and trigger2[0] == 1);

def cnt = if barnumber() == 1 then 0
 else if ((dow <> dow[1]) and trigger) then 1
 else if (dow <> dow[1]) then 0
 else if trigger then (cnt[1] + 1)
 else cnt[1];

def buy = ( trigger and cnt <= maxtrades);

plot trig2 = if trigger2 then 2 else 1;
plot once2 = if buy then 4 else 3;
plot buy2 = if buy then 6 else 5;

# top and bottom lines, to make it easier to see signal lines
plot a = 0;
plot b = 7;

# desc bubbles location
input bubble_offset = 2;
input show_bubbles = yes;
def x = show_bubbles and lastbar[bubble_offset];

addchartbubble(x , 0.5 , "trigger" , Color.YELLOW , yes);
addchartbubble(x , 2.5 , maxtrades + "/" + (if reset_each_day then "day" else "chart"), Color.YELLOW , yes);
addchartbubble(x , 4.5 , "buy" , Color.YELLOW , yes);

# day separator lines
addverticalline((dow <> dow[1]), "day", color.cyan);

#addchartbubble(1, 9, dow + "\n" + dow[1] , color.cyan, no);
#addchartbubble(1, 9, trigger + "\n" + cnt , color.cyan, no);
#plot t = 9.5;
#

kUg089z.jpg
this does not work when placed within a custom strategy. is there any reason for that? i'm seeing zero trades rather than the one per day i have it set at.
 
hi thx for your quick reply.

this code i posted is after an hour or so of fiddling with your original code and also looking at the other local post on counting you posted for extra input to try and get it to work. its still not working in this form. i attempted to embed your code exactly as it is written, simply changing the variables to fit my code, and that yielded the same result showing zero trades on the chart and no trade data for the strategy at all. when i remove the code which is attempting to limit the number of trades to one per day, either when using your code in its original form, or my version i posted here, then i see trades on the chart as expected.

code not relevant to the question is left out intentionally.

Code:
# break of custom time range high/low strategy

input timePeriodStart = 800;
input timePeriodEnd = 930;
input tradePeriodStart = 930;
input tradePeriodEnd = 1659;

def startPeriodCounter = SecondsFromTime(timePeriodStart);
def endPeriodCounter = SecondsTillTime(timePeriodEnd);
def timeRangeWindow = if startPeriodCounter >= 0 and endPeriodCounter >= 0 then 1 else 0;
def timeWindowStart = !timeRangeWindow[1] and timeRangeWindow;
def timeRangeWindowHigh = CompoundValue(1, if timeWindowStart then high else if timeRangeWindow then Max(high, timeRangeWindowHigh[1]) else timeRangeWindowHigh[1], 0);
def timeRangeWindowLow = CompoundValue(1, if timeWindowStart then low else if timeRangeWindow then Min(low, timeRangeWindowLow[1]) else timeRangeWindowLow[1], 0);

def startTradeCounter =  SecondsFromTime(tradePeriodStart);
def endTradeCounter = SecondsTillTime(tradePeriodEnd);
def tradeWindow = if startTradeCounter >= 0 and endTradeCounter >= 0 then 1 else 0;
def tradeWindowStart = !tradeWindow[1] and tradeWindow;

def longSignal = close > timeRangeHigh and close[1] <= timeRangeHigh;
def shortSignal = close < timeRangeLow and close[1] >= timeRangeLow;
def signal = if tradeWindow and ( longSignal or shortSignal ) then 1 else 0;

# count number of trades per day, limit to 1 per day:
def tradeCount = if tradeWindowStart then 0 else if tradeWindow and EntryPrice() then 1 else tradeCount[1];

# trade entry rules:
def longEntry = tradeWindow and longSignal and !tradeCount;
def shortEntry = tradeWindow and shortSignal and !tradeCount;
 
Last edited:
hi thx for your quick reply.

this code i posted is after an hour or so of fiddling with your original code and also looking at the other local post on counting you posted for extra input to try and get it to work. its still not working in this form. i attempted to embed your code exactly as it is written, simply changing the variables to fit my code, and that yielded the same result showing zero trades on the chart and no trade data for the strategy at all. when i remove the code which is attempting to limit the number of trades to one per day, either when using your code in its original form, or my version i posted here, then i see trades on the chart as expected.

code not relevant to the question is left out intentionally.

Code:
# break of custom time range high/low strategy

input timePeriodStart = 800;
input timePeriodEnd = 930;
input tradePeriodStart = 930;
input tradePeriodEnd = 1659;

def startPeriodCounter = SecondsFromTime(timePeriodStart);
def endPeriodCounter = SecondsTillTime(timePeriodEnd);
def timeRangeWindow = if startPeriodCounter >= 0 and endPeriodCounter >= 0 then 1 else 0;
def timeWindowStart = !timeRangeWindow[1] and timeRangeWindow;
def timeRangeWindowHigh = CompoundValue(1, if timeWindowStart then high else if timeRangeWindow then Max(high, timeRangeWindowHigh[1]) else timeRangeWindowHigh[1], 0);
def timeRangeWindowLow = CompoundValue(1, if timeWindowStart then low else if timeRangeWindow then Min(low, timeRangeWindowLow[1]) else timeRangeWindowLow[1], 0);

def startTradeCounter =  SecondsFromTime(tradePeriodStart);
def endTradeCounter = SecondsTillTime(tradePeriodEnd);
def tradeWindow = if startTradeCounter >= 0 and endTradeCounter >= 0 then 1 else 0;
def tradeWindowStart = !tradeWindow[1] and tradeWindow;

def longSignal = close > timeRangeHigh and close[1] <= timeRangeHigh;
def shortSignal = close < timeRangeLow and close[1] >= timeRangeLow;
def signal = if tradeWindow and ( longSignal or shortSignal ) then 1 else 0;

# count number of trades per day, limit to 1 per day:
def tradeCount = if tradeWindowStart then 0 else if tradeWindow and EntryPrice() then 1 else tradeCount[1];

# trade entry rules:
def longEntry = tradeWindow and longSignal and !tradeCount;
def shortEntry = tradeWindow and shortSignal and !tradeCount;

you posted partial, incomplete code.
there is nothing i can do with this.
i will check back in a few days to see if you posted complete code.


timeRangeHigh and timeRangelow are used in these formulas, and are not defined.
def longSignal = close > timeRangeHigh and close[1] <= timeRangeHigh;
def shortSignal = close < timeRangeLow and close[1] >= timeRangeLow;

i am not going to guess at what formulas should be assigned to those variables.

are you trying to modify a paid for study?
.. if yes, then it will be hard to help without seeing the code.
.. if no, then post the whole code. you don't have any secret code that hasn't been seen before.

-----------------------

but i may not be able to help. i see you are using EntryPrice() and i haven't used that function very much. i think it has an average $$ value when there is an active trade.
in your formula , def tradeCount = , you are treating it like a boolean instead of a number variable. ( checking if it is true or false)
i think positives numbers are interpretted as true, but might be better to check if it is > 0 . ( if EntryPrice() > 0 ... )
 
you posted partial, incomplete code.
there is nothing i can do with this.
i will check back in a few days to see if you posted complete code.


timeRangeHigh and timeRangelow are used in these formulas, and are not defined.
def longSignal = close > timeRangeHigh and close[1] <= timeRangeHigh;
def shortSignal = close < timeRangeLow and close[1] >= timeRangeLow;

i am not going to guess at what formulas should be assigned to those variables.

are you trying to modify a paid for study?
.. if yes, then it will be hard to help without seeing the code.
.. if no, then post the whole code. you don't have any secret code that hasn't been seen before.

-----------------------

but i may not be able to help. i see you are using EntryPrice() and i haven't used that function very much. i think it has an average $$ value when there is an active trade.
in your formula , def tradeCount = , you are treating it like a boolean instead of a number variable. ( checking if it is true or false)
i think positives numbers are interpretted as true, but might be better to check if it is > 0 . ( if EntryPrice() > 0 ... )
it is not a paid for study, just a custom one. and as i said, it works without the tradecounter so that is the main focus of my question. hence the lack of the rest of the code simply for brevity sake.

i arrived at using EntryPrice() simply because i couldn't get your code to function with the strategy once your code was integrated. i have seen EntryPrice() used as a way to confirm that a trade is currently open. in this case i am simply using it to confirm that a trade has been opened for a particular day / trading session.

i'm pretty sure it can be checked like a boolean because i am expecting 0 or NaN to be returned if there is no active trade and this will be interpreted exactly the same as boolean "false". if it actually is a number it should return true regardless. i don't think using EntryPrice() is the issue, considering none of the other logic / options for coding this have worked so far, but i'll give it a try using >0 just to check. thank you.

here is the full code:

Code:
# break of custom time range high/low

input timePeriodStart = 800;
input timePeriodEnd = 930;
input tradePeriodStart = 930;
input tradePeriodEnd = 1659;
input numberOfDays = 0;
input numberOfYears = 0;
input target = .100;
input stop = .050;
input tradeSize = 1;

def oneTick = TickSize(GetSymbol());

def okToPlot = GetLastDay() - numberOfDays <= GetDay() and GetLastYear() - numberOfYears <= GetYear();

# the time range window
def startPeriodCounter = SecondsFromTime(timePeriodStart);
def endPeriodCounter = SecondsTillTime(timePeriodEnd);
def timeRangeWindow = if startPeriodCounter >= 0 and endPeriodCounter >= 0 then 1 else 0;

# the trading window
def startTradeCounter =  SecondsFromTime(tradePeriodStart);
def endTradeCounter = SecondsTillTime(tradePeriodEnd);
def tradeWindow = if startTradeCounter >= 0 and endTradeCounter >= 0 then 1 else 0;

def timeWindowStart = !timeRangeWindow[1] and timeRangeWindow;
def tradeWindowStart = !tradeWindow[1] and tradeWindow;

def timeRangeWindowHigh = CompoundValue(1, if timeWindowStart then high else if timeRangeWindow then Max(high, timeRangeWindowHigh[1]) else timeRangeWindowHigh[1], 0);
def timeRangeWindowLow = CompoundValue(1, if timeWindowStart then low else if timeRangeWindow then Min(low, timeRangeWindowLow[1]) else timeRangeWindowLow[1], 0);

def timeRangeHigh = if okToPlot and tradeWindow then timeRangeWindowHigh else Double.NaN;
def timeRangeLow = if okToPlot and tradeWindow then timeRangeWindowLow else Double.NaN;

def longSignal = close > timeRangeHigh and close[1] <= timeRangeHigh;
def shortSignal = close < timeRangeLow and close[1] >= timeRangeLow;
def signal = if tradeWindow and ( longSignal or shortSignal ) then 1 else 0;

def tradeCount = if tradeWindowStart then 0 else if tradeWindow and EntryPrice() then 1 else tradeCount[1];

def longEntry = tradeWindow and longSignal and !tradeCount; 
def shortEntry = tradeWindow and shortSignal and !tradeCount;

def longEntryPrice = open[-1];
def shortEntryPrice = open[-1];
def longTargetPrice = if longEntry then ((longEntryPrice + target) / oneTick) * oneTick else longTargetPrice[1];
def shortTargetPrice = if shortEntry then ((shortEntryPrice - target) / oneTick) * oneTick else shortTargetPrice[1];
def longTarget = high[-1] >= longTargetPrice;
def shortTarget = low[-1] <= shortTargetPrice;
def longStopPrice = if longEntry then ((longEntryPrice - stop) / oneTick) * oneTick else longStopPrice[1];
def shortStopPrice = if shortEntry then ((shortEntryPrice + stop) / oneTick) * oneTick else shortStopPrice[1];
def longStop = low[-1] <= longStopPrice;
def shortStop = high[-1] >= shortStopPrice;

AddOrder(OrderType.BUY_AUTO, longEntry, longEntryPrice, tradeSize, Color.GREEN, Color.GREEN);
AddOrder(OrderType.SELL_TO_CLOSE, longStop, longStopPrice, tradeSize, Color.GRAY, Color.GRAY);
AddOrder(OrderType.SELL_TO_CLOSE, longTarget, longTargetPrice, tradeSize, Color.MAGENTA, Color.MAGENTA);

AddOrder(OrderType.SELL_AUTO, shortEntry, shortEntryPrice, tradeSize, Color.RED, Color.RED);
AddOrder(OrderType.BUY_TO_CLOSE, shortStop, shortStopPrice, tradeSize, Color.GRAY, Color.GRAY);
AddOrder(OrderType.BUY_TO_CLOSE, shortTarget, shortTargetPrice, tradeSize, Color.YELLOW, Color.YELLOW);
 
Last edited:

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
393 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top