Repository navigation
Expand file tree
/
Copy pathexample6_chart_types.py
More file actions
152 lines (117 loc) · 4.93 KB
/
Copy pathexample6_chart_types.py
File metadata and controls
152 lines (117 loc) · 4.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#!/usr/bin/env python3
"""
Example 6: HeikinAshi Chart Type
Demonstrates how to use HeikinAshi chart type for smoother price action analysis.
"""
import asyncio
from TradingView import Client, ChartSession
async def main():
print("=== Example 6: HeikinAshi Chart Type ===")
# Create client
client = Client(debug=False)
# Set up event handlers
def on_connect():
print("✅ Connected to TradingView WebSocket")
def on_login(data):
print("✅ Successfully logged in")
def on_error(error):
print(f"❌ Error: {error}")
def on_close():
print("🔌 Connection closed")
# Register event handlers
client.on_connected(on_connect)
client.on_logged(on_login)
client.on_error(on_error)
client.on_disconnected(on_close)
# Connect to TradingView
print("🔗 Connecting to TradingView...")
await client.connect()
# Wait a moment for connection to establish
await asyncio.sleep(2)
print("✅ Ready to create chart sessions")
# Example 1: Regular Candlestick Chart (baseline)
print("\n📊 Creating regular candlestick chart for BTCUSD...")
session1 = ChartSession(client)
def on_candlestick_update(data):
if 'periods' in data and data['periods']:
latest = data['periods'][0]
print(f"Regular Candlestick - Time: {latest['time']}, Open: {latest['open']}, Close: {latest['close']}, High: {latest['max']}, Low: {latest['min']}")
def on_candlestick_error(*args):
print(f"❌ Candlestick error: {args}")
session1.on_update(on_candlestick_update)
session1.on_error(on_candlestick_error)
# Regular candlestick chart
session1.set_market("BINANCE:BTCUSD", {
'timeframe': '5', # 5-minute candles
'range': 5
})
# Wait for initial data
await asyncio.sleep(3)
# Example 2: HeikinAshi Chart
print("\n📊 Creating HeikinAshi chart for BTCUSD...")
session2 = ChartSession(client)
def on_heikinashi_update(data):
if 'periods' in data and data['periods']:
latest = data['periods'][0]
print(f"HeikinAshi - Time: {latest['time']}, Open: {latest['open']}, Close: {latest['close']}, High: {latest['max']}, Low: {latest['min']}")
def on_heikinashi_error(*args):
print(f"❌ HeikinAshi error: {args}")
session2.on_update(on_heikinashi_update)
session2.on_error(on_heikinashi_error)
# HeikinAshi chart type
session2.set_market("BINANCE:BTCUSD", {
'timeframe': '5', # 5-minute
'range': 5,
'type': 'HeikinAshi'
})
# Wait for initial data
await asyncio.sleep(3)
# Example 3: HeikinAshi Chart with Different Symbol
print("\n📊 Creating HeikinAshi chart for ETHUSD...")
session3 = ChartSession(client)
def on_eth_heikinashi_update(data):
if 'periods' in data and data['periods']:
latest = data['periods'][0]
print(f"ETH HeikinAshi - Time: {latest['time']}, Open: {latest['open']}, Close: {latest['close']}, High: {latest['max']}, Low: {latest['min']}")
def on_eth_heikinashi_error(*args):
print(f"❌ ETH HeikinAshi error: {args}")
session3.on_update(on_eth_heikinashi_update)
session3.on_error(on_eth_heikinashi_error)
# HeikinAshi chart for ETH
session3.set_market("BINANCE:ETHUSD", {
'timeframe': '15', # 15-minute
'range': 3,
'type': 'HeikinAshi'
})
# Wait for initial data
await asyncio.sleep(3)
# Keep sessions alive to receive data
print("\n⏳ Receiving data from different chart types...")
print(" Compare regular candlesticks vs HeikinAshi smoothed data")
print(" Press Ctrl+C to stop...")
try:
# Run for a reasonable time to see differences
for i in range(30): # Run for about 1 minute
await asyncio.sleep(2)
if i % 10 == 0:
print(f"\n--- {i//10 + 1}/3: Still monitoring chart types ---")
except KeyboardInterrupt:
print("\n🛑 Stopping data reception...")
# Cleanup
print("\n🔔 Unsubscribing from all chart sessions...")
session1.unsubscribe()
session2.unsubscribe()
session3.unsubscribe()
print("🔌 Disconnecting...")
client.disconnect()
print("✅ HeikinAshi chart example completed!")
print("\n📝 Summary:")
print(" - Regular candlesticks show raw OHLC data")
print(" - HeikinAshi smooths price action using modified OHLC calculations:")
print(" • HA Close = (Open + High + Low + Close) / 4")
print(" • HA Open = (Previous HA Open + Previous HA Close) / 2")
print(" • HA High = Max(High, HA Open, HA Close)")
print(" • HA Low = Min(Low, HA Open, HA Close)")
print(" - HeikinAshi helps identify trends and reduces market noise")
if __name__ == "__main__":
asyncio.run(main())