-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_bot.py
More file actions
193 lines (164 loc) · 6.92 KB
/
run_bot.py
File metadata and controls
193 lines (164 loc) · 6.92 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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
"""
PocketPine test bot — connects transpiled PineScript strategy to PocketOption
via BinaryOptionsToolsV2's subscribe_symbol_timed.
Usage:
python run_bot.py --ssid YOUR_SSID
python run_bot.py --ssid YOUR_SSID --asset EURUSD_otc --timeframe 60 --amount 1.0
python run_bot.py --ssid YOUR_SSID --pine my_strategy.pine
python run_bot.py --ssid YOUR_SSID --dry-run # no real trades
"""
import asyncio
import argparse
import logging
import os
from datetime import timedelta
from BinaryOptionsToolsV2.pocketoption import PocketOptionAsync
from pocketpine.strategy import Strategy, Bars
from pocketpine.signal_parser import Signal, Action
logger = logging.getLogger("pocketpine.bot")
async def run_bot(
ssid: str,
strategy: Strategy,
asset: str = "EURUSD_otc",
timeframe: int = 5,
history_bars: int = 200,
amount: float = 1.0,
duration: int = 5,
dry_run: bool = False,
check_win: bool = True,
):
# ── Connect ──
logger.info("Connecting to PocketOption...")
api = PocketOptionAsync(ssid)
await asyncio.sleep(5)
balance = await api.balance()
logger.info(f"Connected. Balance: {balance}")
try:
payout = await api.payout(asset)
logger.info(f"Payout for {asset}: {payout}%")
except Exception:
logger.warning(f"Could not fetch payout for {asset}")
# ── Load history ──
history_seconds = timeframe * history_bars
logger.info(f"Loading {history_bars} bars of history...")
try:
candles = await api.get_candles(asset, timeframe, history_seconds)
if candles:
logger.info(f"Candle sample keys: {list(candles[0].keys()) if isinstance(candles[0], dict) else type(candles[0])}")
logger.info(f"First candle: {candles[0]}")
strategy.warmup(candles)
logger.info(f"Warmed up with {len(candles)} historical bars")
else:
logger.warning("No historical candles returned")
except Exception as e:
logger.error(f"Failed to load history: {e}")
# ── Subscribe to live candles ──
logger.info(f"Subscribing to {asset} candles (period={timeframe}s)...")
stream = await api.subscribe_symbol_timed(
asset, timedelta(seconds=timeframe)
)
trade_count = 0
win_count = 0
loss_count = 0
logger.info("Live stream started. Watching for signals...")
first_candle = True
async for candle in stream:
if first_candle:
logger.info(f"Live candle sample: {candle}")
first_candle = False
signal = strategy.on_bar(candle)
if not signal:
continue
trade_count += 1
action_str = "BUY" if signal.action == Action.BUY else "SELL"
logger.info(f"[#{trade_count}] SIGNAL: {action_str} {asset} ${amount} for {duration}s")
if dry_run:
logger.info(f"[#{trade_count}] DRY RUN — skipping trade execution")
continue
try:
if signal.action == Action.BUY:
trade_id, _ = await api.buy(
asset=asset, amount=amount, time=duration, check_win=False
)
else:
trade_id, _ = await api.sell(
asset=asset, amount=amount, time=duration, check_win=False
)
logger.info(f"[#{trade_count}] Trade placed: id={trade_id}")
if check_win:
result = await api.check_win(trade_id)
outcome = result.get("result", "unknown")
if outcome == "win":
win_count += 1
else:
loss_count += 1
logger.info(
f"[#{trade_count}] Result: {outcome} "
f"(W:{win_count} L:{loss_count} Total:{trade_count})"
)
except Exception as e:
logger.error(f"[#{trade_count}] Trade failed: {e}")
def load_strategy(args) -> Strategy:
"""Load strategy from --pine file or default test_strategy.py."""
pine_file = args.pine
if pine_file:
from pocketpine.pine_parser import PineTranspiler
t = PineTranspiler()
code = t.transpile_file(pine_file)
out_path = pine_file.rsplit(".", 1)[0] + "_strategy.py"
with open(out_path, "w", encoding="utf-8") as f:
f.write(code)
logger.info(f"Transpiled → {out_path}")
else:
out_path = "test_strategy.py"
if not os.path.exists(out_path):
raise FileNotFoundError(
"No test_strategy.py found. Use --pine to transpile a .pine file first."
)
code = open(out_path, encoding="utf-8").read()
ns = {}
exec(compile(code, out_path, "exec"), ns)
for obj in ns.values():
if isinstance(obj, type) and issubclass(obj, Strategy) and obj is not Strategy:
return obj(asset=args.asset, amount=args.amount, duration=args.duration)
raise RuntimeError("No Strategy subclass found in transpiled output")
def main():
parser = argparse.ArgumentParser(description="PocketPine Bot")
parser.add_argument("--ssid", type=str, default=os.environ.get("POCKETPINE_SSID", ""),
help="PocketOption SSID (or set POCKETPINE_SSID)")
parser.add_argument("--ssid-file", type=str, default="ssid.txt",
help="File containing SSID (default: ssid.txt)")
parser.add_argument("--pine", type=str, help="Path to .pine file (transpiles automatically)")
parser.add_argument("--asset", type=str, default="EURUSD_otc")
parser.add_argument("--timeframe", type=int, default=5, help="Candle period in seconds")
parser.add_argument("--history", type=int, default=200, help="Bars of history to load")
parser.add_argument("--amount", type=float, default=5.0, help="Trade amount")
parser.add_argument("--duration", type=int, default=5, help="Trade duration in seconds")
parser.add_argument("--dry-run", action="store_true", help="Log signals without trading")
parser.add_argument("--no-check-win", action="store_true", help="Don't wait for results")
args = parser.parse_args()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt="%H:%M:%S",
)
if not args.ssid and os.path.exists(args.ssid_file):
args.ssid = open(args.ssid_file, encoding="utf-8").read().strip()
logger.info(f"SSID loaded from {args.ssid_file}")
if not args.ssid:
args.ssid = input("Enter your PocketOption SSID: ").strip()
strategy = load_strategy(args)
logger.info(f"Strategy loaded: {type(strategy).__name__} ({len(strategy.p)} params)")
asyncio.run(run_bot(
ssid=args.ssid,
strategy=strategy,
asset=args.asset,
timeframe=args.timeframe,
history_bars=args.history,
amount=args.amount,
duration=args.duration,
dry_run=args.dry_run,
check_win=not args.no_check_win,
))
if __name__ == "__main__":
main()