본문 바로가기
category/BybitAPI 자동 매매

Bybit API ema cross 자동 매매 with python-2

by 자운대고라니 2023. 2. 20.
반응형

수수료 20% 할인 bybit 추천인 링크 : https://www.bybit.com/invite?ref=7R9MO

수수료 20% 할인 bybit 추천인 코드 : 7R9MO

해당 링크로 가입 시 저에게 소정의 커미션이 들어옵니다.

 

이 글은 투자를 권유하는 것이 아닙니다. 손해의 책임은 본인에게 있습니다.

 

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
import pandas as pd
import datetime
import requests
import time
import calendar
from pybit import HTTP
from datetime import datetime, timedelta, timezone
 
from requests.api import post
 
apiKey = '내 Api Key'
apiSecret = '내 Secret Key'
#symbol to be traded
symbol = 'XRPUSDT'
 
query_kilne = 'https://api.bybit.com/public/linear/kline?symbol=' # USDT
# query_kilne = 'https://api.bybit.com/v2/public/kline/list?symbol=' # USD
latest_infoSymbol = 'https://api.bybit.com/v2/public/tickers?symbol='
 
#candle in minutes
tick_interval  = '1'
 
#quantity to be traded in USD
qty1 = 10
 
opt=0
while True:
    bybitticker=symbol
 
    now = datetime.utcnow()
    unixtime = calendar.timegm(now.utctimetuple())
    since = unixtime
 
    start=str(since-60*60*int(tick_interval))
    url = query_kilne+bybitticker+'&interval='+tick_interval+'&from='+str(start)
    data = requests.get(url).json()
    D = pd.DataFrame(data['result'])
 
    marketprice = latest_infoSymbol + symbol
    res = requests.get(marketprice)
    data = res.json()
    lastprice = float(data['result'][0]['last_price'])
 
    price = lastprice
    df = D['close']
 
    ma9 = df.rolling(window=9).mean()
    ma26 = df.rolling(window=26).mean()
 
    test1=ma9.iloc[-2]-ma26.iloc[-2]
    test2=ma9.iloc[-1]-ma26.iloc[-1]
 
    session = HTTP(
        endpoint = 'https://api.bybit.com/',
        api_key=apiKey,
        api_secret = apiSecret)
 
    positionsize=session.my_position(symbol=symbol)['result'][0]['size']
    if session.my_position(symbol=symbol)['result'][0]['side']=='Sell':
        positionsize=positionsize*-1
        
        lastprice = float(session.latest_information_for_symbol(symbol=symbol)['result'][0]['last_price'])
    call='None'
    try:
        if test1>0 and test2<0:
            time.sleep(55)
            if test1>0 and test2<0:
                if positionsize>0:
                    print('skip')
                    time.sleep(2)
                    continue
                call = 'Dead Cross'
                qty = qty1
                if positionsize<0:
                    qty=qty1+abs(positionsize)
 
                if opt == 0:
                    opt = 1
 
                    print(session.place_active_order(
                            symbol=bybitticker,
                            side='Sell',
                            order_type='Market',
                            qty=qty1,
                            time_in_force="GoodTillCancel",
                            reduce_only=True,
                            close_on_trigger=False
                        ))
 
                    print(session.place_active_order(
                            symbol=bybitticker,
                            side='Sell',
                            order_type='Market',
                            qty=qty1,
                            time_in_force="GoodTillCancel",
                            reduce_only=False,
                            close_on_trigger=False
                        ))    
 
        if test1<0 and test2>0:
            time.sleep(55)
            if test1<0 and test2>0:
                if positionsize<0:
                    print('skip')
                    time.sleep(2)
                    continue
                call='Golden Cross'
                qty=qty1
 
                if positionsize > 0:
                    qty=qty1+abs(positionsize)
                if opt == 1:
                    opt = 0
                    print(session.place_active_order(
                        symbol=bybitticker,
                        side='Buy',
                        order_type='Market',
                        qty=qty1,
                        time_in_force="GoodTillCancel",
                        reduce_only=False,
                        close_on_trigger=False
                    ))
 
                    print(session.place_active_order(
                        symbol=bybitticker,
                        side='Buy',
                        order_type='Market',
                        qty=qty1,
                        time_in_force="GoodTillCancel",
                        reduce_only=True,
                        close_on_trigger=False
                    ))
 
 
    except:
        pass
 
    print('Name: ', bybitticker)
    print('Date: ', now)
    print('price: ', lastprice)
    print('MA 9: ', round(ma9.iloc[-1],2))
    print('MA 26: ', round(ma26.iloc[-1],2))
    print('Golden Cross/Dead Cross: ', call)
    print('opt: ', opt)
    print('')
 
    time.sleep(2)
cs

 

참고자료 : https://limetimeline.tistory.com/433

 

 

 

반응형

댓글