All Downloads are FREE. Search and download functionalities are using the official Maven repository.

estonlabs.cxtl.exchanges.mexc.spot.v3.MEXCStreamFactory Maven / Gradle / Ivy

There is a newer version: 1.4.14
Show newest version
package estonlabs.cxtl.exchanges.mexc.spot.v3;

import estonlabs.cxtl.common.AbstractStreamFactory;
import estonlabs.cxtl.common.auth.Credentials;
import estonlabs.cxtl.common.codec.Codec;
import estonlabs.cxtl.common.codec.JacksonCodec;
import estonlabs.cxtl.common.stream.core.WebsocketConnection;
import estonlabs.cxtl.exchanges.a.specification.domain.Exchange;
import estonlabs.cxtl.exchanges.mexc.spot.v3.domain.WSListenKey;
import estonlabs.cxtl.exchanges.mexc.spot.v3.domain.enums.WSMethod;
import lombok.NonNull;
import lombok.SneakyThrows;

import java.net.URI;
import java.util.concurrent.TimeUnit;

public class MEXCStreamFactory extends AbstractStreamFactory {

    public static final URI PROD = URI.create("wss://wbs.mexc.com/ws");

    public static final MEXCOutboundMessage PING = new MEXCOutboundMessage().setMethod(WSMethod.PING);

    private static final Codec CODEC = new JacksonCodec();

    private URI baseUri;
    private MEXCCex cex;

    public MEXCStreamFactory(URI baseUri) {
        super(Exchange.MEXC, CODEC, MEXCInboundContainer.class);
        this.baseUri = baseUri;
        staleWindow(TimeUnit.SECONDS.toMillis(30));
        ping(TimeUnit.MINUTES.toMillis(1), () -> PING);
    }

    @Override
    protected MEXCStreamFactory me() {
        return this;
    }

    public MEXCStreamFactory cex(MEXCCex cex) {
        this.cex = cex;
        return this;
    }

    public WebsocketConnection createPublicStream() {
        return newPublicWebsocket(baseUri, null);
    }

    @SneakyThrows
    public WebsocketConnection createPrivateStream(@NonNull Credentials credentials, long timestamp) {
        if(cex == null){
            throw new IllegalStateException("A MEXCCex must be set to create a private websocket for MEXC");
        }

        WSListenKey listenKey = cex.createListenKey(credentials, timestamp).block();
        if(listenKey == null || listenKey.getListenKey() == null){
            throw new IllegalStateException("Could not get a listen key for MEXC");
        }

//        ping(TimeUnit.MINUTES.toMillis(60), ()->{
//            cex.refreshListenKey(credentials).subscribe();
//        },false);

        URI uriWithKey = new URI(
                baseUri.getScheme(),
                baseUri.getUserInfo(),
                baseUri.getHost(),
                baseUri.getPort(),
                baseUri.getPath(),
                "listenKey=" + listenKey.getListenKey(),
                baseUri.getFragment()
        );
        return newPrivateWebsocket(uriWithKey, null);
    }
}