User: We have websocket that pushes realtime klines updates for each change in current 1min candle. Program should to determine last update for each candle and output the close price from this update (so in other words it outputs close price of each 1min candle). Explain in words how to do this.
Response:
{"symbol":"BTC_USDT","data":{"symbol":"BTC_USDT","interval":"Min1","t":1732134720,"o":94258.5,"c":94268.6,"h":94287.9,"l":94252,"a":3443194.35551,"q":365211,"ro":94258.5,"rc":94268.6,"rh":94287.9,"rl":94252},"channel":"push.kline","ts":1732134748705}
Response data parameters description:
Parameter Data Type Description
symbol string the name of the contract
a decimal total transaction amount
c decimal the closing price
interval string interval: Min1、Min5、Min15、Min30、Min60、Hour4、Hour8、Day1、Week1、Month1
l decimal the lowest price
o decimal the opening price
q decimal total transaction volume
h decimal the highest price
t long trading time,unit:second(s), the start time of the window(windowStart)
Assistant: To determine and output the closing price of each 1-minute candle from a websocket that continuously pushes kline updates, you'll need to follow these steps:
Connect to the Websocket:
Set up your application to connect to the websocket server and subscribe to the relevant channel for 1-minute klines (push.kline with an interval of Min1).
Receive and Parse Messages:
As the websocket sends data, your program should be capable of receiving these messages. The data will be in JSON format, similar to the example you provided.
Parse the JSON to extract relevant fields, particularly the symbol, interval, time t, and the close price c.
Track Candle Updates:
For each unique t value (which represents the start time of each 1-minute interval), track the updates you receive. This means storing the latest message for each unique t until you determine it is complete.
Determine when a Candle is Complete:
A 1-minute candle is "complete" once no more updates are received for that specific time window (t) and the time advances to the next window. One way to determine this is by waiting for a message with a t value greater than the current one. This indicates that the next candle has started, and the previous one is now complete.
Output the Closing Price:
Once you determine that a candle is complete (i.e., the start of a new one-min interval is detected because the value changes), output the last received close price for that interval.
Assistant
t
c
Repeat for the Next Candle:
Reset your tracker for the next time interval (t) and repeat the process.
Here is how you could implement this logic in pseudocode:
initialize websocket connection
subscribe to 'push.kline' for 'Min1'
candle_data = {}
on websocket message (receive data):
parse JSON data to extract:
symbol = data["symbol"]
interval = data["data"]["interval"]
start_time = data["data"]["t"]
close_price = data["data"]["c"]
if interval == "Min1":
if start_time not in candle_data:
# Detect the end of the current candle
for previous_time in list(candle_data.keys()):
if previous_time < start_time:
# Output the last known close price for completed candle
print(f"Completed Candle Close: {candle_data[previous_time].close_price}")
# Remove the completed candle from tracking
del candle_data[previous_time]
# Update or set the latest close price for the current candle
candle_data[start_time] = {"close_price": close_price}
This approach allows the program to monitor each 1-minute interval and ensure that it outputs the final close price as soon as the updates stop for that interval, marking the end of the candle.
User: Add this to this Python program:
import json
import traceback
import requests
from websocket import create_connection
from conf import CHAT_ID, TELEGRAM_API_URL
MEXC WebSocket and Telegram Bot configurations
MEXC_WS_URL = "wss://contract.mexc.com/edge"
PAIR = "BTC_USDT" # Set the pair you want to track
TIMEFRAME = "Min1" # 1-minute candles
TREND_SIDE = "long" # Set the trend side ("long" for upward, "short" for downward)
except Exception as e:
print("Error sending message:", e)
Function to analyze the candles for conditions
def analyze_candles():
global max_price, min_price, max_volume, message_count
if len(candles) < 3:
return # Not enough data yet
last_candle = candles[-1]
last_price = last_candle["close"]
last_volume = last_candle["volume"]
# Update max and min price and volume
max_price = max(max_price, last_price)
min_price = min(min_price, last_price)
max_volume = max(max_volume, last_volume)
# Condition 1: Three consecutive candles closing in the same direction
if (TREND_SIDE == "long" and all(c["close"] > c["open"] for c in candles[-3:])) or \
(TREND_SIDE == "short" and all(c["close"] < c["open"] for c in candles[-3:])):
send_telegram_message(f"COND 1: Three consecutive {TREND_SIDE} candles.")
# Condition 2: Candle closes with a 5% or more change in trend direction
change_percent = ((last_candle["close"] - last_candle["open"]) / last_candle["open"]) * 100
if (TREND_SIDE == "long" and change_percent >= 5) or \
(TREND_SIDE == "short" and change_percent <= -5):
send_telegram_message(f"COND 2: Candle closed with a {change_percent:.2f}% {TREND_SIDE} change.")
# Condition 3: Three consecutive candles with increasing volume
if len(candles) >= 4:
if all(float(candles[i]["volume"]) > float(candles[i - 1]["volume"]) for i in range(-3, 0)):
send_telegram_message("COND 3: Three consecutive candles with increasing volume.")
# Every 10 candles, send a summary message
message_count += 1
if message_count >= 10:
price_ratio = (last_price / max_price) * 100
price_min_ratio = (last_price / min_price) * 100
volume_ratio = (last_volume / max_volume) * 100
summary = (
f"MAX {price_ratio:.2f}%\n"
f"MIN {price_min_ratio:.2f}%\n"
f"VOL {volume_ratio:.2f}%"
)
send_telegram_message(summary)
message_count = 0
Function to process WebSocket messages
def process_message(message):
global candles
global current_candle_time
data = json.loads(message)
print(message)
if "channel" in data and data["channel"] == "push.kline":
candle = data["data"]
# Check if candle matches our interval and pair
# if not candles or (int(candles[-1]["timestamp"])-int(candle["t"]))==60:
# if not candles and candle or candles[-1]["timestamp"] + 60 == candle["t"]:
if current_candle_time != candle["t"]:
current_candle_time = candle["t"]
new_candle = {
"open": float(candle["o"]),
"close": float(candle["c"]),
"high": float(candle["h"]),
"low": float(candle["l"]),
"volume": float(candle["q"]), # total transaction volume
"timestamp": candle["t"]
}
candles.append(new_candle)
print(candles)
# Keep only the last 10 candles for analysis
if len(candles) > 10:
candles.pop(0)
analyze_candles()
Main function to connect to the MEXC WebSocket
def main():
global msg
ws = create_connection(MEXC_WS_URL)
# Subscribe to 1-minute kline data for the chosen pair
ws.send(json.dumps({
"method": "sub.kline",
"param": {
"symbol": PAIR,
"interval": TIMEFRAME
}
}))
if name == "main":
while True:
try:
main()
except Exception:
# time.sleep(3)
print(traceback.format_exc())
# print("MSG",msg)
send_telegram_message(traceback.format_exc())
Assistant:
To incorporate the logic that ensures the last update of each 1-minute candle is used to output the close price into your existing Python program, you can modify the process_message function to track the unique timestamp of each candle. By doing this, you will be able to determine when a candle has completed its updates and output the close price appropriately.
Here's how you can modify the program:
Track the current_candle_time and update the close price whenever a message is received for the current interval.
Detect when a candle is complete by checking if the next message belongs to a new interval.
Output and store the close price once a candle is confirmed to be complete.
Below is the updated process_message function and related adjustments:
# Function to process WebSocket messages
def process_message(message):
global candles
global current_candle_time
data = json.loads(message)
if "channel" in data and data["channel"] == "push.kline":
candle_data = data["data"]
# Check if candle matches our interval and pair
if candle_data["interval"] == TIMEFRAME and candle_data["symbol"] == PAIR:
start_time = candle_data["t"]
close_price = float(candle_data["c"])
if current_candle_time != start_time:
# New candle started, finalize the previous candle
if current_candle_time:
# Output the last known close price for the completed candle
completed_candle = candles[-1] if candles else {"timestamp": current_candle_time, "close": close_price}
print(f"Completed Candle Timestamp: {completed_candle['timestamp']}, Close: {completed_candle['close']}")
# Start tracking the new candle
current_candle_time = start_time
new_candle = {
"open": float(candle_data["o"]),
"close": close_price,
"high": float(candle_data["h"]),
"low": float(candle_data["l"]),
"volume": float(candle_data["q"]), # total transaction volume
"timestamp": start_time
}
candles.append(new_candle)
# Keep only the last 10 candles for analysis
if len(candles) > 10:
candles.pop(0)
analyze_candles()
else:
# Update the close price for the current candle's ongoing updates
candles[-1]["close"] = close_price
# Main function to connect to the MEXC WebSocket
def main():
ws = create_connection(MEXC_WS_URL)
# Subscribe to 1-minute kline data for the chosen pair
ws.send(json.dumps({
"method": "sub.kline",
"param": {
"symbol": PAIR,
"interval": TIMEFRAME
}
}))
try:
while True:
message = ws.recv()
process_message(message)
except json.JSONDecodeError:
pass
except Exception as e:
send_telegram_message(traceback.format_exc())
print(traceback.format_exc())
finally:
ws.close()
if __name__ == "__main__":
while True:
try:
main()
except Exception:
print(traceback.format_exc())
send_telegram_message(traceback.format_exc())
Explanation:
current_candle_time != start_time: Detects when a new candle period starts. This triggers finalization of the previous candle by outputting its closing price.
candles[-1]["close"] = close_price: Handles ongoing updates to the current candle by updating its closing price.
Output: Each completed candle now outputs its timestamp and last close price right when the new candle interval begins. This ensures the previous candle's final close price is captured and used for analysis.
This approach ensures accurate tracking of the close prices for each complete 1-minute candle, aligning with your program's requirements for continuous monitoring and analysis.