반응형
안녕하세요 여러분~ 크리에이트 메이커 입니다.
요즘 코인 자동 매매 소스코드가 많이 있어서 저도 문서보고 공부하면서 짠 코드를 공유하려고 합니다.
이것저것 하느라 좀 섞여서 보기 불편 할 수도 있는데, 잘 보시면 핵심인 부분만 골라서 쓰시면 됩니다.
사실 좀더 깔끔하고, 복붙하면 바로 되는 코드가 있지만, 의뢰를 받고 작성한 것이라 전체 공개를 해버리면 의뢰자 분입장에서 손해를 볼 수 잇기 때문에 일부 핵심적인 부분만 공개하겠습니다.
import pprint
import requests
import ccxt
import datetime
import pandas as pd
import os
import time
import sys
import json
from prettytable import PrettyTable
from binance_d import RequestClient
from binance_d.constant.test import *
from binance_d.base.printobject import *
from binance_d.model.constant import *
import binance
from binance.client import Client
from RequestClient.RestRequestClient import RestRequestClient, ResponseError
flag_short = 0
flag_long = 0
flag_time_short = 0
flag_time_long = 0
short_time = 0
long_time = 0
short_id = ""
long_id = ""
first_long_buy_id = ""
position_long = ""
first_short_buy_id = ""
position_short = ""
def Start_Future_Margin():
global flag_short
global flag_long
global flag_time_short
global flag_time_long
global short_id
global long_id
global first_long_buy_id
global position_long
global first_short_buy_id
global position_short
try:
binance_api = '공개키'
binance_secret = '비밀키'
request_client = RequestClient(api_key=binance_api, secret_key=binance_secret)
client = Client(binance_api, binance_secret)
infos = client.futures_position_information(symbol='BTCUSDT')
datelog = datetime.datetime.now().date()
logf = sys.stdout
sys.stdout = open('log' + str(datelog) + '.txt', 'a+')
print("루프 시작 ==================================")
print(datetime.datetime.now())
print("현재 계좌 정보")
pprint.pprint(infos)
try:
print("포지션 : "+infos[1]['positionSide'])
print("마진 :" +infos[1]['isolatedMargin'])
print("지갑 : "+infos[1]['isolatedWallet'])
print("포지션 : " + infos[2]['positionSide'])
print("마진 :" + infos[2]['isolatedMargin'])
print("지갑 : " + infos[2]['isolatedWallet'])
long_sub = float(infos[1]['isolatedMargin']) - float(infos[1]['isolatedWallet'])
long_pnl = long_sub/float(infos[1]['isolatedWallet'])*100
short_sub=float(infos[2]['isolatedMargin']) - float(infos[2]['isolatedWallet'])
short_pnl = short_sub / float(infos[2]['isolatedWallet']) * 100
print("롱포 수익률 : "+str(long_pnl))
print("숏포 수익률 : "+str(short_pnl))
long_pre_amount = float(infos[1]['positionAmt'])
short_pre_amount = -float(infos[2]['positionAmt'])
print("롱 소유량 "+ str(long_pre_amount))
print("숏 소유량 "+ str(short_pre_amount))
except:
print("숏, 롱 둘중하나 아직 매수 없음")
sys.stdout.close()
sys.stdout = logf
binance = ccxt.binance(config={
'apiKey': '공개키',
'secret': '비밀키',
'enableRateLimit': True,
'options': {
'defaultType': 'future'
}
})
btc_ohlcv = binance.fetch_ohlcv(
symbol="BTCUSDT",
timeframe='1m',
since=None,
limit=2
)
df = pd.DataFrame(btc_ohlcv, columns=['datetime', 'open', 'high', 'low', 'close', 'volume'])
df['datetime'] = pd.to_datetime(df['datetime'], unit='ms')
df.set_index('datetime', inplace=True)
logf = sys.stdout
sys.stdout = open('log' + str(datelog) + '.txt', 'a+')
print("자유로운 돈 : " + str(ihave))
print("갖고있는 코인 : " + str(mycoin))
print("시가 : " + str(price_open))
print("종가 : " + str(price_close))
sys.stdout.close()
sys.stdout = logf
# 포지션 조회
balance = binance.fetch_balance()
positions = balance['info']['positions']
# 래버리지 설정 #만약 웹페이지에서 로그인 한 상태에서 레버리지를 설정하고 있다면 해당 코드의 레버리지 적용은 무시됩니다.
markets = binance.load_markets()
symbol = "BTC/USDT"
market = binance.market(symbol)
leverage = 10
resp = binance.fapiPrivate_post_leverage({
'symbol': market['id'],
'leverage': leverage
})
logf = sys.stdout
sys.stdout = open('log' + str(datelog) + '.txt', 'a+')
buy_time_plus = datetime.datetime.now().second
print("종가 - 시가 : " + str(price_margin))
amount1 = 0
if (30 / ((price_close) + 2)) > 0.001:
amount1 = 30 / ((price_close) + 2)
else:
amount1 = 0.001
print("어마운트 : "+str(amount1) )
amount1 = round(amount1,3)
order = client.futures_create_order(symbol='BTCUSDT', side='BUY', positionSide='LONG',
type='LIMIT', price=price_close + 2, timeInForce='GTC',
quantity=amount1)
print("루프 종료 ==================================")
sys.stdout.close()
sys.stdout = logf
except:
print("binance or ccxt connect fail !!!")
time.sleep(5)
# 끝끝
코드를 자세히 보시면 선물 지갑의 각각의 수익률을 구하는 공식도 있습니다.
바이낸스, ccxt에서 수익률 자체를 알려주는 api가 없기 때문에 직접 계산해서 구해야 합니다.
오차율이 1퍼 정도 있지만, 코드를 다듬으면 0퍼까지 오차율을 줄일수 있습니다.
ccxt와 바이낸스 api를 이용하면 왠만한 자동 매매 기술을 구현 할 수 있습니다.....
반응형
'IT기술(코딩)' 카테고리의 다른 글
smtp 501 5.5.4 IP ADDRESS: EHLOerror how solve this error smtp 메일 송신 501 에러 해결 방법. (0) | 2022.08.15 |
---|---|
sql 트리거 쿼리문 에러 syntax 해결 방법 중 하나 (0) | 2022.08.09 |
어셈블리어 MIPS를 이용한 Mars_NS-shaft.jar 컴파일 (0) | 2022.05.09 |
ccxt 바이낸스 자동 매매 api 선물 지정가 방법좀 알려주실분. (0) | 2022.05.02 |
바이낸스 자동 매매 소스코드, ccxt 소스코드 버그? leverage에 따른 구매 금액 변동... (0) | 2022.04.22 |