1. Introduction & Hook
Trading is a game of levels. The most successful traders know that markets respect certain price points more than others. These are not random—they are the result of collective psychology, institutional flows, and technical confluence. The Weekly/Monthly Level Strategy in Pine Script is a powerful approach that leverages these high-importance levels to boost your trading success. In this comprehensive guide, you’ll learn not just how to code this strategy, but also the market logic, mathematical foundation, and advanced automation techniques that can set you apart from the crowd.
2. What is Weekly/Monthly Level Strategy?
The Weekly/Monthly Level Strategy is a systematic trading approach that identifies and reacts to key support and resistance levels derived from weekly and monthly timeframes. These levels act as psychological barriers where price often stalls, reverses, or accelerates. By marking these levels and building rules around them, traders can anticipate high-probability trade setups, manage risk, and improve consistency. This strategy is especially popular among swing traders, position traders, and algorithmic systems that seek to exploit market structure over longer horizons.
3. Market Logic Behind the Strategy
Why do weekly and monthly levels matter? Markets are fractal, but higher timeframes dominate the narrative. Institutional traders, hedge funds, and large market participants often base their decisions on weekly and monthly charts. These levels represent consensus points where significant buying or selling has occurred. When price revisits these zones, it often triggers reactions—either as a bounce, a breakout, or a fakeout. By aligning your trades with these levels, you’re effectively trading alongside the big players, not against them.
4. Mathematical Foundation & Formula
The core of the Weekly/Monthly Level Strategy is the identification of high, low, and close prices for each week and month. These are calculated as follows:
- Weekly High: The highest price reached during the previous week.
- Weekly Low: The lowest price reached during the previous week.
- Weekly Close: The closing price of the previous week.
- Monthly High: The highest price reached during the previous month.
- Monthly Low: The lowest price reached during the previous month.
- Monthly Close: The closing price of the previous month.
These levels are then projected onto the current chart and used as reference points for trade entries, exits, and stop placements.
5. Step-by-Step Calculation Example
Let’s walk through a practical example. Suppose you’re analyzing EUR/USD on a daily chart. Here’s how you’d calculate the weekly and monthly levels:
- Suppose last week’s high was 1.1200, low was 1.1000, and close was 1.1150.
- Suppose last month’s high was 1.1300, low was 1.0900, and close was 1.1100.
On your current chart, you would draw horizontal lines at 1.1200, 1.1000, 1.1150, 1.1300, 1.0900, and 1.1100. When price approaches these levels, you look for confirmation signals (e.g., candlestick patterns, volume spikes) to enter or exit trades.
6. Pine Script Implementation
Let’s implement the Weekly/Monthly Level Strategy in Pine Script. The following code calculates and plots the previous week’s and month’s high, low, and close levels. It also highlights when price interacts with these levels.
//@version=6
// Weekly/Monthly Level Strategy
// Author: The Wallstreet Bulls
indicator("Weekly/Monthly Level Strategy", overlay=true)
// Get previous week and month high/low/close
prev_week_high = request.security(syminfo.tickerid, "W", high[1])
prev_week_low = request.security(syminfo.tickerid, "W", low[1])
prev_week_close = request.security(syminfo.tickerid, "W", close[1])
prev_month_high = request.security(syminfo.tickerid, "M", high[1])
prev_month_low = request.security(syminfo.tickerid, "M", low[1])
prev_month_close = request.security(syminfo.tickerid, "M", close[1])
// Plot levels
plot(prev_week_high, color=color.blue, linewidth=2, title="Prev Week High")
plot(prev_week_low, color=color.blue, linewidth=2, title="Prev Week Low")
plot(prev_week_close, color=color.blue, linewidth=1, style=plot.style_dotted, title="Prev Week Close")
plot(prev_month_high, color=color.purple, linewidth=2, title="Prev Month High")
plot(prev_month_low, color=color.purple, linewidth=2, title="Prev Month Low")
plot(prev_month_close, color=color.purple, linewidth=1, style=plot.style_dotted, title="Prev Month Close")
// Highlight price interaction
is_touching_week = (low <= prev_week_high and high >= prev_week_high) or (low <= prev_week_low and high >= prev_week_low)
barcolor(is_touching_week ? color.new(color.blue, 80) : na)
is_touching_month = (low <= prev_month_high and high >= prev_month_high) or (low <= prev_month_low and high >= prev_month_low)
barcolor(is_touching_month ? color.new(color.purple, 80) : na)
This script overlays the previous week’s and month’s levels on any chart. When price touches these levels, the bar color changes for easy visual identification.
7. Parameters & Customization in Pine Script
Customization is key. You can add user inputs to control which levels are displayed, their colors, and alert conditions. Here’s an enhanced version:
//@version=6
indicator("Weekly/Monthly Level Strategy Custom", overlay=true)
show_week = input(true, "Show Weekly Levels")
show_month = input(true, "Show Monthly Levels")
week_color = input.color(color.blue, "Week Level Color")
month_color = input.color(color.purple, "Month Level Color")
prev_week_high = request.security(syminfo.tickerid, "W", high[1])
prev_week_low = request.security(syminfo.tickerid, "W", low[1])
prev_week_close = request.security(syminfo.tickerid, "W", close[1])
prev_month_high = request.security(syminfo.tickerid, "M", high[1])
prev_month_low = request.security(syminfo.tickerid, "M", low[1])
prev_month_close = request.security(syminfo.tickerid, "M", close[1])
plot(show_week ? prev_week_high : na, color=week_color, linewidth=2, title="Prev Week High")
plot(show_week ? prev_week_low : na, color=week_color, linewidth=2, title="Prev Week Low")
plot(show_week ? prev_week_close : na, color=week_color, linewidth=1, style=plot.style_dotted, title="Prev Week Close")
plot(show_month ? prev_month_high : na, color=month_color, linewidth=2, title="Prev Month High")
plot(show_month ? prev_month_low : na, color=month_color, linewidth=2, title="Prev Month Low")
plot(show_month ? prev_month_close : na, color=month_color, linewidth=1, style=plot.style_dotted, title="Prev Month Close")
Now, users can toggle levels and adjust colors to fit their preferences.
8. Python & FastAPI + NoSQL Implementation
Algorithmic traders often want to calculate these levels server-side for use in dashboards, bots, or alerts. Here’s how you can implement the logic in Python, expose it via FastAPI, and store results in a NoSql Database like MongoDB.
# Python: Calculate weekly/monthly levels
from fastapi import FastAPI
from pymongo import MongoClient
from datetime import datetime, timedelta
import pandas as pd
app = FastAPI()
client = MongoClient("mongodb://localhost:27017/")
db = client["trading"]
@app.post("/levels/")
def calculate_levels(symbol: str, data: list):
df = pd.DataFrame(data)
df["date"] = pd.to_datetime(df["date"])
df.set_index("date", inplace=True)
weekly = df.resample("W").agg({"high": "max", "low": "min", "close": "last"})
monthly = df.resample("M").agg({"high": "max", "low": "min", "close": "last"})
last_week = weekly.iloc[-2]
last_month = monthly.iloc[-2]
result = {
"symbol": symbol,
"week": {"high": last_week["high"], "low": last_week["low"], "close": last_week["close"]},
"month": {"high": last_month["high"], "low": last_month["low"], "close": last_month["close"]}
}
db.levels.insert_one(result)
return result
This API receives OHLCV data, calculates the levels, stores them in MongoDB, and returns the result. You can schedule this endpoint to run after each week/month closes.
9. Node.js / JavaScript Implementation
JavaScript is popular for web dashboards and bots. Here’s a Node.js example using plain arrays:
// Node.js: Calculate weekly/monthly levels
function getLevels(data) {
// data: [{date, high, low, close}]
const weekGroups = {};
const monthGroups = {};
data.forEach(row => {
const d = new Date(row.date);
const week = `${d.getFullYear()}-W${getWeek(d)}`;
const month = `${d.getFullYear()}-${d.getMonth()+1}`;
if (!weekGroups[week]) weekGroups[week] = [];
if (!monthGroups[month]) monthGroups[month] = [];
weekGroups[week].push(row);
monthGroups[month].push(row);
});
const weeks = Object.values(weekGroups);
const months = Object.values(monthGroups);
const lastWeek = weeks[weeks.length-2];
const lastMonth = months[months.length-2];
const weekHigh = Math.max(...lastWeek.map(r => r.high));
const weekLow = Math.min(...lastWeek.map(r => r.low));
const weekClose = lastWeek[lastWeek.length-1].close;
const monthHigh = Math.max(...lastMonth.map(r => r.high));
const monthLow = Math.min(...lastMonth.map(r => r.low));
const monthClose = lastMonth[lastMonth.length-1].close;
return {
week: {high: weekHigh, low: weekLow, close: weekClose},
month: {high: monthHigh, low: monthLow, close: monthClose}
};
}
function getWeek(date) {
const onejan = new Date(date.getFullYear(),0,1);
return Math.ceil((((date - onejan) / 86400000) + onejan.getDay()+1)/7);
}
This function groups data by week and month, then extracts the required levels for use in bots or dashboards.
10. Backtesting & Performance Insights
Backtesting is essential to validate any strategy. In Pine Script, you can use the strategy namespace to automate entries and exits based on level interactions. Here’s a simple backtest logic:
//@version=6
strategy("Weekly/Monthly Level Backtest", overlay=true)
prev_week_high = request.security(syminfo.tickerid, "W", high[1])
prev_week_low = request.security(syminfo.tickerid, "W", low[1])
long_entry = ta.crossover(close, prev_week_high)
short_entry = ta.crossunder(close, prev_week_low)
if long_entry
strategy.entry("Long", strategy.long)
if short_entry
strategy.entry("Short", strategy.short)
This script enters long when price crosses above the previous week’s high, and short when it crosses below the previous week’s low. You can analyze win rate, drawdown, and expectancy using TradingView’s built-in strategy tester.
11. Risk Management Integration
Risk management is the backbone of sustainable trading. Here’s how you can integrate position sizing, stop-loss, and take-profit into your Pine Script strategy:
//@version=6
strategy("Weekly/Monthly Level Risk", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=2)
prev_week_high = request.security(syminfo.tickerid, "W", high[1])
prev_week_low = request.security(syminfo.tickerid, "W", low[1])
long_entry = ta.crossover(close, prev_week_high)
short_entry = ta.crossunder(close, prev_week_low)
stop_loss = 1.5 * syminfo.mintick
profit_target = 3.0 * syminfo.mintick
if long_entry
strategy.entry("Long", strategy.long)
strategy.exit("Long Exit", from_entry="Long", stop=prev_week_low, limit=close+profit_target)
if short_entry
strategy.entry("Short", strategy.short)
strategy.exit("Short Exit", from_entry="Short", stop=prev_week_high, limit=close-profit_target)
This code uses a percentage of equity for position sizing, sets stop-loss at the opposite weekly level, and a fixed profit target. You can further refine this with ATR-based stops or volatility filters.
12. Combining with Other Indicators
The Weekly/Monthly Level Strategy is even more powerful when combined with other indicators. For example, you can filter trades using RSI, MACD, or moving averages. Here’s how to add an RSI filter:
//@version=6
strategy("Weekly/Monthly Level + RSI", overlay=true)
prev_week_high = request.security(syminfo.tickerid, "W", high[1])
prev_week_low = request.security(syminfo.tickerid, "W", low[1])
rsi = ta.rsi(close, 14)
long_entry = ta.crossover(close, prev_week_high) and rsi > 50
short_entry = ta.crossunder(close, prev_week_low) and rsi < 50
if long_entry
strategy.entry("Long", strategy.long)
if short_entry
strategy.entry("Short", strategy.short)
This script only enters trades when the RSI confirms momentum in the direction of the breakout.
13. Multi-Timeframe & Multi-Asset Usage
One of the greatest strengths of this strategy is its adaptability. You can apply it to any timeframe or asset class:
- Intraday: Use previous day’s high/low for 15m or 1h charts.
- Swing: Use weekly/monthly levels for daily or 4h charts.
- Assets: Works for stocks, forex, crypto, commodities, and even options (for level-based spreads).
To implement multi-timeframe logic in Pine Script:
//@version=6
indicator("Multi-Timeframe Levels", overlay=true)
prev_day_high = request.security(syminfo.tickerid, "D", high[1])
prev_week_high = request.security(syminfo.tickerid, "W", high[1])
prev_month_high = request.security(syminfo.tickerid, "M", high[1])
plot(prev_day_high, color=color.orange, title="Prev Day High")
plot(prev_week_high, color=color.blue, title="Prev Week High")
plot(prev_month_high, color=color.purple, title="Prev Month High")
This overlays multiple timeframe levels for confluence trading.
14. AI/ML Enhancements
Modern trading leverages AI and machine learning to optimize strategies. Here’s how you can use the Weekly/Monthly Level Strategy as a feature for ML models:
- Feature Engineering: Use distance to nearest weekly/monthly level as an input feature.
- Reinforcement Learning: Train an RL agent to optimize entry/exit parameters based on level interactions.
# Python pseudocode for RL agent
state = [price, distance_to_week_high, distance_to_week_low, rsi]
action = agent.select_action(state)
reward = calculate_pnl()
agent.learn(state, action, reward)
This approach allows your bot to learn optimal behaviors around key levels, adapting to changing market regimes.
15. Automation with Playwright/Jest
Testing your strategy scripts is crucial for reliability. You can use playwright for end-to-end browser automation or Jest for unit testing in JavaScript environments.
// Jest unit test for Node.js level calculator
const { getLevels } = require('./levels');
test('calculates correct weekly/monthly levels', () => {
const data = [
{date: '2023-01-01', high: 10, low: 5, close: 8},
{date: '2023-01-02', high: 12, low: 7, close: 11},
// ... more data
];
const levels = getLevels(data);
expect(levels.week.high).toBeGreaterThanOrEqual(levels.week.low);
expect(levels.month.high).toBeGreaterThanOrEqual(levels.month.low);
});
For Playwright, you can automate TradingView chart interactions to verify that your Pine Script plots levels correctly.
16. Advanced Variations
There are many ways to enhance the Weekly/Monthly Level Strategy:
- Dynamic Levels: Use ATR or volatility bands around weekly/monthly levels.
- Volume Profile: Combine with volume-at-price analysis for stronger confluence.
- Breakout Filters: Require confirmation from order flow or momentum indicators.
- Partial Exits: Scale out at multiple targets based on level proximity.
17. Common Pitfalls & Misconceptions
- Blindly trading every touch: Not every interaction with a level is a trade signal. Wait for confirmation.
- Ignoring context: Consider trend, volatility, and news events.
- Overfitting: Avoid excessive parameter tuning on historical data.
- Neglecting risk: Always use stops and proper position sizing.
18. Conclusion & Key Takeaways
The Weekly/Monthly Level Strategy is a robust, time-tested approach that leverages the power of higher timeframe levels. By understanding the market logic, implementing the right code, and integrating risk management, you can trade with greater confidence and consistency. Combine this strategy with other indicators, automate your workflow, and use AI to stay ahead of the curve. Remember: discipline and adaptability are your greatest assets.
Glossary of Key Terms
- Support/Resistance: Price levels where buying or selling pressure is expected to emerge.
- OHLC: Open, High, Low, Close prices for a given period.
- ATR: Average True Range, a measure of volatility.
- Backtesting: Testing a strategy on historical data to evaluate performance.
- Confluence: Multiple signals or levels aligning to strengthen a trade setup.
- Reinforcement Learning: A type of machine learning where agents learn by trial and error.
Comparison Table
| Strategy | Timeframe | Key Levels | Best For | Drawbacks |
|---|---|---|---|---|
| Weekly/Monthly Level | Weekly, Monthly | Prev High/Low/Close | Swing, Position | May miss fast moves |
| Daily Pivot | Daily | Pivot, S/R | Intraday | More noise |
| Moving Average Cross | Any | MA values | Trend | Lags in ranging |
| Breakout | Any | Recent High/Low | Momentum | False breakouts |
TheWallStreetBulls